/* (CC) 2007 Eden Design 
Library javascript file

Structure of this file:         
1. Implementation of namespace:
	- Lib (Lib= Library)
2. Definition global variables
3. General functions
4. Validation functions
5. Specific functions
6. Call: Lib.addEvent(window, "unload", Lib.eventCache.flush); detach all event handlers

Be aware! No calls are made in this file; it is only a library (hence the name); one exception: window.unload
Make your function calls in the specific javascript files, in the ___.init()
	
"namespace": Lib = library */
var Lib = {};

/* global variables */
Lib.debug = false; 														//used for debugging - do not change
Lib.allowAlert = true; 													//used for debugging - do not change
Lib.safari = (navigator.userAgent.toLowerCase().indexOf("safari") != - 1);
Lib.opera = window.opera ? true : false;
Lib.ie = document.all ? true : false;
Lib.pageIsStyled = false;
Lib.selectIsClicked = false; 

Lib.selectAlternates = []; 
/* ========== CORE ============================================================================ */
//adds events to elements of the DOM
Lib.addEvent = function (obj,evt,fn) {
	if (obj.addEventListener)
		obj.addEventListener(evt,fn,false);
	else if (obj.attachEvent)
		obj.attachEvent("on"+evt,fn);
}

//removes events to elements of the DOM
Lib.removeEvent = function (obj,evt,fn) {
	if (obj.removeEventListener)
		obj.removeEventListener(evt,fn,false);
	else if (obj.detachEvent)
		obj.detachEvent("on"+evt,fn);
}

/* keeping track on all the attached events (add) and detaching them (flush)
for more documenatation see: http://novemberborn.net/javascript/event-cache */
Lib.eventCache = function(){
	try {
		var listEvents = [];
		
		/*  Implement array.push for browsers which don"t support it natively. (used in EventCache)
		Please remove this if it"s already in other code */
		if(Array.prototype.push == null){
			Array.prototype.push = function(){
				for(var i = 0; i < arguments.length; i++){
					this[this.length] = arguments[i];
		       	};
		        return this.length;
			};
		};
	     
	    return {
			listEvents : listEvents,
	     
			add : 	function(node, sEventName, fHandler, bCapture){
						listEvents.push(arguments); 
					},
	     
			flush : 	function(){
					var i, item;
					for(i = listEvents.length - 1; i >= 0; i = i - 1){
						item = listEvents[i];
	                 	Lib.removeEvent(item[0], item[1], item[2])
	                    
						item[0][item[1]] = null;
					};
			}
	      };
	} catch (ex){ Lib.errHandler(ex); }	
}();

//display alert is alert is allowed (not cancelled in confirm) and debug = true
Lib.debugAlert = function (message) {
		if(Lib.allowAlert && Lib.debug) { Lib.allowAlert = confirm(message); }
	}

//handles errors in javascript
Lib.errHandler = function (err) {
		var errorText = "";
		for (var i in err) { errorText += i + "=" + err[i] + "\n"; }
		Lib.debugAlert("An error has occured: \n\n" + errorText + "\nSee Firefox browser for correct linenumbers."); 			
		return true;	
	}	
/* ========== END CORE ====================================================================== */
	
/* ========== GENERAL FUNCTIONS ============================================================= */
//checks if all the elements with the id specified in the arguments of this function exist; return true if they do exist; false if one or more do not exist
Lib.elementsExists = function () {
	var result = true;
	for(var i=0; i< arguments.length; i++) {
		if(!document.getElementById(arguments[i])) result=false;
	}
	return result;
}

//adds stylesheet
Lib.addStyleSheet = function (relPath) {
	if(document.getElementsByTagName("head"))
	{
		var head = document.getElementsByTagName("head")[0]; 
		var newStyle = document.createElement("link");
   		newStyle.setAttribute("type", "text/css");
		newStyle.setAttribute("rel", "stylesheet"); 
		newStyle.setAttribute("href", relPath); 
		head.appendChild(newStyle);
	}
} 

