var req;
var timer; 
var key;
var num;
var locale;
var serverURL;
var pauseTime;
var parameters;
var textId;
var finalDivName;
var formName;
var ALL_RESULTS_FOR = 'All Results For :'
var locationId = new Array();
currentSelectedID = 99;
maxSelectedID = 0;
var popupBoxName, textBoxName;

if(window.onresize == null){
	window.onresize = restorePopup;
}

function restorePopup(){
	if(finalDivName!=null && document.getElementById(finalDivName)!=null){
		if(document.getElementById(finalDivName).style.visibility=="visible"){
			hidePopup();
			showPopup();
		}	
	}
}

//initialize the XMLHttpRequest object
if (window.XMLHttpRequest) {
	req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
	req = new ActiveXObject("Microsoft.XMLHTTP");
}

function initPopup(tBox, popupBox){
	popupBoxName = popupBox;
	textBoxName = tBox;
	//get popup box's layer style
	var popupLayer = document.getElementById(finalDivName).style;

	// get the text box object
	var qText = document.getElementById(tBox);
	
	//turn off built-in autocomplete feature coming from browsert
	qText.setAttribute('autocomplete','off');

	//alert(qText.getAttribute("autocomplete").value);
	//get x/y position of the text box
	var x = findPosX(qText);
	var y = findPosY(qText);

 	//get width of the textbox
	var width = getWidth(qText);
	//position the popup box right below the text box
	
	if (window.XMLHttpRequest){
		if (navigator.appName == "Microsoft Internet Explorer") {
			//alert('IE7');
			x=x+42;
		}
	} else if (navigator.appName == "Microsoft Internet Explorer") {
		x=x+142;
	} 

	//popupLayer.left = (x + 2 ) + "px";
	//popupLayer.top =  (y + 20) +"px";	
	
	//set the width of the popup layer
	popupLayer.width = width;
}

function setValueInLocation(location){
	//alert('called');
	var locationText = document.getElementById("search_location_id");
	if(locationText!=null){
		locationText.value = locationId[location];
	}
	var locationText1 = document.getElementById("header_search_location_id");
	if(locationText1!=null){
		locationText1.value = locationId[location];
	}
	
}

function setValueInSearchType(spanObject){
	var sourceText = document.getElementById("search_source_id");
	var sourceText1 = document.getElementById("header_search_source_id");
	var val = removeXMLCorrection(spanObject.innerHTML);
	var qText = (document.getElementById(textId));
	if (val.indexOf(ALL_RESULTS_FOR) == -1 && val.indexOf(',') != -1){
		var names = val.split(',');
		qText.value = names[0];
		document.getElementById(textId).value = val;
		if(sourceText!=null){
			sourceText.value = 3;
		}
		if(sourceText1!=null){
			sourceText1.value = 3;
		}
	} else {
		var names = val.split(':');
		qText.value = names[1];
		document.getElementById(textId).value = names[1];
		if(sourceText!=null){
			sourceText.value = 4;
		}
		if(sourceText1!=null){
			sourceText1.value = 4;
		}
	}	
}


//select value put into text
function doMouseClick(spanObject){
	setValueInSearchType(spanObject);
	hidePopup();
	document.getElementById(textId).focus(true);

	if(formName=='search_top'){
		setAction('search_top');
	} else if (formName=='homeSearch'){
		setAction('homeSearch');
	}
	document.forms[formName].submit();
}

// hide pop up
function hidePopup(){
	
	clearTimeout(timer);
	var popupLayer = document.getElementById(finalDivName).style;
	popupLayer.visibility="hidden";	
	
}

function showPopup(){
	//alert("i am here to show pop up");
	var popupLayer = document.getElementById(finalDivName).style;
	popupLayer.visibility="visible";
}

function enterSubmit(event){
return false;
}

