/**
This file has been used in the application to cater the need of type ahead functionality implemented on motoring page (motoring.jsp).
**/

var hiddenLocationId;
var ajaxReq;
var motoringTimer; 
var keyMotoring;
var numMotoring;
var localeMotoring;
var pauseMotoringTime;
var parametersMotoring;
var textIdMotoring;
var finalDivNameMotoring;
var formNameMotoring;
var motoringLocationIds = new Array();
currentSelectedIDMotoring = 99;
maxSelectedIDMotoring = 0;
var popupBoxNameMotoring, textBoxNameMotoring;

if(window.onresize == null){
	window.onresize = restorePopupMotoring;
}

function restorePopupMotoring(){
	if(finalDivNameMotoring!=null && document.getElementById(finalDivNameMotoring)!=null){
		if(document.getElementById(finalDivNameMotoring).style.visibility=="visible"){
			hidePopupMotoring();
			showPopupMotoring();
		}	
	}
}

//initialize the XMLHttpRequest object
if (window.XMLHttpRequest) {
	ajaxReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
	ajaxReq = new ActiveXObject("Microsoft.XMLHTTP");
}

function initPopupMotoring(tBox, popupBox){
	popupBoxNameMotoring = popupBox;
	textBoxNameMotoring = tBox;
	//get popup box's layer style
	var popupLayer = document.getElementById(finalDivNameMotoring).style;

	// get the text box object
	var qText = document.getElementById(tBox);
	
	//turn off built-in autocomplete feature coming from browsert
	qText.setAttribute('autocomplete','off');

	//get x/y position of the text box
	var x = findPosXMotoring(qText);
	var y = findPosYMotoring(qText);

 	//get width of the textbox
	var width = getWidthMotoring(qText);
	//position the popup box right below the text box
	
	if (window.XMLHttpRequest){
		if (navigator.appName == "Microsoft Internet Explorer") {
			//For 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;
}

/*
	This method is used to set the location id into the hidden text box.
*/
function setValueInLocationMotoring(location){

	var locationText = document.getElementById(hiddenLocationId);
	if(locationText!=null){
		locationText.value = motoringLocationIds[location];
	}	
}

function setValueInSearchTypeMotoring(spanObject){
	var val = removeXMLCorrectionMotoring(spanObject.innerHTML);
	var qText = (document.getElementById(textIdMotoring));
	
	if (val.indexOf(ALL_RESULTS_FOR) == -1 && val.indexOf(',') != -1){	
		var names = val.split(',');
		qText.value = names[0];
		document.getElementById(textIdMotoring).value = val;		
	} else {
		var names = val.split(':');
		qText.value = names[1];
		document.getElementById(textIdMotoring).value = names[1];		
	}	
}


/*
	select value put into text
*/
function doMouseClickMotoring(spanObject){
	setValueInSearchTypeMotoring(spanObject);
	hidePopupMotoring();
	document.getElementById(textIdMotoring).focus(true);	
}

/*
	hide pop up
*/
function hidePopupMotoring(){
	
	clearTimeout(motoringTimer);
	var popupLayer = document.getElementById(finalDivNameMotoring).style;
	popupLayer.visibility="hidden";	
	
}

function showPopupMotoring(){
	var popupLayer = document.getElementById(finalDivNameMotoring).style;
	popupLayer.visibility="visible";
}

/*
	This method gets value from text box and keyboard value.
*/
function getQueryMotoring(id,k,event,motoring) {
	var check = k.length;
	textIdMotoring=id;
	var popupLayer = document.getElementById(finalDivNameMotoring).style;
   
	if(popupLayer.visibility=="visible") {

	var KeyID = event.keyCode;
	
	if(KeyID==13) {
		hidePopupMotoring();
		
	}

		switch(KeyID){
			case 40:
			{
			
			if(currentSelectedIDMotoring == 99){
			currentSelectedIDMotoring = 0;
			}else{
				
					removefocusTextMotoring(document.getElementById('ID'+ finalDivNameMotoring+currentSelectedIDMotoring));	
					if(maxSelectedIDMotoring == currentSelectedIDMotoring){	
									
					currentSelectedIDMotoring = 0;
					}else{
						currentSelectedIDMotoring = currentSelectedIDMotoring+1;
						
					}
				}	
				setValueInSearchTypeMotoring(document.getElementById('ID'+ finalDivNameMotoring+currentSelectedIDMotoring));
			
				// This line set the location id in the hidden text box.
				setLocationIdForMotoring(currentSelectedIDMotoring,motoring);			
				focusTextMotoring(document.getElementById('ID'+ finalDivNameMotoring+currentSelectedIDMotoring));		
				
				return;	
			}
			break;
			case 38:
			{		
				if(currentSelectedIDMotoring != 99){						
					removefocusTextMotoring(document.getElementById('ID'+ finalDivNameMotoring+currentSelectedIDMotoring));			
					if(currentSelectedIDMotoring == 0){	
						
						currentSelectedIDMotoring = maxSelectedIDMotoring;
					}else{
					currentSelectedIDMotoring = currentSelectedIDMotoring-1;
					}
				}		
				setValueInSearchTypeMotoring(document.getElementById('ID'+ finalDivNameMotoring+currentSelectedIDMotoring));

				// This line set the location id in the hidden text box.
				setLocationIdForMotoring(currentSelectedIDMotoring,motoring);
				focusTextMotoring(document.getElementById('ID'+ finalDivNameMotoring+currentSelectedIDMotoring));
				return;
			}
			break;	
			case 13:
			if(check <= 2){
    			 return true;
    		}
    		return false;
			break;
			case 27:
			{
				hidePopupMotoring();
				currentSelectedIDMotoring = 99;
				maxSelectedIDMotoring = 0;
				return;
			}
			break;
			default:
			{		
			   currentSelectedIDMotoring = 99;
				maxSelectedIDMotoring = 0;				
			}
			
	   	}	
	}
	
	motoringLocationIds = new Array();		
	keyMotoring=k;
	
	//don't send a request to the server if no value is selected 
	hidePopupMotoring();
	if (keyMotoring.length<2) {	
		if(keyMotoring!=''){
		
	//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;
         }
      }
   	    				
		}	
		else{
			return false;
		}
		showPopupMotoring();	
		return;
	}	
		
	//if not ready, abort the previous request
	if (ajaxReq.readyState != 0) {
		
		ajaxReq.abort();
	} 
	
	//will start the timer
	if(popupLayer.visibility=="visible"){
		return;
	}	
	motoringTimer=setTimeout('connectServerMotoring()', pauseMotoringTime);		
}