//removes stylesheet
Lib.removeStyleSheet = function (stylesheetFileName) {
	if(document.getElementsByTagName("head"))
	{
		var head = document.getElementsByTagName("head")[0]; 
		var linkElements = head.getElementsByTagName("link");
		
		for(var i=0; i<linkElements.length; i++) {
			
			var href = linkElements[i].getAttribute("href");
			if( href.indexOf(stylesheetFileName) != -1) {  
				linkElements[i].disabled=true; 
				head.removeChild(linkElements[i]); 
			}			
		}		
	}	
} 

//gets next element in DOM tree
Lib.getNextElement = function ( elem ) {
    do { elem = elem.nextSibling; } 
	while ( elem && elem.nodeType != 1 );
    return elem;
}

/* 
Used to find element with certain classname
searchClass: string containing the class(es) that you are looking for 
tagName (optional, defaults to ‘*’) : An optional tag name to narrow the search to specific tags e.g. ‘a’ for links. 
containerElement (optional, defaults to document) An optional object container to search inside. Again this narrows the scope of the search */
Lib.getElementsByClassName = function (searchClass, tagName, containerElement) {
	tagName = tagName || "*";
	containerElement = containerElement || document;
	
	var allElements = containerElement.getElementsByTagName(tagName);
	if (!allElements.length &&  tagName == "*" &&  containerElement.all) allElements = containerElement.all;
	
	var elementsFound = new Array();
	var delim = searchClass.indexOf("|") != -1  ? "|" : " ";
	
	var arrClass = searchClass.split(delim);
	for (var i = 0, j = allElements.length; i < j; i++) {
		var arrObjClass = allElements[i].className.split(" ");
		if (delim == " " && arrClass.length > arrObjClass.length) { continue; }
		var c = 0;
		comparisonLoop:
			for (var k = 0, l = arrObjClass.length; k < l; k++) {
				for (var m = 0, n = arrClass.length; m < n; m++) {
					if (arrClass[m] == arrObjClass[k]) c++;
					if (( delim == "|" && c == 1) || (delim == " " && c == arrClass.length)) {
						elementsFound.push(allElements[i]);
					break comparisonLoop;
				}
			}
		}
	}
	return elementsFound;
}

Lib.inputAutoClear = function () {
	var inputFields = Lib.getElementsByClassName("text", "input");
	for (var i=0; i<inputFields.length; i++) {
		// Add a onfocus to every text input with class "text"
		// This will store the initial value for restoring it when the box stays empty when losing focus
		inputFields[i].onfocus = function() { if (!this.getAttribute("default")||this.getAttribute("default")== this.value) {this.setAttribute("default", this.value); this.value = "";} };
		Lib.eventCache.add(inputFields[i], "onfocus", function() { if (!this.getAttribute("default")||this.getAttribute("default")== this.value) {this.setAttribute("default", this.value); this.value = "";} }, false);
		
		// Add a onblur to every text input with class "text"
		// This will restore the initial value if no value is inserted
		inputFields[i].onblur = function() { if (this.value.length==0) { this.value = this.getAttribute("default")} };
		Lib.eventCache.add(inputFields[i], "onblur", function() { if (this.value.length==0) {this.value = this.getAttribute("default")} }, false);		
	}
}

Lib.getWindowWidth = function () {
	var myWidth = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth+24;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
	}
	return myWidth;
}

// get window height in pixels
Lib.getWindowHeight = function () {
	var myHeight = 0;
	if( typeof( window.innerHeight ) == 'number' ) {
		//Non-IE
		myHeight = window.innerHeight;
	} else if( document.documentElement &&  document.documentElement.clientHeight  ) {
		//IE 6+ in 'standards compliant mode'
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && document.body.clientHeight) {
		//IE 4 compatible
		myHeight = document.body.clientHeight;
	}
	return myHeight;
}

//get scrolling from top in pixels
Lib.getScrollY = function () {
  var scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;    
  }
  return scrOfY;
}

