/*
 * Wastewater Javascript functions
 * author: acoote
 * 
 * TODO: Comment the front page AJAX stuff. We're not 100% sure if we're even going to use it at this point,
 * so I'm not going to do work through it again until we're sure!
 * 
 * TODO: Rationalisation- do we need the IE6 PNG replacer? The holding gradient (and associated stuff)?
 * 
 */


var ReplaceString = "#topbuttons li a span, h2, h3, h4, h5, .bigbody, .rightbutton span.header, .right_quote p";

function getBackSize() {
	// Function to calculate what size background to use. Nothing too interesting!
	var targetimg;
	if (window.getWidth() <= 1024) {
		targetimg = 1024;
	}
	else if (window.getWidth() <= 1280) {
		if (window.getHeight() > 800){
			targetimg = 1600;
		} else {
			targetimg = 1280;
		}	
	}
	else if (window.getWidth() <= 1600) {
		targetimg = 1600;
	}
	else {
		targetimg = 1920;
		}
	return targetimg;
}

function setHoldingBackground() {
	// Function to set initial gradient. I've turned it off at least for now- it confuses
	// Safari and I'm not sure what use it is, really
	$E('body').setStyle("background","#757F81 url(/_images/back-hold-" + getBackSize() + ".jpg) repeat-x center bottom");
}


function setBackground() {
	targetimg = getBackSize();
	// Preloads the background- this was for use with the holding function above. It doesn't
	// really make any difference either way now, because it doesn't display until it's loaded.
	var a = new Asset.image("/_images/back-" + targetimg + "-RDay.jpg", {id: 'myImage', title: 'myImage', onload: function() {
		 $E('body').setStyle("background","#757F81 url(/_images/back-" + targetimg + "-RDay.jpg) no-repeat left bottom fixed");
		 }});
	$E('body').setStyle("height",window.getSize().y);

}
var opacityFade;
var menuFade;
// Establish what to pre-load
var addresses = new Array();
addresses[0] = "index.htm";
addresses[1] = "what/index.htm";
addresses[2] = "inthecrd/index.htm";
addresses[3] = "environment/index.htm";
addresses[4] = "media/index.htm";
addresses[5] = "contact/index.htm";

currentPanel = null;

function hasWebFonts() {
	// Detection JS for if a browser has web fonts support. Will have to be hard-coded, for now
	// just detects Safari 3.
	if (!Browser.Engine.webkit420) {
		return false;
	} else {
		return true;
	}
}


function setFrontJS() {
	//Setting the functions and opacities of the front buttons.
	buttons = $$("a[class='button']");
	for(x=0;x<buttons.length;x++) {
		buttons[x].setStyle("opacity", "0.7");
		buttons[x].set('morph', {duration: 200, transition: 'linear', link: 'cancel'});
		buttons[x].addEvent("mouseenter", function() {
			this.morph({opacity: 1});
		});
		buttons[x].addEvent("mouseleave", function() {
			this.morph({opacity: 0.7});
		})
		
		/*
		 * COMMENTED OUT FOR TESTING OTHER IDEAS
		 * buttons[x].addEvent("click", buttonclick.bindWithEvent(buttons[x]));
		 * 
		 * ADDED FOR TESTING IDEAS
		*/
		
		buttons[x].addEvent("click", splashLinkGo.bindWithEvent(buttons[x]));
		
	}
	/* COMMENTED OUT FOR TESTING OTHER IDEAS
	//Add event to top bar button
	$("topclick").addEvent("click", buttonclick.bindWithEvent(buttons[x]));
	
	//Create preloader
	$('splash').setStyle("left","920px");
	var loadingBox = new Element("div", {
		id: "loadingbox"
	});
	loadingBox.innerHTML = "loading, please wait...";
	var scrollBox = new Element("div",{
		id: "scrollbox"
	})
	scrollBox.injectInside(loadingBox);
	var scrollBit = new Element("div", {
		id:"scrollbit"
	})
	scrollBit.injectInside(scrollBox);
	loadingBox.injectInside($('frontsplash'));

	//Set up the preloads, or ignore if already done
	for (x=0; x<addresses.length; x++) {
		if ((window.location.pathname == "/" + addresses[x]) || (window.location.pathname == "/" + addresses[x].replace("index.htm",""))) {
			$('splash').id = "splash" + x;
			currentPanel = x;
		} else {
			new Ajax("/_dynamic/fetch-content.aspx?page=" + addresses[x],{method: 'get', onComplete: function(){
				receivePage(this)
			}}).request();
		}
	}
	*/
	if (hasWebFonts() == false) {
		replaceElements("h1 a, h2, .bigbody , .button span");
	}

}