/*
	This method is used to connect the server by forming specific URL & calling processResponseMotoring() method.
*/
function connectServerMotoring(){
	
	// This will clear the timeout value; used to synchronized the Ajax request.
	clearTimeout(motoringTimer);

	// URL created to hit the SearchCommand.java with type ahead key value. We can also set some flag here to differentiate the ajax // request; Whether it is coming from motoring page or from some where else. Using this we can fix the number of resulted 
	// location ids comes from server-side; which is 6 for now.
	var url = typeAheadPathMotoring+"?key="+escape(keyMotoring)+"&localeCode="+localeMotoring;
	
	//sending request to the server
	if (ajaxReq != null) {	
	    ajaxReq.open("GET", url, true);		    
	    ajaxReq.onreadystatechange = processResponseMotoring;	   
	    ajaxReq.send(null);
	}
}

/*
	This method process the response comes from server and validate request states for the same. Then calls parseResponseMotoring().
*/
function processResponseMotoring() {
	try{
	if (ajaxReq.readyState == 4){
		//process only if OK	
        if (ajaxReq.status == 200)	{        
			if(ajaxReq.responseText==null) { 
				hidePopupMotoring();
			}
			else {		
				parseResponseMotoring(ajaxReq.responseText);
			}
		}
	}
	}catch(e){
		//don't show any script error 
	}
}

