// Globals
var W3CDOM = (document.getElementsByTagName && document.createElement);
var curZoom = 100;
var validForm = true;
var firstError;
var isOpera = navigator.userAgent.indexOf("Opera") > -1; 
var isIE = navigator.userAgent.indexOf("MSIE") > 1 && !isOpera; 
var isMoz = navigator.userAgent.indexOf("Mozilla/5.") == 0 && !isOpera;

var currentTicker, firstTicker, tickerFilter, tickerMsgs, tickerCount = 0, tickerTimeout, clockInt;

// ticker
function pauseTicker() { clearInterval(tickerTimeout); }
function resumeTicker() { tickerTimeout = setInterval(changeTicker, 6000); }

// event handlers
onload = function() { init(); }

function init()
{

	//initSiteStat();
	
	// don't run ticker code for browsers that don't support the W3C DOM
	if (!document.createElement) return false;
 
	// if (isIE) initIE();
	if (isOpera) initOpera();

	document.forms[0].onsubmit = function (){
		return validate()
	}
	
	if (document.getElementById)
	{
	    ZoomInit();
		initTickers();
		initOpeners();
		initHoverLinks();
		showSearchHighlight();	
	    // set current zoom from cookie if present
	    if (GetCookie("currentZoom") != null) {
		    curZoom = parseInt(GetCookie("currentZoom"));
		    do_Zoom();
	    }
	}
}