//find position of element relative to window
Lib.findElementPosition = function (obj){
	var curleft = curtop = 0;
	if (obj.offsetParent) {
	
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}


Lib.setCookie = function (name, value) {  
	var argv = Lib.setCookie.arguments;  
	var argc = Lib.setCookie.arguments.length;  
	var expires = (argc > 2) ? argv[2] : null;  
	var path = (argc > 3) ? argv[3] : null;  
	var domain = (argc > 4) ? argv[4] : null;  
	var secure = (argc > 5) ? argv[5] : false;  
	document.cookie = name + "=" + escape (value) + 
	((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + 
	((path == null) ? "" : ("; path=" + path)) +  
	((domain == null) ? "" : ("; domain=" + domain)) +    
	((secure == true) ? "; secure" : "");
}

Lib.getCookie = function (name) {
	var start = document.cookie.indexOf(name+"="); 
	var len = start+name.length+1; 
	if ((!start) && (name != document.cookie.substring(0,name.length))) { return  null; }
	if (start == -1){ return null; }
	
	var end = document.cookie.indexOf(";",len); 
	
	if (end == -1) { end = document.cookie.length; } 
	return unescape(document.cookie.substring(len,end)); 
}

Lib.querystring = function (qs) { // optionally pass a querystring to parse
	this.params = new Object();
	this.get= Lib.getQuerystring;
	
	if (qs == null) { qs=location.search.substring(1,location.search.length); }

	if (qs.length == 0) { return; }

	// Turn <plus> back to <space>
	// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&') // parse out name/value pairs separated via &
	
	// split out each name=value pair
	for (var i=0;i<args.length;i++) {
		var value;
		var pair = args[i].split('=')
		var name = unescape(pair[0])

		if (pair.length == 2)
			value = unescape(pair[1])
		else
			value = name
		
		this.params[name] = value
	}
}

Lib.getQuerystring = function (key) {
	var value=this.params[key];
	return value;
}


/* ========== END GENERAL FUNCTIONS ========================================================= */


/* ========== START VALIDATION SCRIPTS ====================================================== */

/* ========== END VALIDATION SCRIPTS ======================================================== */

/* ========== START SPECIFIC FUNCTIONS ========================================================= */
/* scaling links ------------------------------------------------------*/
Lib.addScalingLinks = function () {
	if(!Lib.elementsExists("metaLinks", "utilities")) { return; }
	
	if(Lib.pageIsStyled) {
		var ul = document.createElement("ul");
		ul.id  = "scalingLinks";
		
		for(var i=0; i<3;i++) {
			var li = document.createElement("li");
			var hyperlink = document.createElement("a");
			hyperlink.href="#";
			if(i==0) {
				hyperlink.id = "scalingNormal";
				hyperlink.title= Lib.titleScalingLinkNormal;
				hyperlink.innerHTML = "<span class=\"text-only\">" + Lib.textScalingLinkNormal + "</span>";		
				hyperlink.className = "active";		
			}
			else if(i==1) {
				hyperlink.id = "scalingLarge";
				hyperlink.title= Lib.titleScalingLinkLarge;
				hyperlink.innerHTML = "<span class=\"text-only\">" + Lib.textScalingLinkLarge + "</span>";
			}
			else if(i==2) {
				hyperlink.id = "scalingLargest";
				hyperlink.title= Lib.titleScalingLinkExtraLarge;
				hyperlink.innerHTML = "<span class=\"text-only\">" + Lib.textScalingLinkExtraLarge + "</span>";
			}
			hyperlink.onclick = function () { Lib.scaleFont(this.id, true); Lib.setAtiveScalingLink(this.id); return false; };
			Lib.eventCache.add(hyperlink, "onclick", function () { Lib.scaleFont(this.id, true); Lib.setAtiveScalingLink(this.id); return false; }, false); 			
			li.appendChild(hyperlink);	
			ul.appendChild(li);
		}
		
		var metaLinks = document.getElementById("metaLinks");
		metaLinks.parentNode.insertBefore(ul, Lib.getNextElement(metaLinks));
		 
		if(Lib.getCookie("fontsize") && Lib.getCookie("fontsize").length != 0){ 
			var cookieValue = Lib.getCookie("fontsize");
			if(cookieValue == "scalingNormal" || cookieValue == "scalingLarge" || cookieValue == "scalingLargest") {
				Lib.setAtiveScalingLink(cookieValue); 
			}
		}
	}
}

/* end scaling links ------------------------------------------------------*/	

/* Footer -----------------------------------------------------------------*/
Lib.addPrintLink = function () {
	if(!Lib.elementsExists("footer")) { return; }
	
	var footer = document.getElementById("footer");
	var ul = footer.getElementsByTagName("ul");
	var li = document.createElement("li");
	var hyperlink = document.createElement("a");
	hyperlink.innerHTML = Lib.textPrintLink;
	hyperlink.href= "#";
	hyperlink.onclick = function () { window.print(); return false; };
	Lib.eventCache.add(hyperlink, "onclick", function () {  window.print(); return false; }, false); 	
	
	li.appendChild(hyperlink);
	if(ul[0]) { ul[0].appendChild(li); }
}
		
		
Lib.positionFooter = function () {
//	if(!Lib.elementsExists("header", "main", "footer")) { return; }
//	
//	
//	if(Lib.pageIsStyled) {
//		var headerHeight = document.getElementById("header").offsetHeight;
//					
//		var main =  document.getElementById("main");
//		var mainHeight = main.offsetHeight;
//		var mainWidth = main.offsetWidth;
//		
//		var footer = document.getElementById("footer");
//		var footerHeight = footer.offsetHeight;
//		var footerWidth = footer.offsetWidth;
//		
//		var windowHeight = Lib.getWindowHeight();
//		
//		//position footer absolute if header + main height is less than windowHeight + footer height
//		if(headerHeight + mainHeight < windowHeight - footerHeight) {
//			footer.style.position = "absolute";
//			footer.style.top = windowHeight - footerHeight + 'px';
//		}
//		else { footer.style.position	= 'static';	}	
//		
//		//set footer width fixed if footer is less wide than main
//		if(footerWidth < mainWidth ) {  footer.style.width = mainWidth + "px";  }
//		else { footer.style.width = "100%";	}
//	}
	
}
/* End Footer -----------------------------------------------------------------*/

Lib.setScreenWidth = function (isHome) {
//	if(document.getElementsByTagName("body")[0].id != "locations") {
//		var allContainer = document.getElementById("allContainer");
//		var screenWidth = Lib.getWindowWidth();
//	
//		if(screenWidth <985) { allContainer.className = "small-screen"; }
//		else { allContainer.className = ""; }
//	}
}

Lib.scaleFont = function (status, removeStyleSheets) {
	if(removeStyleSheets) {
		//reset
		Lib.removeStyleSheet ("normal-font.css");
		Lib.removeStyleSheet ("large-font.css");
		Lib.removeStyleSheet ("largest-font.css");
	}
	
	if(status=="scalingNormal") { Lib.addStyleSheet("../styles/normal-font.css");  }
	else if(status=="scalingLarge") { Lib.addStyleSheet("../styles/large-font.css"); }
	else if(status=="scalingLargest") { Lib.addStyleSheet("../styles/largest-font.css"); }
	
	Lib.setCookie("fontsize", status) 
	Lib.positionFooter();		
} 

Lib.setAtiveScalingLink = function (id) {
	//reset
	document.getElementById("scalingNormal").className = "";	
	document.getElementById("scalingLarge").className = "";	
	document.getElementById("scalingLargest").className = "";	
	document.getElementById(id).className = "active";		 
} 

// replace standard dropdown boxes by style ones
Lib.selectAlternate = function () {
	if(Lib.pageIsStyled) {
		var candidates = Lib.getElementsByClassName("_dhtml-select", "select");
		for (var i=0; i<candidates.length; i++) {
			// Retrieve the required information from the original select box
			var origSelect	= candidates[i];
			var origClass	= origSelect.className.replace(" hide", "").substring(1);
	
			// Create replacement select box
			Lib.selectAlternates[Lib.selectAlternates.length]	= origSelect.getAttribute('id') + '_alt_dropdown';
			
			var selectReplace		= document.createElement('div');
			selectReplace.setAttribute('id', origSelect.getAttribute('id') + '_alt');
			selectReplace.setAttribute('orig_id', origSelect.getAttribute('id'));
			selectReplace.className		= origClass;
			selectReplace.onclick		= function() { Lib.openSelect (this); };
			Lib.eventCache.add(selectReplace, "onclick", function() { Lib.openSelect (this); }, false);		  	
									
			var selectReplaceList		= document.createElement('dl');
			var optionReplace		= document.createElement('dt');
			selectReplaceText 		= document.createTextNode(origSelect.options[0].text);
			optionReplace.appendChild(selectReplaceText);
			selectReplaceList.appendChild(optionReplace);
			selectReplace.appendChild(selectReplaceList);
	
			// Create replacement select box dropdown
			var selectReplaceOptions		= document.createElement('div');
			selectReplaceOptions.setAttribute('id', origSelect.getAttribute('id') + '_alt_dropdown');
			selectReplaceOptions.className		= origClass + '_options';
			var selectReplaceList			= document.createElement('dl');
			
			for (var j= 0; j<origSelect.options.length; j++) {
				   if (j != 0 ) { // added by Bart to hide the first 'option' from the list
	      var optionReplace		= document.createElement('dt');
				optionReplaceLink		= document.createElement('a')
				optionReplaceLink.href= "#";
				optionReplaceLink.setAttribute('position', j);
				optionReplaceLink.setAttribute('select_alt', origSelect.getAttribute('id') + '_alt');
				optionReplaceLink.setAttribute('select', origSelect.getAttribute('id'));
				optionReplaceLink.onclick	= function() { Lib.optionClick(this); return false; }; 			
				Lib.eventCache.add(optionReplaceLink, "onclick", function() { Lib.optionClick(this); return false;}, false); 		
				
				optionReplaceText 		= document.createTextNode(origSelect.options[j].text);
				
				optionReplaceLink.appendChild(optionReplaceText);
				optionReplace.appendChild(optionReplaceLink);
				selectReplaceList.appendChild(optionReplace);
				}
			}
	
			// Append the replacement selectbox to the form
			selectReplaceOptions.appendChild(selectReplaceList);
			selectReplace.appendChild(selectReplaceOptions);
			origSelect.parentNode.insertBefore(selectReplace, origSelect);			
			
			// Hide the original selectbox
			origSelect.className = "hide";
		}
		Lib.addEvent (document, "click", Lib.documentClick); 
		Lib.eventCache.add(document, "onclick", Lib.documentClick, false); 			
	}
}


Lib.documentClick = function() {
	if(!Lib.selectIsClicked) {
		var options = Lib.getElementsByClassName("dhtml-select_options", "div");  			
		for (var i=0; i<options.length; i++) {
			options[i].setAttribute('open', 'false');
			options[i].style.display = 'none';
		}
	}
	else { Lib.selectIsClicked = false; }	
}	

Lib.openSelect = function (selectReplace) {
	Lib.selectIsClicked = selectReplace.getAttribute('orig_id');
	var targetSelect	= document.getElementById(selectReplace.getAttribute('orig_id') + '_alt');
	var targetSelectDD 	= document.getElementById(selectReplace.getAttribute('orig_id') + '_alt_dropdown');
	lastClickedItem		= selectReplace.getAttribute('orig_id') + '_alt_dropdown';
	
	if (targetSelectDD.getAttribute('open') == 'true') {
		targetSelectDD.setAttribute('open', 'false');
		targetSelectDD.style.display = 'none';
		targetSelectDD.style.height = "auto";
		targetSelectDD.style.overflow = "visible";
	} 
	else {
		
		targetSelectDD.setAttribute('open', 'true');
		targetSelectDD.style.display = 'block';
		
		if(targetSelectDD.offsetHeight>200) {
			targetSelectDD.style.overflow = "auto";
			targetSelectDD.style.overflowX = "hidden";
			targetSelectDD.style.height = "200px";
			
		} 
	}
}

Lib.optionClick = function (optionReplaceLink) {
	
	document.getElementById(optionReplaceLink.getAttribute('select')).options[optionReplaceLink.getAttribute('position')].selected = "selected";
	
	if(document.getElementById(optionReplaceLink.getAttribute('select')).id.indexOf("locationFinder") != -1) {
		location.href = document.getElementById(optionReplaceLink.getAttribute('select')).options[optionReplaceLink.getAttribute('position')].value;
	}
	else {
		var newOption = document.createElement('dt');
		
		/*
		if (!optionReplaceLink.text) { var newOptionText = document.createTextNode(optionReplaceLink.childNodes[0].toString()); } 
		else { var newOptionText = document.createTextNode(optionReplaceLink.text); }
		
		newOption.appendChild(newOptionText);		
		*/
		if (!optionReplaceLink.text) { newOption.innerHTML = "<span>"+ optionReplaceLink.childNodes[0].toString() + "</span>"; } 
		else { newOption.innerHTML = "<span>"+ optionReplaceLink.text+ "</span>"; }		
		
		document.getElementById(optionReplaceLink.getAttribute('select_alt')).childNodes[0].replaceChild(newOption, document.getElementById(optionReplaceLink.getAttribute('select_alt')).childNodes[0].childNodes[0]);
	}
}

//this function changes the src attribute of any input type="image" elements
//from src="../path/to/image.gif" to src="../path/to/image-on.gif"
//the -on suffix was chosen because -hover conflicted with earlier
//naming conventions.
Lib.addImageButtonHovers = function() {
	var inputs = document.getElementsByTagName('input');
	for (var i=0;i<inputs.length;i++) {
		if (inputs[i].type == 'image') {
    		
    var origButton 	= inputs[i];
    var idleImage; //make sure the onmouseout function can access this var
    
      inputs[i].onmouseover = function()  {
        idleImage = this.getAttribute('src').split('/');
        idleImage = idleImage[idleImage.length-1];
        idleImage = idleImage.substring(0, idleImage.indexOf('.'));
        this.src	= '../images/buttons/' + idleImage + '-on.png';   
      };
		
      inputs[i].onmouseout = function()   { 
        this.src	= '../images/buttons/' + idleImage + '.png'; 
      };
		}
  } 
}

Lib.addButtonHovers = function () {
	var inputs = document.getElementsByTagName('input');
	for (var i=0;i<inputs.length;i++) {
		if (inputs[i].className == "button") {
    		inputs[i].onmouseover = function()  {  this.className = "button hover"; };
			Lib.eventCache.add(inputs[i], "onmouseover", function()  {  this.className = "button hover"; }, false); 	
			
			inputs[i].onmouseout = function()  {  this.className = "button"; };
			Lib.eventCache.add(inputs[i], "onmouseout", function()  {  this.className = "button"; }, false); 		
     	}
  	} 
}

Lib.setPageIsStyled = function () {
	if(Lib.elementsExists("utilities")) { if(parseInt(document.getElementById("utilities").offsetLeft) >100) { Lib.pageIsStyled = true; }	 }	
	if(!Lib.pageIsStyled) { Lib.removeStyleSheet ("javascript.css"); }
}



		
/* ========== END SPECIFIC FUNCTIONS ========================================================= */

//removes all eventhandlers and solves ie memory leak
Lib.addEvent(window, "unload", Lib.eventCache.flush);

