/********************************************************
*														*
*	WRITTEN BY: DAVE HARDING							*
*	DATE:		NOV. 2005								*
*	FOR:		OSLER, HOSKIN & HARCOURT, LLP.			*
*														*
*	DEPENDANCIES:										*
*		people.js - A DYNAMICALLY GENERATED LIST		*
*			OF NAMES IN LAST NAME, FIRST NAME			*
*			AND FIRST NAME, LAST NAME FORMAT.			*
*														*
*		style.css - A STYLE DEFINITION CALLED:			*
*			"peopleSearchOver", "peopleSearch"			*
*														*
*	SOME DIAGNOSTIC CODE IS COMMENTED OUT				*
*														*
********************************************************/		
		
	/****************************
	*	INITIALIZATIONS
	****************************/
	
		/*For Debugging purposes
		DON'T FORGET TO SET TO FALSE
		BEFORE GOING INTO PRODUCTION*/
		var DEBUG = false;
		
		//Keeps track of where the cursor is 
		var currentResult	= 0;
		
		//Keeps track of which cursor key is pressed
		var keyMode;
		
		//Name of the text search box
		var txtBox = 'people_name';
		
		//Name of the results box
		var results_box = 'fillBox';
		
		//iFrame used to cover select boxes
		//and other active x content from
		//DHTML menus
		var iFrame_name		= 'frmOverlay'
		
		/*Length the search value has to be
			before search will be performed*/
		var searchLookup_Num = 2;
		
		/*The input box where the user is 
		typing in their search keyword*/
		var searchBox;
		
		/*
			Boolean whether or not to run init
		*/
		var init_complete = false;
		
		//Set the onclick and onkeyup eventhandlers
		document.onclick = clearFillBox;
		
		document.onreadystatechange = init;
		
	/************************************************************************
	*	Variables for translation lookup									*
	*	Go here to find the character codes:								*
	*	http://webdesign.about.com/od/charactersets/l/bl_htmlcodes.htm		*
	*************************************************************************/
	
		var tran_A = '[' + unescape('%E0%E1%E2%E3%E4') + '\]';
		var tran_E = '[' + unescape('%E8%E9%EA%EB') + '\]';
		var tran_C = '[' + unescape('%E7') + '\]';
		var tran_I = '[' + unescape('%EC%ED%EE%EF') + '\]';
		var tran_O = '[' + unescape('%F2%F3%F4%F5%F6') + '\]';
		var tran_U = '[' + unescape('%F9%FA%FB%FC') + '\]';
		
		var myReg_A = new RegExp(tran_A,"gm");
		var myReg_E = new RegExp(tran_E,"gm");
		var myReg_C = new RegExp(tran_C,"gm");
		var myReg_I = new RegExp(tran_I,"gm");
		var myReg_O = new RegExp(tran_O,"gm");
		var myReg_U = new RegExp(tran_U,"gm");
		
		
	
	/****************************
	*	FUNCTIONS
	****************************/
			
		/*
			Performs search on names based on textbox value.
			Apostrophes really played hell with the display
			of the results, so it's best to use the escaped
			version of the array value.
			Same goes with single quotes.
			I also used the string builder because concatonating
			strings is an expensive operation, especiallly 
			when looping through thousands of results each 
			key press.
		*/
		/*
			Preps objects needed in the
			search functions and on the
			html page
			TODO: pull fillbox code into
			getFillBox() function
		*/
		function init()
		{
			if(document.readyState == 'complete')
			{
				if(init_complete == false)
				{
					var search_box	= getSearchBox();
					var iFrame		
					var fillBox		= document.getElementById(results_box);
					if(search_box && fillBox)
					{
						createIFrame();
						iFrame					= document.getElementById(iFrame_name);
						fillBox.style.top		= findPosY(search_box) + search_box.offsetHeight + 3;
						fillBox.style.left		= findPosX(search_box);
						
						iFrame.style.display	= 'None';
						iFrame.style.position	= 'absolute';
						iFrame.style.top		= fillBox.style.top;
						iFrame.style.left		= fillBox.style.left;
						init_complete = true;
					}
				}
			}
		}
		function createIFrame()
		{
			var _body = document.getElementsByTagName("body")[0];
			var _iframe = document.createElement("iframe");
			_iframe.setAttribute("id","frmOverlay");
			_iframe.setAttribute("src","javascript:false;");
			_body.appendChild(_iframe);
			
		}
		//Get the real X position of an object
		function findPosX(obj)
		{
			var curleft = 0;
			if (obj.offsetParent)
			{
				while (obj.offsetParent)
				{
					curleft += obj.offsetLeft
					obj = obj.offsetParent;
				}
			}
			else if (obj.x)
				curleft += obj.x;
			return curleft;
		}
		//Get the real Y position of an object
		function findPosY(obj)
		{
			var curtop = 0;
			if (obj.offsetParent)
			{
				while (obj.offsetParent)
				{
					curtop += obj.offsetTop
					obj = obj.offsetParent;
				}
			}
			else if (obj.y)
				curtop += obj.y;
			return curtop;
		}
		/*
			Gets a reference for the text box
		*/
		function getSearchBox()
		{
			var arrSearch = document.getElementsByTagName('input');
			for(k=0;k<arrSearch.length;k++)
			{
				if(arrSearch[k].id.toLowerCase().indexOf(txtBox) >= 0)
				{
					return arrSearch[k];
				}
			}
			return null;
		}
		function setIFrame(fillBox)
		{
			//if(iFrame == null)
			var	iFrame = document.getElementById(iFrame_name);
			if(iFrame && fillBox)
			{
				iFrame.style.height		= fillBox.offsetHeight;
				iFrame.style.width		= fillBox.offsetWidth;
				iFrame.style.zindex		= fillBox.zIndex - 1;
				iFrame.style.display	= fillBox.style.display;
			}
			else
				return false;
		}
		
		function pplSearch(evt)
		{	
			//init();	
			var fillBox			= document.getElementById(results_box);
			
			/*This populates the global variable "searchBox" so
			that cycles aren't wasted finding the input control
			everytime the user presses a key.*/
			if(searchBox == null)
			{
				searchBox = getSearchBox();
				if(searchBox == null)
				{
					if(DEBUG)
						alert('Yo, search box instance is null');
					else
						return null;
				}
			}
			var searchValue		= searchBox.value.toLowerCase();
			
			var i;
			var j;
			var results			= 0;
			var s_quote			= unescape("%27");
			var escaped_name;
			var sb = new StringBuilder();
			
			/*Check the number of characters entered
				If less than specified number, clear
				the results display box
			*/
			if(searchValue.length >= searchLookup_Num)
			{		
				if(isAcceptedKey(evt))
				{
					//results = 0;
					if(fillBox != null)
					{
						fillBox.innerHTML = '';
						fillBox.style.display = 'block';
							
						for(i = 0; i < arrName.length; i++)
						{
							escaped_name = escape(arrName[i]);
							if(translate(arrName[i].toLowerCase()).indexOf(translate(searchValue)) == 0 && searchValue.length != 0)
							{
								sb.append("<div class=\"peopleSearch\" id=\"ln_");
								sb.append(i);
								sb.append("\" onmouseover=\"this.className=");
								sb.append(s_quote);
								sb.append("peopleSearchOver");
								sb.append(s_quote);
								sb.append("\" onmouseout=\"this.className=");
								sb.append(s_quote);
								sb.append("peopleSearch");
								sb.append(s_quote);
								sb.append("\" onclick=\"setPeopleBox(");
								sb.append(s_quote);
								sb.append(escaped_name);
								sb.append(s_quote);
								sb.append(");\">");
								sb.append(arrName[i]);
								sb.append("</div>");
								results ++;
							}
						}
						//Populate the results display box
						if(sb)
						{
							fillBox.innerHTML = sb.toString();
						}
						
						/*Position the iFrame so the fillbox
						will take zIndex precedence over
						HTML select and inputs*/
						setIFrame(fillBox);
						
						//Reset the result counter
						currentResult = 0;
						if(fillBox.style.display == 'block' && results == 0)
							clearFillBox('pplSearch');
					}	
				}
			}
			else
			{
				if(fillBox.style.display == 'block' && currentResult == 0)
					clearFillBox('pplSearch');
			}
		}
		/*Uses Regular expressions to use
		English characters for comparison*/
		function translate(value)
		{		
			return value.replace(myReg_A,'a').replace(myReg_E,'e').replace(myReg_C,'c').replace(myReg_I,'i').replace(myReg_O,'o').replace(myReg_U,'u');
		}
		/*Clears the results text box*/
		function clearFillBox(fnName)
		{
			var fillBox = document.getElementById(results_box);
			if(fillBox != null)
			{
				if(fillBox.style.display == 'block')
				{
					fillBox.innerHTML = '';
					currentResult = 0;
					fillBox.style.display = 'none';
					//status = '';
					setIFrame(fillBox);
				}
			}
		}
		/*Sets the text box value to the value passed in*/
		function setPeopleBox(value)
		{
			if(searchBox)
			{
				searchBox.value = unescape(value);
				clearFillBox('setPeopleBox');
			}
		}
		function checkForCursor(e)
		{
			//event.keyCode? event.keyCode : event.charCode
			var popupEl			= document.getElementById(results_box);
			var numKey			= getKeyNum(e);
			var character		= String.fromCharCode(numKey);
			var arrList			= popupEl.childNodes;
			
			//If the popup is visisble
			if(popupEl.style.display == 'block')
			{
				//If Up cursor was pressed
				if(character == '&')
				{
					if(currentResult >= 0)
					{	
						if(keyMode == 'down')
							currentResult --;
						var oldResult = arrList[currentResult];
						if (oldResult != null)
						{
							oldResult.className = 'peopleSearch';
						}
						if(currentResult > 0)
						{	
							var newHightlightedResult = arrList[currentResult -1];
							if (newHightlightedResult != null)
							{
								newHightlightedResult.className = 'peopleSearchOver';
							}
						}
						//status = 'Result : ' + currentResult + ' ' + arrList[currentResult].innerHTML;
						currentResult --;
					}
					keyMode = 'up';
				}
				//If Right cursor was pressed
				if(character == '\'')
				{
					return false;
				}
				//If Down cursor was pressed
				if(character == '(')
				{
					if(currentResult < arrList.length)
					{
						if(keyMode == 'up')
							currentResult ++;
						var prevHighlightedResult;
						var highlightedResult;
						
						highlightedResult = arrList[currentResult];
						highlightedResult.className = 'peopleSearchOver';
						
						if(currentResult > 0)
						{
							prevHighlightedResult = arrList[currentResult -1];
							if (prevHighlightedResult != null)
								prevHighlightedResult.className = 'peopleSearch';
						}
						//status = 'Result : ' + currentResult + ' ' + arrList[currentResult].innerHTML;
						
						if(currentResult < arrList.length)
							currentResult ++;
						
						keyMode = 'down';
					}
				}
				//If Left cursor was pressed
				if(character == '%')
				{
					return false;
				}
				//If Enter key was pressed
				if(numKey == 13)
				{
					var setResultNum;
					if(keyMode == 'down')
						setResultNum = currentResult - 1;
					else
						setResultNum = currentResult;
					var setItem = arrList[setResultNum];
					if(setItem != null)
					{
						if(document.all)
							setPeopleBox(setItem.innerText);
						else
							setPeopleBox(setItem.textContent);
					}
				}
				//If escape key was pressed
				if(numKey == 27)
				{
					clearFillBox('checkForCursor');
				}
			}
			return false;
		}
		/*Tests to see if the arrow keys have been pressed*/
		function isArrowPressed(evt)
		{
			evt = (evt) ? evt : (window.event) ? event : null;
			if (evt)
			{
				var charCode = (evt.charCode) ? evt.charCode :
							((evt.keyCode) ? evt.keyCode :
							((evt.which) ? evt.which : 0));
				if (charCode == 37 || charCode == 38 || charCode == 39 || charCode == 40)
					return true;
				else
					return false;
			}
		}
		/*Checks to see if the button that was pressed was alpha-meric
			Cursor keys are not included because you dont' want a search
			performed if the user is cycling through results with the cursor*/
		function isAcceptedKey(e)
		{
			var keyNum = getKeyNum(e);
			if(keyNum >= 65 && keyNum <= 90 || keyNum == 8 || keyNum == 222)
				return true;
			else
				return false;
		}
		/*Returns the integer value of the key pressed*/
		function getKeyNum(e)
		{
			return parseInt(e.keyCode? e.keyCode : e.charCode);
		}
		function noenter(e) 
		{
			if(getKeyNum(e) == 13)
			{
				return true;
			}
			else
				return false;
		}
		/*Stops propagation of events
			when a user click on one element
			but you don't want the event going up
			to the document level*/
		function stopPropagation(e)
		{
			if (!e)
			{
				var e = window.event;
				e.cancelBubble = true;
				if (e.stopPropagation) 
					e.stopPropagation();
			}
		}
		/*String Builder Written by K.Collins*/
		// Initializes a new instance of the StringBuilder class
		// and appends the given value if supplied
		function StringBuilder(value)
		{
			this.strings = new Array("");
			this.append(value);
		}

		// Appends the given value to the end of this instance.
		StringBuilder.prototype.append = function (value)
		{
			if (value)
			{
				this.strings.push(value);
			}
		}

		// Clears the string buffer
		StringBuilder.prototype.clear = function ()
		{
			this.strings.length = 1;
		}

		// Converts this instance to a String.
		StringBuilder.prototype.toString = function ()
		{
			return this.strings.join("");
		}
