/* 	Create OUAC Namespace 
----------------------------------------------------------*/
var OUAC = {
};

OUAC.addLoadEvent = function(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}

/*	OUAC.createRequestObject():

		A function of the OUAC Namespace that creates
		a new XMLHttpRequest object.
		
		returns ro, a request object.

----------------------------------------------------------*/
OUAC.createRequestObject = function(){
	var ro;

	try
	{
		ro = new XMLHttpRequest();
	}
	catch (error)
	{
		try
		{
			ro = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (error)
		{
			return false;
		}
	}

	return ro;
}

/*	OUAC.prepareSearchForm():

		A function of the OUAC Namespace that controls
		the search form field text.
				
		returns nothing.

----------------------------------------------------------*/
OUAC.prepareSearchForm = function() {
	/* Do a couple of quick checks to make sure the required DOM methods are supported */
	if (!document.getElementById) return false;
	if (!document.getElementsByTagName) return false;
	
	/* Make sure the search form exists in the DOM */
	if (!document.getElementById('searchform')) return false;
	
	var searchform = document.getElementById('searchform');
	
	//Add a variable to hold the default value of the label
	OUAC.labelText = searchform.getElementsByTagName('label')[0].lastChild.nodeValue;
	
	var searchField = searchform.getElementsByTagName('input')[0];
	
	if (searchField.value == '') {
		searchField.value = dict("SEARCH_SITE");// OUAC.labelText;
	}

	searchform.getElementsByTagName('input')[0].onfocus = function() {
		this.value = '';
	}

	searchform.getElementsByTagName('input')[0].onblur = function() {
		if (this.value == '') {
			this.value = dict("SEARCH_SITE");//OUAC.labelText;
		}
	}

}

/*	OUAC.modifyAuxNavLinks():

		A function of the OUAC Namespace that adds
		some additional markup to the links in the aux nav
		(left sidebar nav) to make them look prettier.
				
		returns nothing.

----------------------------------------------------------*/
OUAC.modifyAuxNavLinks = function() {
	if (!document.getElementById('auxnav')) return false;
	
	//Adds elements to the auxillary nav menu to display rounded corners.
	var auxnav = document.getElementById('auxnav');
	var ulObjs = auxnav.getElementsByTagName('ul');
	
	for (var i = 0; i < ulObjs.length; i++) {
	
		if (String(ulObjs[i].parentNode.className).indexOf('controls') < 0) {
			var aTags = ulObjs[i].getElementsByTagName('a');
			
			for (var x = 0; x < aTags.length; x++) {
				if (String(aTags[x].parentNode.className).indexOf('subnav') == -1) {
					//First, grab the value of the textNode, which will be the firstChild.
					var linkText = aTags[x].firstChild.nodeValue;
					
					//Remove the firstChild.
					aTags[x].removeChild(aTags[x].firstChild);
					
					//Rebuild the elements.
					var textSpan = document.createElement('span');
					textSpan.className = 'text';
					
					//Add the text into the textSpan Attribute
					var tNode = document.createTextNode(linkText);
					
					//Add the text node to the textSpan.
					textSpan.appendChild(tNode);
					
					//Add the textSpan to the anchor
					aTags[x].appendChild(textSpan);
					
					//Create 2 empty span tags with different classes, and add them to the atag
					var topSpan = document.createElement('span');
					topSpan.className = 'top';
					
					var botSpan = document.createElement('span');
					botSpan.className = 'bottom';
					
					//Append the new span elements to the aTag
					aTags[x].appendChild(topSpan);
					aTags[x].appendChild(botSpan);
				}
			}
		}
	}	
}

/*	OUAC.prepareRankingSystems():

		A function of the OUAC Namespace that adds event 
		handlers to the links in any 5-star ranking systems
		on the page.
								
		returns nothing
		
----------------------------------------------------------*/
OUAC.prepareRankingSystems = function() {
	//Find any instances of the ranking utility, but only inside the Primary layer.
	var primary = document.getElementById('primary');
	var ulTags = primary.getElementsByTagName('ul');
	
	//loop through the UL's to find the ones with a class of "ranking"
	for (var i = 0; i < ulTags.length; i++) {
		if (String(ulTags[i].className).indexOf('ranking') > -1) {
			//Grab the anchor tags in each UL item.
			var aTags = ulTags[i].getElementsByTagName('a');
			
			for (var x = 0; x < aTags.length; x++) {
				//add the event handlers to the a tags inside of each UL.
				aTags[x].onclick = function() {
				
					var currentRanking = this.parentNode.parentNode.className;
					
					currentRanking = currentRanking.replace('ranking ranking', '');
					currentRanking = parseInt(currentRanking.replace('star', ''));
									
					var selectedRanking = 0;
						
					selectedRanking = String(this.parentNode.className).substr(String(this.parentNode.className).length-1)
					
					//Check to see if the ranking has changed... if it hasn't don't bother updating anything.
					if (selectedRanking == currentRanking) {
						selectedRanking=0;
						currentRanking=0;
					}

						//Create an AJAX function call to store the ranking.
						var pcode = OUAC.getPCode(this.href);
						var comp_id = OUAC.getCompID(this.href);
	
						var http = OUAC.createRequestObject();
						http.open("GET", "/ajax-functions/program-rank-util.php?pcode="+pcode+"&comp_id="+comp_id+"&rank="+selectedRanking);
						http.onreadystatechange = function(){
							//Do nothing... so, return true
							return true;
						};
						http.send(null);
					
						//Change the parent element's class to reflect the selected rating.
						this.parentNode.parentNode.className = 'ranking'+((selectedRanking>0)?' ranking'+selectedRanking+'star':'');

						if (typeof OUAC.addRankedProgramToSidebar == 'function') {
							// Update the sidebar (this function is in the ouac-compare.js file)
							OUAC.updateColumnRankings(selectedRanking, this, currentRanking);
							//OUAC.addRankedProgramToSidebar(selectedRanking, this, currentRanking);
						}
						else {

							//Add some text to the selected star anchor, and reset the rest of the star anchor text values...
							var parentUL = this.parentNode.parentNode;
							var liTags = parentUL.getElementsByTagName('li'); 
		
							for (var y = 0; y < 5; y++) {
								var newTextValue = dict('RANK_X_OUT_OF_5');
								
								if (y+1 == selectedRanking) {
									newTextValue = dict('RANK_CURRENT')+' '+newTextValue;
								}
								
								newTextValue = newTextValue.replace('[NUMBER]', y+1);
								
								if (y+1 != 1) {
									newTextValue = newTextValue.replace('[S]', 's'); //Add plural form
								}
								else {
									newTextValue = newTextValue.replace('[S]', '');
								}
	
								
								liTags[y].getElementsByTagName('a')[0].title = newTextValue;
							}
						}
					//}

					return false;
				}
			}
		}
	}
	
}

var browser=navigator.appName;
var b_version=navigator.appVersion;
var hideGlossaryTerm=0;
var glossaryCache=new Array();

OUAC.prepareGlossaryTerms = function() {
	//Find all the links with a class of 'glossaryterm' and add event handlers for them.
	var aTags = document.getElementById('content').getElementsByTagName('a');
	
	for (var i = 0; i < aTags.length; i++) {
		if (String(aTags[i].className).indexOf('glossaryterm') > -1) {
			aTags[i].onmouseover = aTags[i].onfocus = function() {
				//Don't do anything if the glossarytermdefinition already exists.

				//Hide select boxes for now...
				if (b_version.match(/MSIE\s*6/)) {
					var selects = document.getElementsByTagName('select');
					for (var x = 0; x < selects.length; x++) {
						selects[x].style.visibility = 'hidden';
					}
				}

				if (!document.getElementById('glossarytermdefinition')) {

					hideGlossaryTerm=0;

					//Get the glossary term id (gid_#);
					var gid = String(this.href).match(/\b#gid_(\d+)\b/)[1]; //Do a regular expression match to find the value of #gid_. Array Index 1 will contain JUST the value of the match. Array index 0 gives us the entire matched pattern, which is too much information for our purposes.
					
					//Store the current position of the href object that's being activated.
					hrefPos = OUAC.getElementPosition(this);
					primaryPos = OUAC.getElementPosition(document.getElementById('primary'));
	
					if (glossaryCache["term_"+gid]) {
						//Create an element with an ID of glossarytermdefinition and position it accordingly on the page.
						var gtd = document.createElement('div');
						gtd.id = "glossarytermdefinition";							
						//gtd.style.left = (primaryPos[1])+'px'; //Set by the CSS files now.
						gtd.style.top = (hrefPos[0] - primaryPos[0] + 10)+'px';
													
						var newh5 = document.createElement('h5');
						var newtext = document.createTextNode(glossaryCache["term_"+gid].term+":");
						
						newh5.appendChild(newtext);
						
						gtd.appendChild(newh5);
						
						gtd.innerHTML += glossaryCache["term_"+gid].definition;
						
						document.getElementById('primary').appendChild(gtd);
					}
					else {

						var http = OUAC.createRequestObject();
						http.open("GET", "/ajax-functions/glossary-util.php?gid="+gid+"&lang="+curLang());
		
						http.onreadystatechange = function(){
							if ((http.readyState == 4)&&(hideGlossaryTerm==0)) {

								var glossaryTermData = eval('('+http.responseText+')');
								glossaryCache["term_"+gid]=glossaryTermData;
								
								//Create an element with an ID of glossarytermdefinition and position it accordingly on the page.
								var gtd = document.createElement('div');
								gtd.id = "glossarytermdefinition";							
								//gtd.style.left = (primaryPos[1])+'px'; //Set by the CSS files now.
								gtd.style.top = (hrefPos[0] - primaryPos[0] + 10)+'px';
															
								var newh5 = document.createElement('h5');
								var newtext = document.createTextNode(glossaryTermData.term+":");
								
								newh5.appendChild(newtext);
								
								gtd.appendChild(newh5);
								
								gtd.innerHTML += glossaryTermData.definition;
								
								document.getElementById('primary').appendChild(gtd);
							}
						};
	
						http.send(null);
					}
					//alert("top: "+hrefPos[0]+", left: "+hrefPos[1]);
				}
			};
			
			aTags[i].onmouseout = aTags[i].onblur = function() {
				if (document.getElementById('glossarytermdefinition')) {

					//Show select boxes again...
					if (b_version.match(/MSIE\s*6/)) {
						var selects = document.getElementsByTagName('select');
						for (var x = 0; x < selects.length; x++) {
							selects[x].style.visibility = '';
						}
					}
					
					var gtd = document.getElementById('glossarytermdefinition');
					
					gtd.parentNode.removeChild(gtd);
				}
				hideGlossaryTerm=1;
			};
		}
	}
	
}

OUAC.getPCode = function(hrefVal) {
	var pcode = hrefVal.match(/\bpcode=(\d+_\d+_\d+_\d+)\b/)[1]; //Do a regular expression match to find the value of pcode. Array Index 1 will contain JUST the value of the match. Array index 0 gives us the entire matched pattern, which is too much information for our purposes.

	return pcode;
}

OUAC.getCompID = function(hrefVal) {
	var comp_id = hrefVal.match(/\bcomp_id=(t?\d+)\b/)[1]; //Do a regular expression match to find the value of comp_id. Array Index 1 will contain JUST the value of the match. Array index 0 gives us the entire matched pattern, which is too much information for our purposes.

	return comp_id;
}

OUAC.getElementPosition = function(elem) {
	// gets the 'top' and 'left' positions an element (elem). 
	var curtop = 0; 
	var curleft = 0; 

	if (elem.offsetParent) { 
		while (elem.offsetParent) { 
		curtop += elem.offsetTop; 
		curleft += elem.offsetLeft; 
		elem = elem.offsetParent; 
		} 
	} 
	else { 
		if (elem.y) curtop += elem.y; 
		if (elem.x) curleft += elem.x; 
	} 

	var r=Array(); 

	r[0]=curtop; 
	r[1]=curleft; 

	return r;
}

OUAC.showLoadingNotice = function(elem) {
	//create a loading screen.
	var newDiv = document.createElement('div');
	var newTN = document.createTextNode(dict('JS_LOADING')); //Loading...
	
	newDiv.appendChild(newTN);
	newDiv.id='LoadingNotice';
	
	elem.appendChild('newDiv');
}

OUAC.hideLoadingNotice = function() {
	if (document.getElementById('LoadingNotice')) {
		document.getElementById('LoadingNotice').parentNode.removeChild(document.getElementById('LoadingNotice'));
	}
}

OUAC.isExternal = function(href) {
// tests a link to see if it's on- or off-site.

	if (
		 (href.match(/^https?:\/\//i)) &&
		 (!href.match(/electronicinfo\.ca/i)) && 
		 (!href.match(/infoelectronique\.ca/i))) {

		return 1;
	}
	return 0;
}
OUAC.newWindowLinks = function() {
// checks all the links on a page and makes ones that go off-site open in a new window/tab...

	var as=document.all? document.all.tags("A"):document.getElementsByTagName("A")
	for (i=0;i<as.length;i++) {
		src=as[i].getAttribute("href");
		if ((src!=null)&&(OUAC.isExternal(src))) {
			as[i].target="_blank";
			//alert(src);
		}
	}
}

OUAC.browser = navigator.userAgent;

//Add the init functions to the load event of the page.
OUAC.addLoadEvent(OUAC.prepareSearchForm);
OUAC.addLoadEvent(OUAC.modifyAuxNavLinks);
OUAC.addLoadEvent(OUAC.prepareGlossaryTerms);
OUAC.addLoadEvent(OUAC.prepareRankingSystems);

// Commented out because it forces all links to open in a new window in IE 6 & 7
//OUAC.addLoadEvent(OUAC.newWindowLinks);

// initialize jQuery because it's easier to deal with now...
$(document).ready(function() {
	
	// initialize behaviors on "Saved Comparisons" page...
	var os=$("table.savedcomparisons");
	if (os.length) {
		$('table.savedcomparisons input[type="checkbox"]').click(function(e) {
			// count how many check-boxes are marked, and if >=2, reveal the "combine" fields (otherwise, hide)...
			var cbs=$('table.savedcomparisons input[type="checkbox"]').filter(function(i) { return ($(this).is(":checked"))?1:0; });
			if (cbs.length>=2) {
				$('table.savedcomparisons tr.combiner').show();
			}
			else {
				$('table.savedcomparisons tr.combiner').hide();
			}
		});

	}
});

