/* ===========================================================================
 * Filename: javascript/functions.css
 * Author: Rebecca Skeers, rebecca@webmistress.com.au, www.webmistress.com.au except where noted
 * Date: 11 April 2007
 * Description: Contains JavaScript functions to enhance the Hobart Water website.
 * =========================================================================== 
 */



/* ===========================================================================
 * CONFIGURATION
 * =========================================================================== 
 */

  
/* Number of home page feature images (located in images/interface/homepage/ and named featureX.jpg) */
var numHomeImages = 1;

/* Number of background images (located in images/interface/backgrounds/ and named rhsX.jpg) */
var numBackgroundImages = 1;




/* ===========================================================================
 * SCHEDULE THE BEHAVIOURS
 * =========================================================================== 
 */

attachEventListener(window, "resize", resizePage, false);
attachEventListener(window, "load", initPage, false);
attachEventListener(window, "unload", unloadPage, false);

function initPage() 
{	
	setFromStyleCookies();
	initLinks();
	initHomepageImage();
	initNavigation();
	initBackgroundImage();
	initTables();
	initBoxes();
	initTextSizeLinks();
	tidyPage();
}

function resizePage()
{
	tidyPage();
}

function unloadPage() 
{
  	setStyleCookies();
}




/* ===========================================================================
 * THE FUNCTIONS
 * =========================================================================== 
 */


function initNavigation() 
{
	var nav = document.getElementById("navigation");
	
	if(nav != null)
	{
		var uls = getChildrenByTagName(nav,"ul");
		for (var k = 0; k < uls.length; k++)
		{
			var listItems = getChildrenByTagName(uls[k],"li");
		
			var first = 0;
			var last = listItems.length-1;

			
			for (var i=0; i<listItems.length; i++) 
			{
				if(i==first) setClass(listItems[i],"first");
				if(i==last) setClass(listItems[i],"last");
				
				colourclass = 'colour' + ((i%5)+1);
				setClass(listItems[i],colourclass);
				
				if(listItems[i].className.match("last") && listItems[i].className.match("current"))
					setClass(listItems[i],"current-last");
				
				//listItems[i].style.zIndex=1000-i*10;
				
				attachEventListener(listItems[i], "mouseover", navigationOn, false);
				attachEventListener(listItems[i], "mouseout", navigationOff, false);
				attachEventListener(listItems[i], "focus", navigationOn, false);
				attachEventListener(listItems[i], "blur", navigationOff, false);
			}
		}
	}
};



function navigationOn() 
{
	var newclass="";
	for (j=1; j<=5; j++) 
	{
		var str="colour"+j;
		if(this.className.match(str))
			newclass="col"+j+"-hover";
	}
	if(this.className == "")
		this.className="hover " + newclass;
	else
		this.className+=" hover " + newclass;
		
	//var subMenu = this.getElementsByTagName("ul");
	//if (subMenu.length > 0)
		//subMenu[0].style.marginTop = this.offsetHeight + "px";
}

function navigationOff()
{
	var newclass="";
	for (j=1; j<=5; j++) 
	{
		var str="colour"+j;
		if(this.className.match(str))
			newclass="col"+j+"-hover";
	}
	
	this.className=this.className.replace(new RegExp(" "+newclass+"\\b"), "");
	this.className=this.className.replace(new RegExp(newclass+"\\b"), "");
	
	this.className=this.className.replace(new RegExp(" hover\\b"), "");
	this.className=this.className.replace(new RegExp("hover\\b"), "");
	
	var subMenu = this.getElementsByTagName("ul");
	if (subMenu.length > 0)
		subMenu[0].style.marginTop = "0px";
}


function tidyPage()
{
	if(document.body)
	{
		if(!document.body.className.match("colourway") && !document.body.className.match("homepage"))
		{
			var colourwayRandom = Math.ceil(Math.random() * 5);
			setClass(document.body,"colourway"+colourwayRandom);
		}
	}
	
	// Set the stylesheet for smalls screens if necessary.
	var theWidth = getBrowserWidth();
	if (theWidth <= 890)
		setActiveStyleSheet("Small screen");
	else
		unsetActiveStyleSheet("Small screen");
	
	
	// Make the page height at least as big as the browser to display the background image to the bottom of the browser.
	if(document.getElementById("page"))
	{
		pageHeight = document.getElementById("page").offsetHeight;
		browserHeight = getBrowserHeight();
		if(pageHeight < browserHeight)
			document.getElementById("page").style.height=browserHeight+'px';
	}
	
	
	// Make the height of the 'weather' and 'downloads' box on the home page match.	
	if(document.body)
	{
		if(document.body.className.match("homepage"))
		{
			var divs = document.body.getElementsByTagName("div");
			var downloadsHeight = 0;
			var weatherHeight = 0;
			var downloadskey, weatherkey;
			for (var i = 0; i < divs.length; i++)
			{
				if(divs[i].className.match("downloads"))
				{
					downloadsHeight=divs[i].offsetHeight;
					downloadskey=i;
				}
				if(divs[i].className.match("sponsorship"))	
				{
					weatherHeight=divs[i].offsetHeight;
					weatherkey=i;
				}
			}
			
			if(downloadsHeight < weatherHeight)
				divs[downloadskey].style.height=(weatherHeight-2)+'px';
			else
				divs[weatherkey].style.height=(downloadsHeight-2)+'px';
		}	
	}
	
	
	// Fix up the image caption widths
	if(document.getElementById("content"))
	{
		var divs = document.getElementById("content").getElementsByTagName("div");
		for (var i = 0; i < divs.length; i++)
		{
			if(divs[i].className.match("image-left") || divs[i].className.match("image-right") || divs[i].className.match("image-block"))
			{
				var imagelist = divs[i].getElementsByTagName("img");
				if(imagelist.length>0)
				{
					divs[i].style.width = imagelist[0].width+"px";
				}
			}
			
		}
	}
	
	
	// Randomise the contours
	var contours = document.getElementById("background2");
	if(contours)
	{
		randomNumber = Math.floor(Math.random() * 100);
		contours.style.backgroundPositionX = randomNumber+"%";
	}
	
	
	// Position divider line
	var siteinfo = document.getElementById("siteinfo");
	var divider = document.getElementById("divider");
	if(siteinfo && divider)
	{
		var xpos = getRoughPosition(siteinfo,'x');
		var ypos = getRoughPosition(siteinfo,'y');
		divider.className = 'visible';
		divider.style.left=xpos + 'px';
		divider.style.top=ypos + 'px';
	}
}