function setPageJS(){

	var h1 = $('navbar').getElement("h1");
	h1.setStyle("cursor", "pointer");
	h1.addEvent("click", function() {
		document.location = "http://" + window.location.host;
	})
	$('searchterms').addEvents({
		focus: function() {
			if ($('searchterms').value == "Search the site") {
				$('searchterms').setStyles({
					"font-weight": "normal",
					"color": "#000000"
				});
				$('searchterms').value = "";
			}
			$('submitbutton').disabled = false;
		},
		blur: function() {
			if ($('searchterms').value == "") {
				$('searchterms').setStyles({
					"font-weight": "bold",
					"color": "#666666"
				});
				$('searchterms').value = "Search the site";
				$('submitbutton').disabled = true;
			}
		}
	});
	$('submitbutton').addEvents({
		mouseenter: function() {
			this.setStyle("background-image","url('/_images/search_over.gif')");
		},
		mouseleave: function() {
			this.setStyle("background-image","url('/_images/search_off.gif')");
		}
	});
	$('submitbutton').disabled = true;
	$('searchterms').value = "Search the site";
	currentfolder = "/" + String(document.location.pathname).split("/")[1] + "/";
	var slideFunc = function(){
		arguments[0].slide('in');
	};
	var showItem = function(){
		//alert(arguments[0].getSize().y)
		if (arguments[0].getSize().y <= 2 && arguments[1] == "start") {	
			arguments[0].setStyle("visibility", "visible");
		} else if (arguments[0].getSize().y <= 1 && arguments[1] == "complete") {
			arguments[0].setStyle("visibility", "hidden");
		}
	};
	//Set opacities and functions for top buttons
	buttons = $('topbuttons').getElements("li[class=button]");
	for (x = 0; x < buttons.length; x++) {
		buttons[x].id = "button" + x;
		buttons[x].getElement("a").setStyle("opacity","0.8");	
		buttons[x].getElement("ul").setStyles({
			"opacity":"0.95",
			"visibility": "hidden"
		});
		buttons[x].set("morph", {duration: 200, link: "cancel"});
		buttons[x].getElement("a").set("morph", {duration: 100, link: "cancel"});
		buttons[x].getElement("ul").set("morph", {duration: 200, link: "cancel",
		 onStart: showItem.pass([buttons[x].getElement("ul"),"start"]),
		 onComplete: showItem.pass([buttons[x].getElement("ul"),"complete"])
		 });
	//	buttons[x].getElement("ul").setStyle("display","block");
		buttons[x].addEvents({"mouseenter": function(){
				// function to show the dropdown
				this.getElement("a").morph({
					opacity: 1,
					"background-color": "#DBE7B8"
					});
				this.getElement("ul").morph({height: this.getElement("ul").getScrollSize().y})
				
			},"mouseleave": function(){
				// and hide the dropdown
				this.getElement("a").morph({
					opacity: 0.8,
					"background-color": "#FBFBEE"
					});
				this.getElement("ul").morph({height: 0})
			}
		});
		
		buttons[x].getElement("a").addEvents({
			"mouseenter": function() {
				
				this.morph({"background-color": "#DBE7B8"})
			},
			"mouseleave": function() {
				this.morph({"background-color": "#FBFBEE"})
			}
		})
		
		//Set sub-item actions
		links = buttons[x].getElements("li a");
		for (y = 0; y < links.length; y++) {
			links[y].set("morph", {duration: 100, link: "cancel"});
			links[y].addEvent("mouseenter", function(){
				this.morph({"background-color": "#99CC66"});
			});
			links[y].addEvent("mouseleave", function(){
				this.morph({"background-color": "#689259"});
			});
		}
		
		linkloc = buttons[x].getElement("a").getProperty("href").replace("http://" + document.location.host,"");
	/*	if ((linkloc != currentfolder) && ((document.referrer == "http://" + document.location.host + "/") || (document.referrer == "http://" + document.location.host))) {
			buttons[x].setStyles({
				"display": "block",
				"width": buttons[x].getSize().x,
				"height": buttons[x].getSize().y
			});
			buttons[x].getElement("a").set('slide', {
				duration: 'long',
				transition: 'bounce:out'
			});
			buttons[x].getElement("a").slide('hide');
			var slide = slideFunc.pass(buttons[x].getElement("a"));
			slide.delay((x * 70)+ 1000);
		} else {*/
			showItem.pass(buttons[x].getElement("ul"));
//		}
		
		
	}	
	
	rightContent = $$(".rightbutton");
	for (x = 0; x < rightContent.length; x++) {
		rightContent[x].setStyle("opacity","0.8");
		rightContent[x].set("morph",{duration: 200});
		rightContent[x].addEvent("mouseenter", function() {
			this.morph({opacity: 1});
		});
		rightContent[x].addEvent("mouseleave", function() {
			this.morph({opacity: 0.8});
		});
	}
	
	if (hasWebFonts() == false) {
		// Header replacement stuff
		//$$(ReplaceString).setStyle("visibility","hidden");
		
	//	CSSHead.innerHTML = ReplaceCSS;
		
		replaceElements(ReplaceString);
	}
	
	pageLinks = $$("#pagecontent a, #sidebar a");
	found = false;
	for (x=0;x<pageLinks.length;x++) {
		if (pageLinks[x].href.indexOf(".gif") > -1 ) {
			pageLinks[x].addClass("mb");
			found = true;
		}
	}
	

}

