/**
 * Healthy Working Lives Slideshow Object
 *
 * Usage: 
 * var tips = initSlideshow('header','h3','includes/js/tips.xml');
 * Returns: Reference to th slideshow object attached to the HTML element specified.
 * Use header.next() or .previous(); etc.
 *
 * 'this.slides' is an array of 'slide' hashtables. 
 *
 */
 
	function slideshow(parent,titleElement,resource) {

		/* make params global */
		this.parentElement = document.getElementById(parent);
		this.titleElement = this.parentElement.getElementsByTagName(titleElement)[0];
		this.resource = resource;
		
		/* load initial slides array */
		this.slides = new Array();
		
		/* globals to store current slide */
		this.slideLocation;

	}

	slideshow.prototype.populate = function() {
		/* send xml request */
		xmlhttp=null
		slideshow = this;
		if (window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest() } 
		else if (window.ActiveXObject) { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP") }
		if (xmlhttp!=null) {
			nocache = new Date; params = "?nocache="+nocache.getTime();
			xmlhttp.onreadystatechange=function(){ slideshow.parse(slideshow); }
			xmlhttp.open('GET', this.resource+params, true);
			xmlhttp.setRequestHeader('Content-Type','text/xml'); 
			xmlhttp.send(null);
		} 
	}
	
	/* parse response */
	slideshow.prototype.parse = function() {

		if (xmlhttp.readyState==1) { 
			// show loading 
		}
		
		if (xmlhttp.readyState==4) { 
			if (xmlhttp.status==200) { 

				/* update the GUI */

					var title = xmlhttp.responseXML.getElementsByTagName("TITLE")[0].firstChild.nodeValue;
					this.titleElement.innerHTML = title;
					
					/* only load navigation if we have nav strings */
					if(xmlhttp.responseXML.getElementsByTagName("NEXT")[0].firstChild.nodeValue != "null" && xmlhttp.responseXML.getElementsByTagName("PREVIOUS")[0].firstChild.nodeValue != "null") {
						var navElement = document.createElement('UL');
						navElement.className='navigate_tips';
						
						/* create 'next' element */
						var nextElement = document.createElement('LI');
						var nextAnchor = document.createElement('A');
						nextAnchor.setAttribute("href","#");
						nextAnchor.onclick=function(){ this.parentNode.parentNode.parentNode.slideshow.next(); this.blur(); return false; }
						nextAnchor.innerHTML=xmlhttp.responseXML.getElementsByTagName("NEXT")[0].firstChild.nodeValue;
						nextElement.appendChild(nextAnchor);
						
						/* create 'previous' element */
						var previousElement = document.createElement('LI');
						var previousAnchor = document.createElement('A');
						previousAnchor.setAttribute("href","#");
						previousAnchor.onclick=function(){ this.parentNode.parentNode.parentNode.slideshow.previous(); this.blur(); return false; }
						previousAnchor.innerHTML=xmlhttp.responseXML.getElementsByTagName("PREVIOUS")[0].firstChild.nodeValue;
						previousElement.appendChild(previousAnchor);
						
						navElement.appendChild(previousElement); navElement.appendChild(nextElement); 
						this.parentElement.appendChild(navElement);
					
						nextElement.style.border="none";
					}
					
				/* load the content blocks */
				
					var tips = xmlhttp.responseXML.getElementsByTagName("SLIDE");
					for(i=0;i<tips.length;i++) {
						var slideHash = {
							"heading": xmlhttp.responseXML.getElementsByTagName("SLIDE")[i].getElementsByTagName('HEADING')[0].firstChild.nodeValue,
							"paragraph": xmlhttp.responseXML.getElementsByTagName("SLIDE")[i].getElementsByTagName('PARAGRAPH')[0].firstChild.nodeValue,
							"link": xmlhttp.responseXML.getElementsByTagName("SLIDE")[i].getElementsByTagName('LINK')[0].firstChild.nodeValue,
							"linktext": xmlhttp.responseXML.getElementsByTagName("SLIDE")[i].getElementsByTagName('LINKTEXT')[0].firstChild.nodeValue,
							"flash": xmlhttp.responseXML.getElementsByTagName("SLIDE")[i].getElementsByTagName('FLASH')[0].firstChild.nodeValue,
							"image": xmlhttp.responseXML.getElementsByTagName("SLIDE")[i].getElementsByTagName('IMAGE')[0].firstChild.nodeValue
						};
						this.slides[i] = slideHash;	
					}
					
				/* show a random content block */
				var random = Math.floor(Math.random()*i+1)
				this.jump(random);	
			}
		}
		
	}
	
	slideshow.prototype.jump = function(location) {
		if(location >= 0 && location < this.slides.length) {
			
			/* Load the first-child paragraph, then the second - if it exists in the HTML and is not NULL in the XML */
			this.parentElement.getElementsByTagName('P')[0].innerHTML = this.slides[location]["heading"];
			if(this.parentElement.getElementsByTagName('P')[1] && this.slides[location]["paragraph"] != "null") {
				this.parentElement.getElementsByTagName('P')[1].innerHTML = this.slides[location]["paragraph"];
			}
			
			/* Load the Image if not NULL in XML */
			if(this.slides[location]["image"] != "null") {
				if(document.getElementById('tip_flash').getElementsByTagName('img')[0]) {
					document.getElementById('tip_flash').getElementsByTagName('img')[0].src=this.slides[location]["image"];
				}
			}
			
			/* Load the Flash if not NULL in XML */
			if(this.slides[location]["flash"] != "null") {
				swfobject.embedSWF(this.slides[location]["flash"], "tip_flash", "149", "205", "9.0.0","","", {swliveconnect:"true"},{name:"tip_flash"});
				document.getElementById('top_tips').onmouseover=function(){ try { document.getElementById('tip_flash').Play(); } catch(e) {} };
				document.getElementById('tip_flash').onmouseover=function(){ try { document.getElementById('tip_flash').Play(); } catch(e) {} };
			} 
			
			/* Display the link, if it exists */
			if(this.slides[location]["link"] != "null" && this.slides[location]["linktext"] != "null") {
				var pars = this.parentElement.getElementsByTagName('p');
				for(i=0;i<pars.length;i++) {
					if(pars[i].className=="link") {
						pars[i].getElementsByTagName('a')[0].setAttribute("href",this.slides[location]["link"]);
						pars[i].getElementsByTagName('a')[0].innerHTML = this.slides[location]["linktext"];
					}
				}	
			}
			
			this.slideLocation = location;
		}
	}
	
	slideshow.prototype.next = function() {
		if(this.slideLocation == this.slides.length-1) {
			this.jump(0);
		} else {		
			this.jump(this.slideLocation+1);
		}
	}
	
	slideshow.prototype.previous = function() {
		if(this.slideLocation == 0) {
			this.jump(this.slides.length-1);
		} else {
			this.jump(this.slideLocation-1);
		}
	}
	
	function initSlideshow(parent,titleElement,resource) {
 		var parentElement = document.getElementById(parent);
 		try { parentElement.slideshow = new slideshow(parent,titleElement,resource); }
 		catch (e) {}
 		parentElement.slideshow.populate();
 		return parentElement.slideshow;
 	}
	
	function loadSlideshows() {
		if(document.getElementById('maincontent').className == "section section_longhazard" || (document.getElementById('maincontent').className == "gateway" && document.getElementsByTagName('body')[0].id == "advice")) {
			var top_answers = initSlideshow('top_questions','h3','/uploads/images/467-top_questions.xml');
		} else if(document.getElementsByTagName('body')[0].id == "home" && document.getElementById('maincontent').className == "homepage") {
			var top_tips = initSlideshow('top_tips','h3','/uploads/images/471-top_tips.xml');
		}
	}

	addLoadEvent(loadSlideshows);

/* Add some more arrows to the page */

	function needMoreArrows() {
		var paragraphs = document.getElementById('copy').getElementsByTagName('P');
		for (i=0; i<paragraphs.length; i++) {
			/* Replace &rarr; characters */
			if(paragraphs[i].innerHTML.search(String.fromCharCode(8594)) >= 0) {
				paragraphs[i].className="link_arrow";
				paragraphs[i].innerHTML = paragraphs[i].innerHTML.replace(String.fromCharCode(8594),"");
			}
			/* Do back-to-tops (ie6 uses uppercase for some really silly reason) */
			if(paragraphs[i].innerHTML.search('back to top</a>') >= 0 || paragraphs[i].innerHTML.search('back to top</A>') >= 0 || paragraphs[i].innerHTML.search('Back to top</a>') >= 0) {
				paragraphs[i].className="backtotop";
			}
		}
	}

/* Add rounded corners */
	
	var rounded = new Array(
		"adviceline",
		"adviceline_flat",
		"search_advice",
		"workplace_visit",
		"hazard_progs",
		"top_tips",
		"subscribe"
	);
	
	function roundBlocks() {		
		for(x=0; x<rounded.length; x++) {		
			if(document.getElementById(rounded[x])) {
				var header = document.getElementById(rounded[x]);
				var crn_tl = document.createElement('span'); crn_tl.className="crn_tl";
				var crn_tr = document.createElement('span'); crn_tr.className="crn_tr";
				var crn_br = document.createElement('span'); crn_br.className="crn_br";
				var crn_bl = document.createElement('span'); crn_bl.className="crn_bl";
				header.appendChild(crn_tl); header.appendChild(crn_tr);
				header.appendChild(crn_br); header.appendChild(crn_bl);
			}	
		}
		
		/* search forms */
		var divs = document.getElementById('maincontent').getElementsByTagName('div');
		for(p=0;p<divs.length;p++) {
			if(divs[p].className=="formpanel"){
				var crn_tl = document.createElement('span'); crn_tl.className="crn_tl";
				var crn_tr = document.createElement('span'); crn_tr.className="crn_tr";
				var crn_br = document.createElement('span'); crn_br.className="crn_br";
				var crn_bl = document.createElement('span');crn_bl.className="crn_bl";
				divs[p].appendChild(crn_tl);divs[p].appendChild(crn_tr);
				divs[p].appendChild(crn_br);divs[p].appendChild(crn_bl);
			}
		}

	}	
			
/* Break blocks of floated elements into rows */
		
	function doubleCols(breakCount,parent,element,breakClass) {
		var copyBlock = document.getElementById(parent);	
		var copyDIVs = copyBlock.getElementsByTagName(element);
		var tagCount = 0;
		for (i=0; i<copyDIVs.length; i++) {
			if (copyDIVs[i].className==breakClass) {
				tagCount++; if(tagCount == breakCount) { 
					var clear = document.createElement('span');
					clear.className="clear";
					copyBlock.insertBefore(clear,copyDIVs[i]);
					tagCount = 1; 
				}
			}
		}
	}
	
/* Add global load events */
		
	function addLoadEvent(func) {	
		var oldonload = window.onload;
		if (typeof window.onload != 'function'){
	    	window.onload = func;
		} else {
			window.onload = function(){ oldonload(); func();}
		}
	}

/*
 * Template specific styling
 * Templates are defined by the class of
 * the 'maincontent' DIV.
 */			
	
	/* =homepage */
	
		if(document.getElementById('maincontent').className == "homepage") {
			
			/* round some blocks */
			rounded[rounded.length+1] = "headings";
			
			/* animation related functions */			
			function homepage() { 
				document.getElementById('headings').onmouseover=function(){ removeFlash('headings'); } 
			}
			
			function removeFlash(element) { 
				var flashObj = document.getElementById('homepage_animation');
				document.getElementById(element).removeChild(flashObj);
				flashAlt = document.createElement('div');
				flashAlt.id="homepage_animation";
				flashImg = document.createElement('img');
				flashImg.alt="Example of Healthy Working Lives";
				flashImg.id="flash-alt";
				flashImg.src="/www.healthyworkinglives.com/images/header/flash-alts/"+flashTitle;
				flashAlt.appendChild(flashImg);
				document.getElementById(element).appendChild(flashAlt);
				flashAlt.style.visibility="visible";
				flashAlt.style.zIndex="150";
				flashImg.style.zIndex="150";
				document.getElementById('headings').onmouseover="";
			}
			
			/* create animation array */
			var homepage_animations = new Array("1-Window-Cleaner.swf",
											"2-Fitness-Instructor.swf",
											"3-Mechanic.swf",
											"4-Cyclist.swf",
											"5-Office-Desk.swf",
											"6-Vacuum-Cleaner.swf",
											"07-Ladder.swf",
											"08-Chef.swf"
										);
			
			/* display random animation */
			if(document.getElementById('homepage_animation')) {
				var random_animation = Math.floor(Math.random()*homepage_animations.length)
				var flashTitle = homepage_animations[random_animation].replace(".swf",".gif");
				document.getElementById('flash-alt').src="/www.healthyworkinglives.com/images/header/flash-alts/"+flashTitle;
				swfobject.embedSWF("/www.healthyworkinglives.com/images/flash/"+homepage_animations[random_animation], "homepage_animation", "650", "215", "9.0.0","","", {wmode:"transparent"});
			}
			
			addLoadEvent(homepage);
		}

	/* =office-hazards */
	
		if(document.getElementById('maincontent').className == "office-hazards") {
			function nonavigation(){ 
				
				document.getElementById('navigation').style.display="none";
				document.getElementById('related').style.display="none";
				document.getElementById('copyheader').style.display="none";
				document.getElementById('copy').style.width="760px";
				document.getElementById('maincontent').style.width="760px";
				document.getElementById('maincontent').style.height="760px";
				
				flashFrame = document.createElement('iframe');
				flashFrame.src="http://www.healthyworkinglives.com/healthyworkinglives-static/includes/flash/office_hazards/index.html";
				flashFrame.style.width="760px"; flashFrame.style.height="760px";
				flashFrame.style.border="0px";
				flashFrame.setAttribute("frameborder","no");
				flashFrame.setAttribute("border","0");
				flashFrame.frameBorder="no"; flashFrame.scrolling="no";
				document.getElementById('office_flash_frame').appendChild(flashFrame);
				
			}
			
			addLoadEvent(nonavigation);
	
		}

	/* =gateway */
	
		if(document.getElementById('maincontent').className == "gateway gateway_wide") {
			rounded[rounded.length+1] = "headings";
			doubleCols(4,'copy','div','divblock');
		}
		
	/* =gateway_wide */
	
		if(document.getElementById('maincontent').className == "gateway") {
			rounded[rounded.length+1] = "headings";
			doubleCols(4,'copy','div','divblock');
		}
	
	/* =section_hazardlong */
	
		if(document.getElementById('maincontent').className == "section section_longhazard") {
			rounded[rounded.length+1] = "headings";
			doubleCols(3,'copy','div','divblock');
		}
		
	/* =section || section_long || section_advice || section_hazard */
	
		if(document.getElementById('maincontent').className == "section" || document.getElementById('maincontent').className == "section section_long" || document.getElementById('maincontent').className == "section section_advice" || document.getElementById('maincontent').className == "section section_hazard") {
			rounded[rounded.length+1] = "headings";
			doubleCols(4,'copy','div','divblock');
		}
	
	/* =page */
	
		if(document.getElementById('maincontent').className == "page" || document.getElementById('maincontent').className == "page page_nested" || document.getElementById('maincontent').className == "page page_advice" || document.getElementById('maincontent').className == "page page_hazard") {
			addLoadEvent(needMoreArrows);
			if(document.getElementsByTagName('body')[0].id=="award" || document.getElementsByTagName('body')[0].id=="contact" || document.getElementsByTagName('body')[0].id=="about") {
				rounded[rounded.length+1] = "headings";
			}
		}
		
	/* =portal */
	
		if(document.getElementById('maincontent').className == "portal") {
			addLoadEvent(needMoreArrows);
		}
		
	/* =nonhsevents */
	
		if(document.getElementById('maincontent').className == "nonhsevents" || document.getElementById('maincontent').className == "wide" || document.getElementById('maincontent').className == "gateway_wide" || document.getElementById('maincontent').className == "wide document") {
			rounded[rounded.length+1] = "headings";
		}
		
	/* =violence */

		function getElementsByClassName(className, tag, elm){			
			var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
			
			var tag = tag || "*";
			var elm = elm || document;
			var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
			var returnElements = [];
			var current;
			var length = elements.length;
			for(var i=0; i<length; i++){
				current = elements[i];
				if(testClass.test(current.className)){
					returnElements.push(current);
				}
			}
			return returnElements;
		}
		
		function roundRelatedPanels()
		{
			var header = getElementsByClassName("panel", "div", document.getElementById('related'));																			
			
			var crn_tl = document.createElement('span'); crn_tl.className="crn_tl";
			var crn_tr = document.createElement('span'); crn_tr.className="crn_tr";
			var crn_br = document.createElement('span'); crn_br.className="crn_br";
			var crn_bl = document.createElement('span'); crn_bl.className="crn_bl";
				
			header[0].appendChild(crn_tl); 
			header[0].appendChild(crn_tr);
			header[0].appendChild(crn_br); 
			header[0].appendChild(crn_bl);			
		}
		
		if(document.getElementById('maincontent').className == "page page_violence") {						
			rounded[rounded.length+1] = "headings";						
			//addLoadEvent(roundRelatedPanels);
		}
		

		
/* Round some misc blocks */
		
		addLoadEvent(roundBlocks);		