/*
	This method parse the result which is ingested in the response object. This is one of the important method for this file. It parse the result which is in xml form and display the result on the page.
*/
function parseResponseMotoring(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 RESULTCOUNT; which is 6 and set in  TypeAheadUtil.java. Can be changed as per busniess requirement.
      	var resultCount = xmlDoc.getElementsByTagName("RESULTCOUNT").item(0).getAttribute("count");
		// This is the key ; say 'atl'. On which type ahead fetch resulted locations from server.
      	var searchFor = xmlDoc.getElementsByTagName("SEARCHFOR").item(0).getAttribute("value");
      	
		// Check inequality of the searched key and key which is returned ingested in xml.
      	if(searchFor != keyMotoring){
      		motoringTimer=setTimeout('connectServerMotoring()', pauseMotoringTime);	
      		return;
      	}
      	
		if(resultCount != "0") {   	  
			var fldValues = xmlDoc.getElementsByTagName("suggestion");			
			maxSelectedIDMotoring = (fldValues.length-1);
			var fldResult='';
			var fldResultNew='';
			
			//add values obtain from typing						
			var i=0;
			// Add location values obtained from the server to drop-down list.
			// Section lies below this loop has been eliminated since it was used to display resolution page when the 
			// results/locations are more than 6.
		    for ( i=0;i<fldValues.length;i=i+1){
		        var val = fldValues.item(i).getAttribute("name"); 
		        fldResult += '<SPAN id=\'ID'+ finalDivNameMotoring+i+'\' class="result" onmouseover="mousefocusTextMotoring(this); " onmouseout="removefocusTextMotoring(this);"   onmousedown="setValueInLocationMotoring('+i+');doMouseClickMotoring(this);" >' + val + '</SPAN><BR>';
		        motoringLocationIds[i] =  fldValues.item(i).getAttribute("locationId");
			}

			// This piece of code form the drop-down list exactly in the div where results are required.
			var div=document.getElementById(finalDivNameMotoring);
			div.innerHTML = fldResult;
			div.innerHTML = '<iframe src="about:blank" scrolling="no" style="position: absolute;left: -3px; top: -1px;z-index: -1; border:1px #666666 solid;padding-left:5px;" frameBorder="0"></iframe>' + fldResult;
			var ieMat = div.firstChild;
			
			ieMat.style.width=div.offsetWidth+"px";
			ieMat.style.height=div.offsetHeight+"px";	
			showPopupMotoring();
	   } else { 
		    hidePopupMotoring();
	   }
}

/*
	This method removes unwanted characters from the result. 
*/
function removeXMLCorrectionMotoring(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 mousefocusTextMotoring(spanInFocus){
	if(currentSelectedIDMotoring != 99){
		removefocusTextMotoring(document.getElementById('ID'+ finalDivNameMotoring +currentSelectedIDMotoring));
	}
	focusTextMotoring(spanInFocus);
}

// put the focus 
function focusTextMotoring(spanInFocus){	
	spanInFocus.style.color='white'; 
	spanInFocus.style.background='blue';
	spanInFocus.style.cursor='hand';
}

//remove focus
function removefocusTextMotoring(spanInFocus){

	spanInFocus.style.background='white';
	spanInFocus.style.color='black'; 
	spanInFocus.style.cursor='default';
}

//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 findPosXMotoring(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 findPosYMotoring(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 getWidthMotoring(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;
    }
}

/*
	This method is used to initialized the file level variables; so that opeartion performed on the precised dom/html elements.  
*/
function initializeMotoring(id,localeCode,divName,currentForm){

	formNameMotoring = currentForm;
	textIdMotoring=id;
	localeMotoring=localeCode;
	currentSelectedIDMotoring = 99;
	maxSelectedIDMotoring = 0;
	pauseMotoringTime=parseFloat(0.25)*1000; //pause time
	numMotoring=15; //number of results
	if(divName!=null){
		finalDivNameMotoring = divName; 
	} else {
		finalDivNameMotoring = 'autocompleteFrom';
	}
	initPopupMotoring(id,finalDivNameMotoring);  	
}

/*
	This method is used to disable the enter key.
*/
function disableMotoringEnterKeyForSearch(event,form) {
	var key = event.keyCode;
	if(key==13){
		return false;
	}
	return true;
}

/*
	This method is used to clear the form.
*/
function clearMotoringForm(which,value1,value2) {

	if (which.value==value1 || which.value==value2) {
		which.value=''; 
	}
	
}

/* 
	This method take location object and hidden location text box id and set the value for the same accordingly.  
*/
function setLocationIdForMotoring(location,hiddenId) {
	
	var locationText = document.getElementById(hiddenId);
	
	if(locationText!=null){
		locationText.value = motoringLocationIds[location];
	}
}

/*
	This method take hidden field ID and initiliaze it by global var.
*/
function checkHiddenField(value) {
	hiddenLocationId = value;
}