function setDocumentJS(){
	resizeContentWindow();
	window.addEvent("resize",resizeContentWindow);
	colourRows()
	handleDocumentLinks($('documentbox').getElement("ul"))
}

function colourRows() {
	var rows = $('documentbox').getElement("ul").getElements('li a');
	on = false;
	for (x=0;x<rows.length;x++) {
		if (on) {
			rows[x].setStyle("background-color","#F7F7F2");
			on = false;
		} else {
			rows[x].setStyle("background-color","#FFFFFF");
			on = true;
		}
	}

}

function handleDocumentLinks(base) {
	var folders = base.getElements(".folder a");
	for (x=0;x<folders.length;x++) {
		folders[x].addEvent('click', function(event){
			event.stop();
			
			var a = event.target;
			a.setStyle("background","url('/_images/ajax-loader.gif') no-repeat " + a.getStyle("background-position-x").toInt() + "px center")
			a.blur();
			new Request.JSON({
				url: a.href + "json.htm",
				onComplete: function(i) {
					if (i.items.length > 1) {
						var parentLi = event.target.getParent();
						var ul = new Element("ul",{
							styles: {
								"overflow": "hidden"
							}
						});
						for (x=0;x<i.items.length;x++) {
							if (i.items[x].title){
							
							var depth = 0;
							var currentNode = parentLi;
							while (currentNode != $('documentbox')) {
								if (currentNode.tagName.toLowerCase() == "ul") {
									depth++;
								}
									currentNode = currentNode.getParent();
							}
							
							var li = new Element("li", {
								"class": i.items[x].type
								
							});
							var a2 = new Element("a", {
								"href": a.href + i.items[x].href,
								styles: {
									"padding-left": 40 + (depth * 24),
									"background-position": 10 + (depth * 24) + "px center"
								}
							});
							a2.innerHTML = i.items[x].title;
							a2.injectInside(li);
							li.injectInside(ul);
							}
						}
						handleDocumentLinks(ul);
						ul.injectInside(parentLi);
						
						
						a.setStyle("background","url('/_images/folder_24_open.png') no-repeat " + (10 + ((depth - 1) * 24)) + "px center");
						ul.set("morph", {duration: 200, link: "cancel", onComplete: function(ul) {
							ul.setStyle("height","auto")
						}});
						ul.setStyle("height","0px");
						ul.morph({
							height: $(ul).getChildren('li').length * 30
						});

						colourRows();
					}
					
				}
			}).send()
		} )
	}
	var files = base.getElements(".file a");
	for (x = 0; x < files.length; x++) {
		files[x].addEvent('click', function(event){
			event.stop();
			$('doctitle').innerHTML = event.target.innerHTML;
			$('doclink').href = String(event.target.href).replace("info.htm",event.target.innerHTML + ".pdf" );
			$('intro').setStyle("display","none");
			$('fileinfo').setStyles({
				"visibility": "visible",
				"height": "auto",
				"overflow": "visible"
			});
			
		});
	}
	
}




