var ARROW_DOWN = 40;
var ARROW_UP = 38;
var ENTER = 13;

function detectBrowser(){
	var browser = navigator.appName
	var version = ""
	
	if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
		version = new Number(RegExp.$1) // capture x.x portion and store as a number
	}
	
	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
		version = new Number(RegExp.$1) // capture x.x portion and store as a number
	}
	
	if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { //test for Opera/x.x or Opera x.x (ignoring remaining decimal places);
		version = new Number(RegExp.$1) // capture x.x portion and store as a number
	}
	
	return [browser, version];
}

function toggleSelectBoxes(toggle){
	//Hide select boxes for IE6 and below only
	var browser = detectBrowser()[0];
	var browserVersion = parseInt(detectBrowser()[1]);
	
	if (browser == 'Microsoft Internet Explorer' && browserVersion <= 6) {
		var selectBoxes = $("select");
		
		for (i = 0; i < selectBoxes.length; i++) {
			if (selectBoxes.get(i).id != "searchArea") {
				if (toggle=="hide") {
					selectBoxes.get(i).css("display", "none");
				}
				
				if (toggle=="show") {
					selectBoxes.get(i).css("display", "inline");
				}
			}
		}		
	}
}

function showPredictiveSearches(){	
	//Select boxes get in the way in some browsers to hide them out of the way
	toggleSelectBoxes('hide');
	
	//Get the x position of the start of the search box, thus predictive box will always display in same relative x position.
	var searchElemOffsetX = $('#keywords').offset().left;
	var searchElemOffsetY = $('#keywords').offset().top + $('#keywords').outerHeight();
	
	return overlib('<div id=\'predictiveSearchResults\' onmouseleave=\'toggleSelectBoxes("show")\'>&nbsp;</div>', WIDTH, 250, STICKY, MOUSEOFF, FIXX, searchElemOffsetX, FIXY, searchElemOffsetY);
}
 	
function choosePredictedSearch(predictedText){
	$('#keywords').val(predictedText);
	$('#searchForm').submit(); 
	//showSearchProgressBar('Searching', 'Searching for ' + predictedText);
}
 	
function unHighLightSingleRow(rowId){
	$('#' + rowId).removeClass('row_on');
	$('#' + rowId).addClass('row_off');
}
 	
function highLightSingleRow(rowId){
	$('#' + rowId).removeClass('row_off');
	$('#' + rowId).addClass('row_on');
	$('#keywords').val($('#' + rowId + ' .searchText').html());
}
 	
function highLightRow(rowId){
	//Loop through all childnodes and unhighlight any that are currently highlighted
	var numChildNodes = $('#predictiveSearchContainer').children().length;
	
	for (c = 0; c < numChildNodes; c++) {
		if ($('#predictiveSearchContainer').children().get(c).id) {
			if ($('#predictiveSearchContainer').children().get(c).id.indexOf('predictiveSearch_') >= 0) {
				if ($('#predictiveSearchContainer').children().get(c).className.indexOf('row_on') >= 0) {
					unHighLightSingleRow($('#predictiveSearchContainer').children().get(c).id);
				}
			}
		}
	}
	
	highLightSingleRow(rowId);
}
 	
function monitorSearchKeys(e){
	//IE Bodge
	if (window.event) {
		ke = window.event.keyCode; // IE
	}
	else {
		ke = e.which; // Firefox and everthing else decent
	}
	
	//Don't do anything if enter is hit
	if (ke != ENTER) {
		//Test to see if arrows are used, if so move between predictive fields, otherwise do ajax update
		if (ke == ARROW_DOWN || ke == ARROW_UP) {
			//Test to ensure the predictive box is present before moving through
			if ($('#predictiveSearchResults')) {
				moveBetweenSearches(ke); 
			}
		}
		else {
			showPredictiveSearches();
		
			var args = { 
				keywords: $('#keywords').val(),
				websiteId: $('#websiteId').val(),
				environment: $('#environment').val()
			};
			$.get("/wrms/asp/remotes/predictiveSearch.asp", args,
				function (data) {
					$('#predictiveSearchResults').html(data);
				}
				,"html");
		}
	}
}
 	
function moveBetweenSearches(ke){
	// Firefox treats white space between elements as text nodes, so be
	// careful to check that each node property exists first
	
	// Find all child nodes that are predictive search lines
	var numChildNodes = $('#predictiveSearchContainer').children().length;
	var numValidChildNodes = 0;
	validChildNodesArr = new Array;
	
	for (var c = 0; c < numChildNodes; c++) {
		if ($('#predictiveSearchContainer').children().get(c).id) {
			if ($('#predictiveSearchContainer').children().get(c).id.indexOf('predictiveSearch_') >= 0) {
				numValidChildNodes++;
				validChildNodesArr[validChildNodesArr.length] = c;
			}
		}
	} 	
	
	var validNodeCounter = 0;
	
	if (ke == ARROW_DOWN) {
		var newRowSet = false;
		
		//Loop through child nodes finding which is highlighted and moving onto the next
		for (var c = 0; c < numChildNodes; c++) {
			if ($('#predictiveSearchContainer').children().get(c).id) {
				if ($('#predictiveSearchContainer').children().get(c).id.indexOf('predictiveSearch_') >= 0) {
					if ($('#predictiveSearchContainer').children().get(c).className.indexOf('row_on') >= 0) {		 					
						unHighLightSingleRow($('#predictiveSearchContainer').children().get(c).id);
						
						if (validNodeCounter + 1 < numValidChildNodes){	 						
							highLightSingleRow($('#predictiveSearchContainer').children().get(validChildNodesArr[validNodeCounter + 1]).id);
						}
						
						newRowSet = true;
						break;
					}
				}
				
				validNodeCounter ++;
			}
		}
		
		//If no rows set, highlight the first child node
		if (!newRowSet) {
			highLightSingleRow($('#predictiveSearchContainer').children().get(validChildNodesArr[0]).id);
		}
	} 
	
	if (ke == ARROW_UP) {
		var newRowSet = false;
		
		//Loop through child nodes finding which is highlighted and moving onto the next
		for (var c = 0; c < numChildNodes; c++) {
			if ($('#predictiveSearchContainer').children().get(c).id) {
				if ($('#predictiveSearchContainer').children().get(c).id.indexOf('predictiveSearch_') >= 0) {
					if ($('#predictiveSearchContainer').children().get(c).className.indexOf('row_on') >= 0) {
						unHighLightSingleRow($('#predictiveSearchContainer').children().get(c).id);
						
						if (validNodeCounter - 1 >= 0) {
							highLightSingleRow($('#predictiveSearchContainer').children().get(validChildNodesArr[validNodeCounter - 1]).id);
						}
						
						newRowSet = true;
						break;
					}
				}
				
				validNodeCounter ++;
			}
		}
		
		//If no rows set, highlight the last child node
		if (!newRowSet) { 				
			highLightSingleRow($('#predictiveSearchContainer').children().get(validChildNodesArr[numValidChildNodes - 1]).id);
		}
	}
}

function closePredictiveSearchBox() {
	cClick();
	toggleSelectBoxes('show');
}