function initSiteStat() {
	thisHost = location.hostname.toLowerCase();
	thisPath = location.pathname.toLowerCase();
	var titleTag = document.getElementsByTagName("title")[0];
	
	if (thisPath == '/') thisPath = '/home';
	thisPath = thisPath.substr(1).replace(/\//gi,".");
	if (thisPath.charAt(thisPath.length-1)==".") thisPath = thisPath.substr(0,thisPath.length-1);
	
	// Firefox, Safari, Opera etc.
	if (titleTag.firstChild)
		if (titleTag.firstChild.nodeValue.indexOf("Error 404") > -1) thisPath = "404." + thisPath;
		
	// IE		
	if (titleTag.innerText)
		if (titleTag.innerText.indexOf("Error 404") > -1) thisPath = "404." + thisPath;
		
	thisPath="http://uk.sitestat.com/scottishexecutive/" + sitestataccount + "/s?" + thisPath + ".p&ns__t="+(new Date()).getTime();
	
	ns_0=document.referrer;
	
	ns_0=(ns_0.lastIndexOf("/")==ns_0.length-1)?ns_0.substring(ns_0.lastIndexOf("/"),0):ns_0;
	if(ns_0.length>0)thisPath+="&ns_referrer="+escape(ns_0);
		window.status = thisPath;
	if (sitestataccount != 'NONE') {
		if (document.createElement) {
			var ns_1 = document.createElement("img");
			ns_1.src=thisPath;
			ns_1.alt="";
			document.getElementById("pageHeader").appendChild(ns_1);
		} else {
			document.write("<img src=\""+thisPath+"\" width=\"1\" height=\"1\" />");
			window.status = "write - " & thisPath;
		}
	
	}
}

function initOpeners() {
	var anchorLinks = document.getElementsByTagName("a");
	for (var i=0;i<anchorLinks.length;i++)
		if (anchorLinks[i].className == 'newWin')
			anchorLinks[i].target = '_blank';
}

function initHoverLinks() {
	var anchorLinks = document.getElementsByTagName("a");
	for (var i=0;i<anchorLinks.length;i++)
		if (anchorLinks[i].className.indexOf('hover') > -1 ) {
			anchorLinks[i].onmouseover = HoverDiv;
			anchorLinks[i].onmouseout = UnHoverDiv;
		}
}

function HoverDiv(e) {
	var targ = getEventTarget(e);
	targ.parentNode.parentNode.className += ' hover';
}

function UnHoverDiv(e) {
	var targ = getEventTarget(e);
	targ.parentNode.parentNode.className = targ.parentNode.parentNode.className.replace(/ hover/gi,'');
}

function initTickers() {
	// test if ticker exists in this document
	if (!window.tickerList) tickerList = document.getElementById("tickerList");

	if (tickerList && !currentTicker && !window.opera)
	{
		// get collection of list items
		tickerMsgs = tickerList.getElementsByTagName("li");
		// current item initialises to first in list
		currentTicker = tickerMsgs[0];

		// if more than one item in list set up changing code
		if (tickerMsgs.length > 1)
		{
			// control events to pause display when mouse is over "ticker" box
			tickerList.onmouseover = pauseTicker;
			tickerList.onmouseout = setTickerTimeout = resumeTicker;
			
			// fancy effects in IE use filter effect on div containing ul
			var filterObj = currentTicker.parentNode.parentNode;
			// verify that filters are defined on div
			tickerFilter = (filterObj.filters && filterObj.filters.length > 0) ? filterObj.filters[0] : null;
			
			setTickerTimeout();

			// get all the anchors contained in the list items
			var tickerLinks = tickerList.getElementsByTagName("a");
			// cycle through collection
			for (var i=0; i<tickerLinks.length; i++)
			{
				// attach control functions to anchors focus and blur events
				tickerLinks[i].onfocus = pauseTicker;
				tickerLinks[i].onblur = resumeTicker;
				// hide all but first item
				if (i>0) tickerMsgs[i].style.display = "none";
			}
			
		}
		else
		{
			// Only one news item, no need to change ticker
			tickerMsgs[0].style.display = "block";
		}
		if (document.readyState && document.readyState=="complete") loaded = true;
	}
}
function changeTicker() {
	if (currentTicker == tickerMsgs[tickerCount]) {
		if (tickerFilter)
			tickerFilter.apply();
		currentTicker.style.display = "none";
		if (tickerFilter) {
			tickerFilter.play();
			setTimeout(changeTicker2, 1150);
		} else {
			changeTicker2();
		}
	}
}

function changeTicker2() {
	if (tickerFilter)
		tickerFilter.apply();
	tickerCount = (++tickerCount == tickerMsgs.length) ? 0 : tickerCount;
	currentTicker = tickerMsgs[tickerCount];
	currentTicker.style.display = "block";
	if (tickerFilter)
		tickerFilter.play();
}

/* http://www.kryogenix.org/code/browser/searchhi/ */
/* Modified 20021006 to fix query string parsing and add case insensitivity */

function highlightWord(node,word) {
	// Iterate into this nodes childNodes
	if (node.hasChildNodes) {
		var hi_cn;
		for (hi_cn=0;hi_cn<node.childNodes.length;hi_cn++) {
			highlightWord(node.childNodes[hi_cn],word);
		}
	}
	
	// And do this node itself
	if (node.nodeType == 3) { 
	// text node
		tempNodeVal = node.nodeValue.toLowerCase();
		tempWordVal = word.toLowerCase();
		if (tempNodeVal.indexOf(tempWordVal) != -1) {
			pn = node.parentNode;
			if (pn.className != "searchword") {
				// word has not already been highlighted!
				nv = node.nodeValue;
				ni = tempNodeVal.indexOf(tempWordVal);
				// Create a load of replacement nodes
				before = document.createTextNode(nv.substr(0,ni));
				docWordVal = nv.substr(ni,word.length);
				after = document.createTextNode(nv.substr(ni+word.length));
				hiwordtext = document.createTextNode(docWordVal);
				hiword = document.createElement("span");
				hiword.className = "searchword";
				hiword.appendChild(hiwordtext);
				pn.insertBefore(before,node);
				pn.insertBefore(hiword,node);
				pn.insertBefore(after,node);
				pn.removeChild(node);
			}
		}
	}
}

function showSearchHighlight() {
	if (!document.createElement) return;
	ref = document.referrer;
	if (ref.indexOf('?') == -1) return;
	qs = ref.substr(ref.indexOf('?')+1);
	qsa = qs.split('&');
	for (i=0;i<qsa.length;i++) {
		qsip = qsa[i].split('=');
	    if (qsip.length == 1) continue;
        if (qsip[0] == 'q' || qsip[0] == 'p' || qsip[0] == 'sClue') {
        // q= for Google; p= for Yahoo; sClue = Convera
			words = unescape(qsip[1].replace(/\+/g,' ')).split(/\s+/);
	        for (w=0;w<words.length;w++) {
				if (words[w].length > 2) {
					highlightWord(document.getElementsByTagName("body")[0],words[w]);
				}
            }
		}
	}
}

function initIE() {
	if (navigator.appVersion.indexOf('MSIE 4') > 0) return;
	var oldBodyText, newBodyText, reg;
	
	if (document.all.mainBody) {
		oldBodyText = document.all.mainBody.innerHTML;
		if (oldBodyText.indexOf("<IFRAME") > 0) return;
		reg = /<ABBR([^>]*)>([^<]*)<\/ABBR>/g;
		newBodyText = oldBodyText.replace(reg, '<ABBR $1><SPAN class=\"help\" $1>$2</SPAN></ABBR>');
		document.all.mainBody.innerHTML = newBodyText;
		
		/* attach resize event and do initial resize */
		/*IE_Resize();
		window.onresize = IE_Resize; */
	}
}

/*
function IE_Resize() {
	if (document.all.pageForm.action == '/Home') return;
	
	var cWidth = document.all.mainBody.clientWidth;
	var mClass = document.all.mainColumn.className;
	if (mClass == "noright" || mClass == "noleft") {
		if (navigator.appVersion.indexOf('MSIE 5') > 0) {
			//document.all.mainColumn.style.width = cWidth - 179;
			//document.all.mainColumn.style.overflow = "auto";
		} else {
			document.all.mainColumn.style.width = cWidth - 195;
			document.all.mainColumn.style.overflowX = "auto";
		}
	}
	if (mClass == "threecol") {
		if (navigator.appVersion.indexOf('MSIE 5') > 0) {
			//document.all.mainColumn.style.width = cWidth - 374;
			//document.all.mainColumn.style.overflow = "auto";
		} else {
			document.all.mainColumn.style.width = cWidth - 390;
			document.all.mainColumn.style.overflowX = "auto";
		}
	}		
}
*/

function initOpera() {
	if (document.all.newsTicker)
		document.all.newsTicker.style.overflow = "auto";
}

/*** Text zooming ***/
function ZoomOut() {
	if (curZoom > 70) curZoom -= 10;
	do_Zoom();
	return false;
}

function ZoomIn() {
	if (curZoom < 250) curZoom += 10;
	do_Zoom();
	return false;
}

function ZoomDefault() {
	curZoom = 100;
	do_Zoom();
	return false;
}

function ZoomTo(z) {
	curZoom = z;
	do_Zoom();
	return false;
}

function do_Zoom() {
	document.getElementsByTagName("body")[0].style.fontSize = curZoom + '%';
	document.getElementById("z1").firstChild.className = "";
	document.getElementById("z2").firstChild.className = "";
	document.getElementById("z3").firstChild.className = "";
	document.getElementById("z4").firstChild.className = "";
	
	if (curZoom == 80) document.getElementById("z1").firstChild.className = "on";
	if (curZoom == 100) document.getElementById("z2").firstChild.className = "on";
	if (curZoom == 125) document.getElementById("z3").firstChild.className = "on";
	if (curZoom == 145) document.getElementById("z4").firstChild.className = "on";
	
	SetCookie("currentZoom",curZoom,false);
}

function ZoomInit() {
    var bc = document.getElementById("breadcrumbsStrip");
    var ul = bc.getElementsByTagName("ul")[0];
    // alert(ul.innerHTML);
    
    var ts = document.createElement("li");
    var tst = document.createTextNode("Text size:");
    ts.appendChild(tst);
    
    var first = ul.firstChild;
    
    ul.insertBefore(ts, first);
    
    // Create zoom elements
    ul.insertBefore(CreateZoomElement(80, "small", "z1"), first);
    ul.insertBefore(CreateZoomElement(100, "normal", "z2"), first);
    ul.insertBefore(CreateZoomElement(125, "large", "z3"), first);
    ul.insertBefore(CreateZoomElement(145, "largest", "z4"), first);
    
}

function CreateZoomElement(scale, label, id) {
    var z = document.createElement("li");
    z.id = id;
    var a = document.createElement("a");
    a.onclick = function() { return ZoomTo(scale); }
    a.href= "#ZoomTo" + scale + "Percent";
    a.title = "Text size " + label;
    var t1 = document.createTextNode("A");
    var t2 = document.createTextNode(" (" + label + ")");
    var t3 = document.createTextNode(" ");
    var sp = document.createElement("span")
    sp.className = "textOnly";
    a.appendChild(t1);
    a.appendChild(sp);
    sp.appendChild(t2);
    z.appendChild(a);
    z.appendChild(t3);

    return z;
}

function GetCookie(sName) {
	var aCookie = document.cookie.split("; ");
	for (var i=0; i < aCookie.length; i++) {
		var aCrumb = aCookie[i].split("=");
		if (sName == aCrumb[0]) 
			return unescape(aCrumb[1]);
	}
	return null;
}

function SetCookie(sName, sValue, isSession) {
	if (!isSession) {
		date = new Date(2010,12,31);
		document.cookie = sName + "=" + escape(sValue) + "; path=/; expires=" + date.toGMTString();
	} else {
		document.cookie = sName + "=" + escape(sValue) + "; path=/;";
	}
}

function getEventTarget(e) {
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	// defeat Safari bug
	if (targ.nodeType == 3) 
		targ = targ.parentNode;
	return targ;
}


/******* FORMS ********/
// modified from Quirksmode example
// may need to hide code from IE Mac
function validate() {
	validForm = true;
	errorstring = '';
	firstError = null;
	
	var x = document.forms[0].elements;
	for (var i=0;i<x.length;i++)
	{
		if (x[i].className.indexOf("required") > -1)
		{
			// Ordinary text box
			if (!x[i].value && x[i].type=='text')
				writeError(x[i]);
				
			// Multiline text box
			if (x[i].tagName.toLowerCase() == 'textarea' && !x[i].value)
				writeError(x[i]);
			
			//alert(x[i].tagName);
			// Dropdown list
			if (x[i].tagName.toLowerCase() == 'select') {
				if (x[i].selectedIndex < 1)
					writeError(x[i]);
				if (x[i].selectedIndex > 0)
					if (x[i].options[x[i].selectedIndex].value == '')
						writeError(x[i]);
			}
		}
		
		// Validate email fields
		if ((x[i].className.indexOf("Email") > -1)  && (!x[i].value.match(/^(([a-z0-9_\-]+)\.)*[a-z0-9_\-]+@(([a-z0-9_\-]+)\.)+[a-z0-9_\-]+$/i)))
		{
			if (x[i].value)
				writeInvalid(x[i],"not a valid email address format");
		}
		
		// Validate number fields
		if ((x[i].className.indexOf("Number") > -1) && (x[i].value))
		{
			if (x[i].value) {
				var num = parseFloat(x[i].value);
				//alert(isNaN(num));
				if (isNaN(num))
					writeInvalid(x[i], "not a valid number")
				else {
					// check for range limit
					if (document.getElementById(x[i].parentNode.id + "_Min")) {
						var minValue = parseFloat(document.getElementById(x[i].parentNode.id + "_Min").value);
						var maxValue = parseFloat(document.getElementById(x[i].parentNode.id + "_Max").value);
						if (num < minValue || maxValue < num) {
							writeInvalid(x[i], "Value must be between " + minValue + " and " + maxValue);
						}
					}
				}
			}
		}
		
		// Validate Date fields
		if (x[i].className.indexOf("Date") > -1)
		{
			if (x[i].value) {
				var dt = Date.parse(x[i].value);
				if (isNaN(dt))
					writeInvalid(x[i],"invalid date format")
				else {
					// check for range limit
					if (document.getElementById(x[i].parentNode.id + "_Min")) {
						var minValue = new Date(document.getElementById(x[i].parentNode.id + "_Min").value);
						var maxValue = new Date(document.getElementById(x[i].parentNode.id + "_Max").value);
						dt = new Date(x[i].value);
						//alert(minValue);
						//alert(dt);
						//alert(dt < minValue);
						//alert(maxValue < dt);
						if (dt < minValue || maxValue < dt) {
							writeInvalid(x[i], "Value must be between " + minValue.toGMTString().substring(5,16) + " and " + maxValue.toGMTString().substring(5,16));
						}
					}
				}
			}

		}
	}
	
	// required Checkboxlist or Radiobuttonlist
	x = document.getElementsByTagName("fieldset");
	for (var i=0;i<x.length;i++) {
		if (x[i].className.indexOf("required") > -1)
		{
			var selectedIndex = -1;
			
			// step through all child input controls
			var fx = x[i].getElementsByTagName("input");
			for (var j=0;j<fx.length;j++) {
				if (fx[j].checked)
					selectedIndex = j;
			}
			
			// check if we failed to find a selected item
			if (selectedIndex == -1) {
				writeError(x[i]);
			}	
		}
	}
	
	if (!W3CDOM)
		alert(errorstring);
	
	if (firstError)
		firstError.focus();
	
	return validForm;
}

function writeInvalid(obj, msg)
{
	if (validForm)
		firstError = obj;
	validForm = false;

	if (obj.hasError)
		return;
	
	if (W3CDOM)
	{
		obj.className += ' error';
		obj.onchange = removeError;
		var sp = document.createElement('span');
		sp.className = 'error';
		sp.appendChild(document.createTextNode(msg));
		obj.parentNode.appendChild(sp);
		obj.hasError = sp;
	}
	else
	{
		errorstring += obj.name + ': ' + message + '\n';
		obj.hasError = true;
	}
}

function writeError(obj)
{
	//if (obj.tagName == 'fieldset') return;

	if (validForm)
		firstError = obj;
	validForm = false;

	if (obj.hasError)
		return;
	
	if (W3CDOM)
	{
		message="required";
		if (document.getElementById(obj.parentNode.id + "_errMsg"))
			message =document.getElementById(obj.parentNode.id + "_errMsg").value;
		obj.className += ' error';
		obj.onchange = removeError;
		var sp = document.createElement('span');
		sp.className = 'error';
		sp.appendChild(document.createTextNode(message));
		obj.parentNode.appendChild(sp);
		obj.hasError = sp;
	}
	else
	{
		errorstring += obj.name + ': ' + message + '\n';
		obj.hasError = true;
	}
}

function removeError()
{
	this.className = this.className.substring(0,this.className.lastIndexOf(' '));
	this.parentNode.removeChild(this.hasError);
	this.hasError = null;
	this.onchange = null;
}

function clickButton(e, buttonid){ 
      var bt = document.getElementById(buttonid); 
      if (typeof bt == 'object'){ 
            if(navigator.appName.indexOf("Netscape")>(-1)){ 
                  if (e.keyCode == 13){ 
                        bt.click(); 
                        return false; 
                  } 
            } 
            if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1)){ 
                  if (event.keyCode == 13){ 
                        bt.click(); 
                        return false; 
                  } 
            } 
      }
} 