function resizeContentWindow(){

	var height = window.getSize().y -
	$('content').getPosition().y -
	$('footer').getSize().y  -
	$('footer').getStyle("margin-top").toInt() - 
	$$('body')[0].getStyle("margin-bottom").toInt() -
	20;
	$('content').setStyle("height",height);
	$('filedetails').setStyles({
		"height": height -30,
		"margin-bottom": 0
	});
	$('documentbox').setStyle("height",
		height-
		$('documentbox').getPosition(($('content'))).y -
		$('pagecontent').getStyle("padding").toInt() 

	)
}

function receivePage(request) {
	for (x = 0; x < addresses.length; x++) {
		if ((addresses[x] == request.url.replace("/_dynamic/fetch-content.aspx?page=",""))) {
			$('frontsplash').setHTML($('frontsplash').innerHTML + request.response["text"]);
			$('splash').id = 'splash' + x;
			$('splash' + x).removeProperty("xmlns");
		}
	}
	$('scrollbit').setStyle("left",$('scrollbit').getStyle("left").toInt() + 60);
	if ($('scrollbit').getStyle("left").toInt() == 0) {
		if (hasWebFonts() == false) {
			replaceElements("h2, .bigbody");
		}
		new Fx.Style($('loadingbox'), 'opacity', {duration:600, onComplete: function() {
			$('loadingbox').remove();
			
			new Fx.Style($('splash' + currentPanel), 'left', {
				duration: 600,
				transition: Fx.Transitions.Quint.easeOut
			}).start(920,0);
		}}).start(1, 0);
	}
}


function replaceIEPNG() {
	// Grabs all PNG images and replaces them with transparent GIFs with IE-specific filter CSS
	// for the PNG. Only way to get IE6 to behave with them, but I'm not actually using any PNG
	// IMGs any more- they're all backgrounds. Can probably remove.
	var images = $$("img[src$=png]");
	for (x = 0; x < images.length; x++) {
		alert(images[x].src);
		images[x].setStyles({
			"height": images[x].getSize()["size"]["y"],
			"width": images[x].getSize()["size"]["x"],
			"filter":"progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\"" + images[x].src + "\", sizingMethod=\"crop\""
			});
		images[x].src = "_images/trans.gif";	
	}
}

var resizeTimer;
function resizeEndAction(func) {
	// This function standardises resize behaviour. In Mozilla, the resize event fires when the user
	// FINISHES resizing- in IE and Safari it keeps firing for every pixel the window is moved. Obviously
	// I don't want to fire the background resizer with every pixel, so I'm forcing it to wait until resizing
	// is complete, or at least the user stops resizing briefly.
	clearTimeout(resizeTimer);
	resizeTimer = setTimeout("setBackground()",100);
	$E('body').setStyle("height",window.getHeight());
}