function initLinks()
{
	if (!document.getElementsByTagName) 
 		return;
 		
 	var b = document.getElementsByTagName("body");
 	theBody = b[0];
 	if(theBody.className.match("popup"))
 	{
	 	is_popup=true;
 		 window.focus();
	}
 
 	var anchors = document.getElementsByTagName("a");
 	for (var i=0; i<anchors.length; i++) 
 	{
   		var anchor = anchors[i];
   		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
   		{
     		anchor.target = "_blank";
 		}	
     	else if (anchor.className.match("print")) 
     	{
        	anchor.onclick = function() 
        	{
          		printPage();
          		return false;
        	};
    	}
    	else if (anchor.className.match("window")) 
     	{
        	anchor.onclick = function() 
        	{
          		popUp(this.getAttribute("href"));
          		return false;
        	};
    	}
    	else if (anchor.className.match("file")) 
     	{
        	anchor.onclick = function() 
        	{
          		window.open(this.getAttribute("href"));
          		return false;
        	};
    	}
    	else if (anchor.className.match("close")) 
     	{
        	anchor.onclick = function() 
        	{
          		window.close();
          		return false;
        	};
    	}
 	}
}





function popUp(URL)
{
	eval("window.open('" + URL + "','windowName', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=482,height=500');");
}


function printPage() 
{
  	if (window.print)
		window.print()
	else
		alert("Sorry, your browser doesn't support the print feature. Use the File menu on your browser to select Print.");
	return false;
}

function initBackgroundImage()
{
	if(document.body)
	{
		randomNumber = Math.ceil(Math.random() * numBackgroundImages);
		setClass(document.body,"rhs"+randomNumber);
	}
};

function initHomepageImage()
{
	if(document.body)
	{
		if(document.body.className.match("homepage"))
		{
			randomNumber = Math.ceil(Math.random() * numHomeImages);
			setClass(document.body,"home-image"+randomNumber);
		}
	}
}



function initTextSizeLinks()
{
	var normal = document.getElementById("textsize-normal");
	if(normal!=null)
	{
		normal.onclick = function() 
		{
	  		unsetActiveStyleSheet("Large text");
	  		return false;
		};
	}
	
	var large = document.getElementById("textsize-large");
	if(large!=null)
	{
		large.onclick = function() 
		{
	  		setActiveStyleSheet("Large text");
	  		return false;
		};
	}
	
	var textversion = document.getElementById("text-version");
	if(textversion!=null)
	{
		textversion.onclick = function() 
		{
	  		setActiveStyleSheet("Text version");
	  		document.styleSheets[1].disabled=true;
	  		return false;
		};
	}
	
	var fullversion = document.getElementById("full-version");
	if(fullversion!=null)
	{
		fullversion.onclick = function() 
		{
	  		unsetActiveStyleSheet("Text version");
	  		document.styleSheets[1].disabled=false;
	  		return false;
		};
	}
}

function initTables()
{
	var tables = document.getElementsByTagName("table");
	for (var i = 0; i < tables.length; i++)
	{ 
		if(tables[i].className.match('data'))
		{
			var trs = tables[i].getElementsByTagName("tr");
			for (var j = 0; j < trs.length; j += 2)
				setClass(trs[j],"alt");
		}
		else if(tables[i].className.match('shaded'))
		{
			var trs = tables[i].getElementsByTagName("tr");
			for (var j = 0; j < trs.length; j++)
			{
				var tds = trs[j].getElementsByTagName("td");
				for (var k = 1; k < tds.length; k += 2)
					setClass(tds[k],"alt");
			}
		}
	}
	return true;
};