// get value from text box and keyboard value 
function getQuery(id,k,event) {
	
	//work on IE only
     var check = k.length;
     textId=id;
    // alert(id+","+k+","+event);
	var popupLayer = document.getElementById(finalDivName).style;
	
	//alert(document.getElementById(finalDivName).id);
   
	if(popupLayer.visibility=="visible"){
	
	
	var KeyID = event.keyCode;
	
	if(KeyID==13){
		hidePopup();
		
	} else {
		var sourceText = document.getElementById("search_source_id");
		if(sourceText!=null){
			sourceText.value = 1;
		}
		var sourceText1 = document.getElementById("header_search_source_id");
		if(sourceText1!=null){
			sourceText1.value = 1;
		}
	}

		switch(KeyID){
			case 40:
			{
			
			if(currentSelectedID == 99){
			currentSelectedID = 0;
			}else{
				
					removefocusText(document.getElementById('ID'+ finalDivName+currentSelectedID));	
					if(maxSelectedID == currentSelectedID){	
									
					currentSelectedID = 0;
					}else{
						currentSelectedID = currentSelectedID+1;
						
					}
				}	
				setValueInSearchType(document.getElementById('ID'+ finalDivName+currentSelectedID));
				setValueInLocation(currentSelectedID);
				focusText(document.getElementById('ID'+ finalDivName+currentSelectedID));		
				
				return;	
			}
			break;
			case 38:
			{		
				if(currentSelectedID != 99){						
					removefocusText(document.getElementById('ID'+ finalDivName+currentSelectedID));			
					if(currentSelectedID == 0){	
						
						currentSelectedID = maxSelectedID;
					}else{
					currentSelectedID = currentSelectedID-1;
					}
				}		
				setValueInSearchType(document.getElementById('ID'+ finalDivName+currentSelectedID));
				setValueInLocation(currentSelectedID);
				focusText(document.getElementById('ID'+ finalDivName+currentSelectedID));
				return;
			}
			break;	
			case 13:
			if(check <= 2){
    			 return true;
    		}
    		return false;
			break;
			case 27:
			{
				hidePopup();
				currentSelectedID = 99;
				maxSelectedID = 0;
				return;
			}
			break;
			default:
			{		
			   currentSelectedID = 99;
				maxSelectedID = 0;				
			}
			
	   	}	
	}
	
	locationId = new Array();
		
	key=k;
	
	//don't send a request to the server if no value is selected 
	hidePopup();
	if (key.length<2) {	
		if(key!=''){
		
	//validation - char can not start with numeric	
		
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < k.length && IsNumber == true; i++) 
      { 
      Char = k.charAt(i); 

        if (ValidChars.search(Char) == -1) 
         {
      
         IsNumber = true;
         }
         else{
         IsNumber = false;
         return false;
         }
      }
   	    fldResult = '<SPAN id=IDNew class="resultNew" >' + key + '</SPAN><BR>';
			var divNew=document.getElementById(finalDivName);
			divNew.innerHTML = fldResult;
			
			divNew.innerHTML = '<iframe src="about:blank" scrolling="no" style="position: absolute;left: -1; top: -1;z-index: -1;filter: progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0);" frameborder="0"></iframe>' + divNew.innerHTML;
			var ieMatNew = divNew.firstChild;
			ieMatNew.style.width = divNew.offsetWidth+"px";
			ieMatNew.style.height = divNew.offsetHeight+"px";
				
		}	
		else{
			return false;
		}
		showPopup();	
		return;
	}	
		
	//if not ready, abort the previous request
	if (req.readyState != 0) {
		
		req.abort();
	} 
	
	//will start the timer
	if(popupLayer.visibility=="visible"){
		return;
	}
	//connectServer();
	timer=setTimeout('connectServer()', pauseTime);	
	/*	
	}
	*/
}

function connectServer(){


	clearTimeout(timer);
	//servlet url, pass the search key
	
	var url = typeAheadPath+"?key="+escape(key)+"&localeCode="+locale;
	
	//send request to the server
	if (req != null) {
	
	    req.open("GET", url, true);
		    
	    req.onreadystatechange = processResponse;
	   
	    req.send(null);
	}
}

function processResponse() {
	try{
	if (req.readyState == 4){
		//process only if OK
	
        if (req.status == 200)	{
        
			if(req.responseText==null) { 
				hidePopup();
			}
			else {
		
				parseResponse(req.responseText);
			}
		}
	}
	}catch(e){
		//don't show any script error 
	}
}

function parseResponse(result){
		
	  var xmlDoc;
      //load xml document
      if(document.implementation && document.implementation.createDocument) {
      	// MOZILLA
      
      	 xmlDoc = document.implementation.createDocument("", "", null);
       	 xmlDoc.async="false";
      	 xmlDoc.loadXML(result);
       } else if (window.ActiveXObject){
	   
	    //IE
      	xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
	    xmlDoc.loadXML(result);
	   }
      
       //get the count 
      	var resultCount = xmlDoc.getElementsByTagName("RESULTCOUNT").item(0).getAttribute("count");
      	var searchFor = xmlDoc.getElementsByTagName("SEARCHFOR").item(0).getAttribute("value");
      	
      	if(searchFor != key){
      		timer=setTimeout('connectServer()', pauseTime);	
      		return;
      	}
      	
		if(resultCount != "0"){
   	  
			var fldValues = xmlDoc.getElementsByTagName("suggestion");
			
			maxSelectedID = (fldValues.length-1);
			var fldResult='';
			var fldResultNew='';
			 
			//add values obtain from typing			
			
			var i=0;
			//add values obtained from the server to popup list
		    for ( i=0;i<fldValues.length;i=i+1){
		        var val = fldValues.item(i).getAttribute("name"); 
		        fldResult += '<SPAN id=\'ID'+ finalDivName+i+'\' class="result" onmouseover="mousefocusText(this); " onmouseout="removefocusText(this);"   onmousedown="setValueInLocation('+i+');doMouseClick(this);" >' + val + '</SPAN><BR>';
		        locationId[i] =  fldValues.item(i).getAttribute("locationId");
			}
			if(resultCount == 6) {
      			var totalCount = xmlDoc.getElementsByTagName("TOTALCOUNT").item(0).getAttribute("count");
      			
   				if(totalCount > 6) {
					fldResult += '<SPAN id=\'ID'+ finalDivName+ i +'\' class="result" onmouseover="mousefocusText(this); " onmouseout="removefocusText(this);"   onmousedown="setValueInLocation('+i+');doMouseClick(this);" >' + ALL_RESULTS_FOR + searchFor + '</SPAN><BR>';
					maxSelectedID = maxSelectedID + 1;
				}
				locationId[i]='All';
			}
			var div=document.getElementById(finalDivName);
			div.innerHTML = fldResult;
			div.innerHTML = '<iframe src="about:blank" scrolling="no" style="position: absolute;left: -1; top: -1;z-index: -1;filter: progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0);" frameborder="0"></iframe>' + fldResult;
			var ieMat = div.firstChild;
			
			ieMat.style.width=div.offsetWidth+"px";
			ieMat.style.height=div.offsetHeight+"px";	
			showPopup();
	   } else { 
		    hidePopup();
	   }
}