function startActions() {

	// This if statement is a quick detection to see if the stylesheet is loaded- if not we're
	// probably on a hand-held device or something, where the JS actions may not work. Best to
	// disable the whole lot.
	//if ($E('body').getStyle("background-color").toUpperCase() == "#3B3B3B") {
	if (1==1) {
		window.addEvent("resize",resizeEndAction);
		/*if ($('splash')) {
		
		 * COMMENTED OUT FOR TESTING OTHER IDEAS
		 $('splash').setStyle("left", "920px"); //This is primarily for Safari- it has some weird loading bugs
			
				
			setFrontJS();
		}
		else if ($('documentbox')) {
			setPageJS();
			setDocumentJS();
		}
		else {*/
			setPageJS();
	//	}
		if (Browser.Engine.trident4) {
			// For some reason the top link isn't clickable once replaced in IE. No idea why.
			$('topclick').setStyle("cursor","pointer");
			$('topclick').addEvent("click", function(event) {
				//event.target.getElement("a").click();
			})
		}
	}
}

function replaceElements(selector) {

	// fetch all the elements that match the selector provided
	var elements = $$(selector);
	
	// the image URL
	var imgpath = "/_dynamic/dax-header.aspx";
	
	// this establishes what style attributes we are going to change, and the text that has to be wrapped
	// around the image URL for it to work. Normally, it'll be background-image and url('')
	var styleName = "background";
	var styleBegin = "url('";
	var styleEnd = "') no-repeat";
	
	// but not if we're running IE6, of course. That needs it's custom filter attribute instead.
	if (Browser.Engine.trident4) {
		styleName = "filter";
		styleBegin = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,src='";
		styleEnd = "', sizingMethod='crop')";
	}
	// Cycles through each element in the array
	for (x=0;x<elements.length;x++) {
		
		// When an element has had its text replaced, the class "replaced" is added. This stops repetition when going
		// through the page more than once. Also, the element has to be at block level, or setting height and width
		// has no effect, and the background won't show up properly.
		
		if (elements[x].hasClass("replaced") == false && elements[x].getStyle("display") == "block") {
			
			// Here we're collecting the style data that will be passed to the ASPX image generator. I'll probably
			// be adding font-weight at some point.
			size = elements[x].getStyle("font-size").toInt();
			color = elements[x].getStyle("color").replace("#", ""); // Can't add # to a URL!
			align = elements[x].getStyle("text-align");
			text = elements[x].get('html').replace("&","%26");
		//alert(text);
			//alert(escape(elements[x].get('html')))
			
			// Now we're setting the element's CSS width and height to it's current size. This way the element won't
			// change size when we reduce the font-size. The padding is taken off because it is included in MooTools'
			// getSize function, but is specified on it's own in CSS.
			w = elements[x].getSize().x - elements[x].getStyle("padding-left").toInt() - elements[x].getStyle("padding-left").toInt();
			h = elements[x].getSize().y - elements[x].getStyle("padding-top").toInt() - elements[x].getStyle("padding-bottom").toInt();
			elements[x].setStyles({
				width: w,
				height: h
			});
			
			// This is the bit that actually applies the background. Each variable is put into a URL query and sent to the
			// ASP.NET image generator.
			elements[x].setStyle(styleName,styleBegin + imgpath + "?w=" + w + "&h=" + h + "&size=" + size + "&align=" + align + "&color=" + color + "&text=" + escape(text) + styleEnd);
			
			// This bit is a specific IE hack- it doesn't like the text indentation when there are line breaks in it
			// so we take them out.
			brList = elements[x].getElements('br');
			if (brList.length > 0) {			
				for (y = 0; y < brList.length; y++) {
					brList[y].remove();
				}
			}
			
			// Adding this class serves two purposes. One, it is used above when detecting if an element has already been
			// replaced. Two, it has some specific style information: setting the text-indent to -1000px and font-size to
			// 1px. This effectively hides the text, but if you select the area, copy and paste, it's still there. Ta-da.
			elements[x].addClass("replaced");
			elements[x].setStyle("visibility","visible");
		
	
		}
	}
	$('loadingsheet').remove();
	
}