function initBoxes()
{
	var maincontent = document.getElementById("main-content");
	
	if(maincontent)
	{
		var divs = maincontent.getElementsByTagName("div");
		var j=0;
		for (var i = 0; i < divs.length; i++)
		{ 
			if(divs[i].className.match('box'))
			{
				if(j%2==1)
					setClass(divs[j],"boxalt");
				j++;
			}
		}
	}
	
	
	
	var additcontent = document.getElementById("additional-content");
	
	if(additcontent)
	{
		var divs = additcontent.getElementsByTagName("div");
		var j=0;
		for (var i = 0; i < divs.length; i++)
		{ 
			if(divs[i].className.match('box'))
			{
				if(j%2==1)
					setClass(divs[j],"boxalt");
				j++;
			}
		}
	}
	return true;
};


function setClass(el, str)
{
	if(el)
	{
		if (el.className == "")
			el.className = str;
		else
			el.className += " "+str;	
	}	
	return true;
}


function removeClass(el, str)
{
	if(el)
	{
		el.className=el.className.replace(new RegExp(" "+str+"\\b"), "");
		el.className=el.className.replace(new RegExp(str+"\\b"), "");	
	}
}


function getChildrenByTagName(target, tagName)
{
	var children = target.childNodes;
	var matching = new Array();
	
	if (children != null)
	{
		for (var i = 0; i < children.length; i++)
		{
			if (children[i].nodeName.toLowerCase() == tagName)
			{
				matching[matching.length] = children[i];
			}
		}
	}
	
	return matching;
};



/* Based upon http://alistapart.com/stories/alternate/ */
function setActiveStyleSheet(title) 
{
	var i, a;
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++) 
	{
		if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) 
		{
			if(a.getAttribute("title") == title) 
			{
				a.disabled = true;
				a.disabled = false;
			}
		}
	}
}

/* Based upon http://alistapart.com/stories/alternate/ */
function unsetActiveStyleSheet(title) 
{
	var i, a;
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++) 
	{
		if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) 
		{
			if(a.getAttribute("title") == title) 
				a.disabled = true;
		}
	}
}


/* Based upon http://alistapart.com/stories/alternate/ */
function setStyleCookies()
{
	var i, a;
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++)
	{
		if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title"))
		{
			if(a.disabled) 
				createCookie("style"+i, 'false', 365);
			else
				createCookie("style"+i, 'true', 365);
		}
	}
	return null;
}

/* Based upon http://alistapart.com/stories/alternate/ */
function setFromStyleCookies()
{
	var i, a, cookie;
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++)
	{
		if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title"))
		{
			cookie = readCookie("style"+i);
			if(cookie=='true')
			{
				a.disabled = true;
				a.disabled = false;
				
				if(a.getAttribute("title")=='Text version')
					document.styleSheets[1].disabled=true;
			}
			else 
			{
				a.disabled = true;
			}
		}
	}
}

/* Based upon http://alistapart.com/stories/alternate/ */
function createCookie(name,value,days) 
{
	if (days) 
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else 
		expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}


/* Based upon http://alistapart.com/stories/alternate/ */
function readCookie(name) 
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) 
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) 
			return c.substring(nameEQ.length,c.length);
	}
	return null;
}







/* The JavaScript Anthology - James Edwards & Cameron Adams */
function getBrowserWidth()
{
	if (window.innerWidth)
		return window.innerWidth;
	else if (document.documentElement && document.documentElement.clientWidth != 0)
		return document.documentElement.clientWidth;
	else if (document.body)
		return document.body.clientWidth;
	
	return 0;
}

/* The JavaScript Anthology - James Edwards & Cameron Adams */
function getBrowserHeight()
{
	if (window.innerHeight)
		return window.innerHeight;
	else if (document.documentElement && document.documentElement.clientHeight != 0)
		return document.documentElement.clientHeight;
	else if (document.body)
		return document.body.clientHeight;
	
	return 0;
}





/* The JavaScript Anthology - James Edwards & Cameron Adams */
function getRoughPosition(ele, dir)
{
	var pos = dir == 'x' ? ele.offsetLeft : ele.offsetTop;
	var tmp = ele.offsetParent;
	while (tmp != null)
	{
		pos += dir == 'x' ? tmp.offsetLeft : tmp.offsetTop;
		tmp = tmp.offsetParent;
	}
	return pos;
}


/* The JavaScript Anthology - James Edwards & Cameron Adams */
function attachEventListener(target, eventType, functionRef, capture)
{
	if (typeof target.addEventListener != "undefined")
	{ 
		target.addEventListener(eventType, functionRef, capture);
	}
	else if (typeof target.attachEvent != "undefined")
	{
		var functionString = eventType + functionRef;
		target["e" + functionString] = functionRef;
		target[functionString] = function(event)
		{
			if(typeof event == "undefined")
			{
				event = window.event
			};

			target["e" + functionString](event);
        };
		target.attachEvent("on" + eventType, target[functionString]);
	}
	else
	{
		eventType = "on" + eventType;

		if (typeof target[eventType] == "function")
		{
			var oldListener = target[eventType];
			target[eventType] = function()
			{
				oldListener();
				return functionRef();
			}
		}
		else
		{
			target[eventType] = functionRef;
		}
	}

	return true;
};