function removeXMLCorrection(str){	
	
	var newString='';
	newString = str.replace('&amp;', '&');	
	newString = newString.replace('&lt;', '<');
	newString = newString.replace('&gt;', '>');
	newString = newString.replace('&quot;', '\"');
	newString = newString.replace('&#39;', '\'');	
	
	return newString;	
}

function mousefocusText(spanInFocus){
	if(currentSelectedID != 99){
		removefocusText(document.getElementById('ID'+ finalDivName +currentSelectedID));
	}
	focusText(spanInFocus);
}
// put the focus 
function focusText(spanInFocus){	
	spanInFocus.style.color='white'; 
	spanInFocus.style.background='blue';
	spanInFocus.style.cursor='hand';
}
//remove focus
function removefocusText(spanInFocus){

	spanInFocus.style.background='white';
	spanInFocus.style.color='black'; 
	spanInFocus.style.cursor='default';
}

function shiftFocus(){
	alert("time to move cursor");
}

//check if it is IE
var isIE = (window.navigator.appName.toLowerCase().indexOf("microsoft")>=0);

//implement loadXML method for Mozilla since it is not supported
 if(!isIE){
	Document.prototype.loadXML = function (s) {

	   	// parse the string to a new doc
	   	var doc2 = (new DOMParser()).parseFromString(s, "text/xml");

	   	// remove all initial children
	   	while (this.hasChildNodes())
	   	   this.removeChild(this.lastChild);

	   	// insert and import nodes
	   	for (var i = 0; i < doc2.childNodes.length; i++) {
	   	   this.appendChild(this.importNode(doc2.childNodes[i], true));
	   	}
       };
} 


//get 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 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;
}

//get width of an object
function getWidth(element){
    if (element.clientWidth && element.offsetWidth && element.clientWidth <element.offsetWidth) {
        return element.clientWidth; 
    } else if (element.offsetWidth) {
        return element.offsetWidth;
    } else if (element.width) {
        return element.width;
    } else {
        return 0;
    }
}

function initialize(id,localeCode,divName,currentForm){

	formName = currentForm;
	textId=id;
	locale=localeCode;
	currentSelectedID = 99;
	maxSelectedID = 0;
	pauseTime=parseFloat(0.25)*1000; //pause time
	num=15; //number of results
	serverURL='.typeAhead';//server URL
	if(divName!=null){
		finalDivName = divName; 
	} else {
		finalDivName = 'autocomplete';
	}
	//alert(divName + ' ' + finalDivName);
	initPopup(id,finalDivName);
    parameters = new Array();
    parameters[0] = 'this param is not used.';
	parameters[1] = 'this param is not used.';
	parameters[2] = 'this param is not used.';
	parameters[3] = 'this param is not used.';
	parameters[4] = 'this param is not used.';
	parameters[5] = 'this param is not used.';
	parameters[6] = 'this param is not used.';
	parameters[7] = 'this param is not used.';
	parameters[8] = 'this param is not used.';
	

}

// disable enter key
function disableEnterKey(event)
{
     var key = event.keyCode;
     return true;
}
function disableEnterKeyForSearch(event,form)
{
     var key = event.keyCode;
	if(key==13){
		setAction(form);
	}

     return true;
}

var formAction =null;

function setAction(formName){
		var radioValue = document.getElementsByName("rdoWebWeather")[0].checked;
		if(!radioValue ){
			document.forms[formName].action = contextJSPath+"/partnerSearch";
		} else {
			document.forms[formName].action = contextJSPath+"/search";
		}
}


function clearform(which,value1,value2){
	if (which.value==value1 || which.value==value2){
		which.value=''; }
	
}

function validate(form){
	var text = form.searchText.value;
	if(text.length < 2){
		return false;
	}else{
	return true;
	}
}

function loadClass(txtBoxClass, text) {
	document.getElementById('header_nav_search_box_input').className = txtBoxClass;
	if (txtBoxClass == 'txtboxGoogle') {	
		document.getElementById('header_nav_search_box_input').value = '';	
	}	
	else {
		document.getElementById('header_nav_search_box_input').value = text;
	}
}