function stopLink(event) {
	  // This function stops an event from happening. It's used on various links to stop them
	  // actually changing the URL. Most commonly because it's a drop-down menu.
	  event.stop();
	  window.blur();
	  return false;
}

function splashLinkGo(event){
	//$E('body').blur();
	event.preventDefault();
	target = event.target;
	destination = null;
	while (target.tagName.toLowerCase() != "li") {
		target.blur();
		if (target.tagName.toLowerCase() == "a") {
			destination = target;
		}
		target = target.parentNode;
	}
	destination.removeEvents('click');
	destination.id = "clickThis"
	var buttonList = $('frontbuttons').getElements('li');
	var slideFunc = function(){
		arguments[0].slide('out');
	};
	for (x=0;x<buttonList.length;x++){
		link = buttonList[x].getElement("a");
		if (buttonList[x] != target) {
			buttonList[x].setStyles({
				"display": "block",
				"width": buttonList[x].getSize().x,
				"height": buttonList[x].getSize().y
			});
			link.set('slide', {
				duration: 'long',
				transition: 'bounce:out'
			});
			if (x == (buttonList.length -1) || (x == (buttonList.length -2) && buttonList[buttonList.length -1] == target)) {	
				link.set('slide', {onComplete: function() {
					if (Browser.Engine.trident) {
						setTimeout("$('clickThis').click()", 500);
					} else {
						setTimeout("window.location = '" + destination.href + "'", 500);
					}
				}})
			}
			var slide = slideFunc.pass(link);
			slide.delay(x * 70);
		} else {
			link.removeEvents('mouseleave');
		}
	}
	
	//stopLink(event);
}

function buttonclick(event) {
	
	  stopLink(event);
	  var link = event.target;
	  while (link.href == null) {
	  	//In some browsers the event will refer to the div tag, if it's clicked.
		//Need to set the reference to the href itself.
	  	link = link.parentNode;
	  }
	  var target = link.href.replace("http://" + window.location.host,"") + "index.htm";
	  for (x=0;x<addresses.length;x++) {
	  	if (("/" + addresses[x] == target) && (currentPanel != x)){
			if (x > currentPanel) {
				firstTo = -920;
				newFrom = 920;
			} else {
				firstTo = 920;
				newFrom = -920
			}
			var myElementsEffects = new Fx.Elements([$('splash' + currentPanel),$('splash' + x)], {
				transition: Fx.Transitions.Quint.easeOut,
				duration: 600
			});
			myElementsEffects.start({
			    '0': { 
			        'left': [0,firstTo]
			    },
			    '1': { 
			        'left': [newFrom,0]
			    }
			});
			currentPanel = x;
		}
	  }
	return false;
}

window.addEvent("domready",startActions);

//Safari is a pain. I have to skip the holding background or it won't work.
if (!Browser.Engine.webkit420) {
//	setHoldingBackground();
	window.addEvent("load",setBackground);
} else {
	window.addEvent("domready",setBackground);
}

if (Browser.Engine.trident4) {
	// IE specific CSS- mostly related to PNG backgrounds
	new Asset.css('/_css/ie6specific.css', {id: 'ie6', title: 'ie6', media: "screen"});
	window.addEvent("domready",replaceIEPNG);
}

if (hasWebFonts() == true) {
	// If the browser has Web Fonts capability then we load the CSS that specifies
	// the fonts.
	
	new Asset.css('/_css/css-font.css', {id: 'cssFonts', title: 'cssFonts'});
} else {
	var ReplaceCSS = "<style type=\"text/css\" id=\"loadingsheet\">" + ReplaceString + " { visibility: hidden }</style>";
		
		document.write(ReplaceCSS);
}

