/**
* JavaScript: Scripts for loading multiple data from server to select suitable one by matching  2 characters enetred from keyboard
* @author: Samanmalee M.K.A.
* Date created: 22/08/2006
* Copyright: Codegen International (Pvt) Ltd.
**/
/**
* Get response from the server should be in following format:
		" getACResponse("", new Array(""),"",new Array("")); "
					1st String value 	-> 2 characters entered using keyboard
					1st Array 			-> main results select by using above 2 characters
					2nd String 			-> maximum value from the main resutls set
					2nd Array			-> if need any extra information to select main results to show it with resutls use this array

		Ex:- if need to select student name started with "ni" and if same name repeated need to know where he/she came from
			response : getACResponse("ni", new Array("nimali","nilupa","nilupa"),"nimali",new Array("colombo","gampola","colombo"));

* mainACLoopRunning() method sets to run at every 10 miliseconds to check changes.
* send request to the server with url need to access and append reuired data need for matching as parameteres of it in sendACRequestToGetResults() method.
* At OnFocus event of the text box need to send 3 parameters to the OnFocus() method.
	1. main field id
	2. sub field id (if match 2 parameters to select data)
	3. url need to access (ex :- 'http://192.168.0.32:8002/XMLHttpRequestHandler6.po?')
**/

//declare globle variables
var g_sACOldInputFieldValue=""; // g_oACInputField value (set during call to sendACRequestToGetResults)
var g_sACCurrentInputFieldValue=""; // sets currents input value
var g_sACNewEnteredFieldValue=""; // assign new entered value at arrow key press
var g_iACEventKeycode=0; // assign event keycode.
var g_iACHighlightedSuggestionIndex=-1; // position of the currently hightlighted item of the Div elements
var g_oACHighlightedSuggestionDiv=null; // currently used div gets as object.
var g_oACCompleteDivList=null; // completeDiv div list at time of keypress
var g_oACDivTag="div"; // use to get the no of rows in the list at every time when list shows
var g_oACInputField=null; // Input field from HTML page
var g_bACHasXMLHTTP=false; // Gets set to true if XMLHTTP Supported
var g_oACXmlHttp=null; // This g_sACInputStringValue the XMLHttp Object
var g_sACCompleteURL=""; // Gets set to "/complete/search/?hl=
var g_oACSelectEntry=null; //set select entry as object to set properties
var g_sACValueAtKeyPress=""; //gets the selected item at keypress
var g_iACTotalLengthOfItem=0; //total length of the item heighlighted
var g_sACFinalValueSelected=""; //final value selected before enter
var g_iACPostionOfSelectedValue=0; //position of the selected item
var g_iACFinalPosition=-1; //use to identify the final position of the highlighted item
var g_iACCount=-1; //use to get item by single click of mouse
var g_iACCompleteDivRows=-1; // completeDiv rows at time of keypress
var g_iACHighlightedIndex=0; //use to highlight items by using arrow keys
var g_iACInputLength=0; //length of the value entered to the input field by keyboard
var g_sACInputStringValue=0; //use to get the length of the highlighted value at mousemove event
var g_sACValueEnter=""; //use to get the length of the text enter by keyboard
var g_oACSearchStringValue2=null; //get input values as parameter
var g_oACSearchStringValue1=null; //get input value as parameter
var g_sACMaximumLengthValue=""; //gets the maximum length of the item selected from response to set the width of the Div
var g_iACNoOfRecords=0; // use to sets the height of the Div using no of records
var g_iACMaxResponseValueLength=0; // use to set the length of the maximum response item
var g_bACHasSecondArray=false; // if has second array this variable sets to true
var g_iACLastKeyCode=0;
var g_oACApplyDivElement=null; // Div object defined in inside HTML page
var g_sACFunctionParameter=null;
var g_oACDivElementID='AutoCompleteDiv';
var g_sACMaxValOfExtraArray="";
var g_sACHotelType = "";

/**
This "onACFocusText()" Method Calls at First when focused to the text box of the HTML page
In HTML page for every text boxes for "onFocus" event this method should be called with paramters.

	4 Parameters need to pass for this method to execute:
		1. p_oMainField	->	id of the focused text box.
		2. p_oSubField	->	id of the any other text box which use as second data to select focused text box data.
		3. p_sURL		->	url need to send request to get results.
		4. p_sACFunctionParameter -> a string constant to identify the required functionality at server side. If No function, then use ''.

ex:- Text box to enter student names can be added to the HTML page as follows.
	HTML code: <input name="name" id="name" type="text" onFocus="onACFocusText('name','city','http://192.168.0.32:8002/XMLHttpRequestHandler6.po?&qu3=name','div1');" value="" autocomplete="off">
		"name"	-> id of the focused text box
		"city"	-> id of the second text box which use its contents to select this data (display city of the each student name in the selection list to make easy to select)
		"http://192.168.0.32:8002/XMLHttpRequestHandler6.po?&qu3=name"	-> url need to access to get results with parameter to identify methods in server

	Div element should be applied inside HTMl page with id "div1"
	HTML code: <div id="div1" style="position:absolute; width:140px; top:89px; left:16px; line-height:15px; font-size:15px"></div>
				This Div element use as "g_oACApplyDivElement" object.
				For all the text boxes only this Div element used to show data

**/

function onACFocusText(p_oMainField,p_oSubField,p_sURL,p_sACFunctionParameter, extraParam){
//    alert(p_oMainField)
//    alert(p_oSubField);
    g_oACSearchStringValue1=document.getElementById(p_oMainField);
	g_oACSearchStringValue2=document.getElementById(p_oSubField);
	g_sACFunctionParameter=p_sACFunctionParameter;
	g_oACApplyDivElement=document.getElementById(g_oACDivElementID);
    if(extraParam)
    {
        g_sACHotelType = extraParam['type'];
    }

    g_oACInputField=document.getElementById(p_oMainField);
    setACPropertyOfDiv(g_oACApplyDivElement);
	g_sACCompleteURL=p_sURL;
//    alert("alert");
        if(getACXMLHTTP()){
			g_bACHasXMLHTTP=true
		}else{
			g_bACHasXMLHTTP=false
		}
	g_oACInputField.onblur=hideACDivElement;
		if(g_oACInputField.createTextRange){
				g_oACInputField.onkeyup=new Function("return getACKeyEvent(event);");  //if input field create text call getEvent and through that check every key press
		}
		else {
		g_oACInputField.onkeyup=getACKeyEvent;
		}
	g_sACOldInputFieldValue=g_sACCurrentInputFieldValue;
	g_sACCurrentInputFieldValue=g_oACInputField.value; //assign new input field value to g_sACCurrentInputFieldValue
 	var oFrameElement = document.createElement("IFRAME");
	oFrameElement.setAttribute("id", "completeDivIFrame");
	oFrameElement.setAttribute("scroll", "no");
	oFrameElement.setAttribute("frameborder", "0");
	oFrameElement.style.position = "absolute";
	oFrameElement.style.visibility = "hidden";
	oFrameElement.style.filter = "Alpha(opacity=0)";
	document.body.appendChild(oFrameElement);
	document.onkeydown=keyACDownHandler; //calls at every key press when focused
}

//sets properties of the Div
function setACPropertyOfDiv(p_oDivElement){
	p_oDivElement.style.borderRight="black "+1+"px solid";	//display border at right of the div
	p_oDivElement.style.borderLeft="black "+1+"px solid";		//display border at left of the div
	p_oDivElement.style.borderTop="black "+1+"px solid";		//display border at top of the div
	p_oDivElement.style.borderBottom="black "+1+"px solid";	//display border atbottom of the div
	p_oDivElement.style.zIndex="1";
	p_oDivElement.style.paddingRight="3px"; //right side distance detween items and Div
	p_oDivElement.style.paddingLeft="3px";//left side distance detween items and Div
	p_oDivElement.style.paddingTop="3px";//top distance detween items and Div
	p_oDivElement.style.paddingBottom="8px";//bottom  distance detween items and Div
	p_oDivElement.style.backgroundColor="white"; //background color of the Div
	hideACDivElement();
}

//access at every key events
function keyACDownHandler(event){
	g_iACCount=0;
	return true;
}

// returns an XMLHttp object
//gets it in an IE/Mozilla friendly way
function getACXMLHTTP(){
var oGetXmlHttp=null;
	try{
	oGetXmlHttp=new ActiveXObject("Msxml2.XMLHTTP")
	}catch(p_oKeyEvent){
		try{
		  oGetXmlHttp=new ActiveXObject("Microsoft.XMLHTTP")
		} catch(oc){
		  oGetXmlHttp=null
		}
	}
	if(!oGetXmlHttp && typeof XMLHttpRequest != "undefined") {
	oGetXmlHttp=new XMLHttpRequest()
	}
	return oGetXmlHttp
}

//get event as parameter when keyup
function getACKeyEvent(p_oKeyEvent){
    g_iACEventKeycode=p_oKeyEvent.keyCode; //assign get event's key code value to variable g_iACEventKeycode
//    alert(g_iACEventKeycode);
    g_sACValueEnter=g_oACInputField.value.length;
		if(g_iACEventKeycode==13||g_iACEventKeycode==3||g_iACCount==1){
			dehighlightACTextValue();
		}
	g_sACCurrentInputFieldValue=g_oACInputField.value;
		if(handleACKeysUpDownEnter(g_iACEventKeycode)&&g_iACEventKeycode!=0) {
			callACAtKeyPress(g_oACApplyDivElement,callACAtMouseEvents) //call if perss key except enter,uparrow,downarrow keys
		}
}

//dehighlight value in the text box
function dehighlightACTextValue(){
	var oGetInputField=g_oACInputField; //gets the value at enter press
		if(oGetInputField.createTextRange){ //check it contains create text range
			var t=oGetInputField.createTextRange();
			t.moveStart("character",oGetInputField.value.length); //dehighlight value in text box  in IE
			t.select()
		} else if (oGetInputField.setSelectionRange){
			oGetInputField.setSelectionRange(oGetInputField.value.length,oGetInputField.value.length) //dehighlight value in Mozilla
		}
}

// returns false if cursor up / cursor down or enter pressed...gets the key code value as para
function handleACKeysUpDownEnter(p_iEventCode){
	if(p_iEventCode==40){ //40=key code value for down arrow
		highlightACNewValue(g_iACHighlightedSuggestionIndex+1); //initially 'g_iACHighlightedSuggestionIndex=-1' then assign the postion of the item as integer
		return false
	}else if(p_iEventCode==38){//38=key code value for up arrow
		highlightACNewValue(g_iACHighlightedSuggestionIndex-1);
		return false
	}else if(p_iEventCode==13||p_iEventCode==3||g_iACCount==1){ //13=key code value for enter key
		g_iACCount==1;
		g_sACOldInputFieldValue=g_sACCurrentInputFieldValue;
		hideACDivElement() //if press enter key hide the div
		return false
	}
		return true
}

// This function  gets called over and over again for every 10milliseconds
function mainACLoopRunning(){		

    if(g_sACOldInputFieldValue!=g_sACCurrentInputFieldValue){ //check old input value and current input value
		var sGetInputFieldValue="";
		sGetInputFieldValue=g_sACCurrentInputFieldValue; //create new object sGetInputFieldValue with current input field value
        if(g_bACHasXMLHTTP){
//             alert(g_bACHasXMLHTTP);
                if ( sGetInputFieldValue != null && sGetInputFieldValue != "" && sGetInputFieldValue.length >= 2){
					  sendACRequestToGetResults() //get response as a java script
				}
			}
		g_oACInputField.focus();
	}
	g_sACOldInputFieldValue=g_sACCurrentInputFieldValue;
	setTimeout("mainACLoopRunning()",10);
	return true
}
// Call mainLoop() after 10 milliseconds...
setTimeout("mainACLoopRunning()",10);

// This use the g_oACXmlHttp object to send a message back
//response need to get form server -> getACResponse("ni", new Array("nimali","nilupa","nilupa"),"nimali",new Array("colombo","gampola","colombo"));
//g_sACCompleteURL	-> complete URL
//g_oACSearchStringValue1.value,g_oACSearchStringValue2.value -> values need to send to the server to match data (if use 1 parameters only g_oACSearchStringValue2.value has no value)
function sendACRequestToGetResults(){
	if(g_oACXmlHttp&&g_oACXmlHttp.readyState!=0){
		g_oACXmlHttp.abort();
	}
	g_oACXmlHttp=getACXMLHTTP();
	if(g_oACXmlHttp){
		var sPara2;
		if(g_oACSearchStringValue2==null){
			sPara2 = '';
		}
		else{
			sPara2 = g_oACSearchStringValue2.value;
		}

			if(g_sACFunctionParameter==''){
				g_oACXmlHttp.open("GET",g_sACCompleteURL+"?para1="+g_oACSearchStringValue1.value+"&para2="+sPara2 + "&hotelType=" + g_sACHotelType,true); //send request for p_sClassOfStyle for the given data
			}
			else{
//                alert(g_sACCompleteURL);
            g_oACXmlHttp.open("GET",g_sACCompleteURL+"?func="+g_sACFunctionParameter+"&para1="+g_oACSearchStringValue1.value+"&para2="+sPara2+ "&hotelType=" + g_sACHotelType,true); //send request for p_sClassOfStyle for the given data
			}

			g_oACXmlHttp.onreadystatechange=function( start_time ) {
				if(g_oACXmlHttp.readyState==4&&g_oACXmlHttp.responseText){ //4=complete state
//                    alert(g_oACXmlHttp.responseText);
                      eval(g_oACXmlHttp.responseText); //get parameter as java script
				}
			}
		g_oACXmlHttp.send(null)
	}
}

//get thiscode dynamically returned from sendACRequestToGetResults
function getACResponse(p_sInputStrinValue,p_aResultsArray,p_sMaximumValue,p_aExtraArrayToIdentify){
	if ( p_aExtraArrayToIdentify  && p_aExtraArrayToIdentify.length == 1 && p_aExtraArrayToIdentify[0]=="" ){
		g_bACHasSecondArray=false;
	}
	else{
		g_bACHasSecondArray=true;
	}
	if ( p_aResultsArray  && p_aResultsArray.length == 1 && p_aResultsArray[0]=="" ){	//result set as a array & g_sACInputStringValue=current input string value
		hideACDivElement(); //if no elements in array hide div
		return;
	}
	g_iACMaxResponseValueLength=p_sMaximumValue.length;
	if(p_sMaximumValue==p_sInputStrinValue){
		hideACDivElement(); //when selecting the complete values hide Div
	}
	else{
		var b=g_oACApplyDivElement;
		b.resultArray=p_aResultsArray; //sets results array to the frame b as resultArray
		b.extraArrayUsed=p_aExtraArrayToIdentify;
		createACSuggestedList(b,b.resultArray,b.extraArrayUsed); //append elements one by one in array to the div
		callACAtKeyPress(b,getACSelectedItem);  //set the div
	}
}

//create suggested list of the Div
//p_oFrameElement -> get Div Element as Object
//p_aResultsArray -> main results array gets from server in response
//p_aExtraArrayUsed -> if response contain extra data array use to select data
function createACSuggestedList(p_oFrameElement,p_aResultsArray,p_aExtraArrayUsed){
	g_sACMaximumLengthValue="";
	g_sACMaxValOfExtraArray="";
	while(p_oFrameElement.childNodes.length>0) { //remove old elements
		p_oFrameElement.removeChild(p_oFrameElement.childNodes[0]);
	}
	for(var iCount=0; iCount<p_aResultsArray.length; ++iCount){
		var oTemporyDivElement=document.createElement("DIV");
		setACStyleForElement(oTemporyDivElement,"aAutoComplete"); //sets the styles
		oTemporyDivElement.onmousedown=mouseACSingleClick; //used when mouse down
		oTemporyDivElement.onmousemove=atACMouseMove; //used for mouseover event
		oTemporyDivElement.onmouseout=atACMouseOut; //used when mouse outl
		var oSpanTag1=document.createElement("SPAN");
		setACStyleForElement(oSpanTag1,"lAutoComplete");
		var oSpanTag2=document.createElement("SPAN");
		oSpanTag2.innerHTML=p_aResultsArray[iCount]; // list of names get as a result of input
		g_iACNoOfRecords=p_aResultsArray.length;
		var temp=p_aResultsArray[iCount];
			if(temp.length>g_sACMaximumLengthValue.length){
					g_sACMaximumLengthValue=temp; //capture the maximum length of the value from results
			}
		var oSpanTag3=document.createElement("SPAN");
		setACStyleForElement(oSpanTag2,"cAutoComplete");

		if(g_bACHasSecondArray){
			oTemporyDivElement.displaySpan=oSpanTag3;
			oSpanTag3.innerHTML=p_aExtraArrayUsed[iCount];
			if(g_sACMaxValOfExtraArray.length<p_aExtraArrayUsed[iCount].length){
				g_sACMaxValOfExtraArray=p_aExtraArrayUsed[iCount];
			}
		}

		setACStyleForElement(oSpanTag3,"dAutoComplete");
		showACDivElement();
		oSpanTag1.appendChild(oSpanTag3);
		oSpanTag1.appendChild(oSpanTag2);
		oTemporyDivElement.appendChild(oSpanTag1);
		p_oFrameElement.appendChild(oTemporyDivElement);
	}
}

//access at mouse single click event
function mouseACSingleClick(){
	g_iACCount=1;
	hideACDivElement();
}

//access on mouseover event
function atACMouseMove(){
   selectACEntry(callACAtMouseEvents(this));
   setACStyleForElement(this,"bAutoComplete")
   g_sACInputStringValue=g_oACSelectEntry.length;
	  if(g_iACCount!=1){ //g_iACCount=1 => value selected by clicking mouse from the list when mouse over
	   selectACRestOfText(g_sACValueEnter,g_sACInputStringValue);
	   g_oACInputField.focus();
	  }
	   if(g_iACCount==1) // if select value from list when mouse over by pressing enter key  div hide
		{
			hideACDivElement();
			dehighlightACTextValue();
			g_oACInputField.focus();
		}
}

//Access at Mouse out event
function atACMouseOut(){
  setACStyleForElement(this,"aAutoComplete")
}

//p_oLocalCompleteDiv -> apply div element
//p_sValueSeleted -> value currently selected
function callACAtKeyPress(p_oLocalCompleteDiv,p_sValueSeleted){
	var localInputField=g_oACInputField;
	var T=false;
	g_iACHighlightedSuggestionIndex=-1;
//    alert(p_oLocalCompleteDiv);
    var J=p_oLocalCompleteDiv.getElementsByTagName(g_oACDivTag);  // # of rows in list
	var O=J.length;
	g_oACCompleteDivList=J;
	g_sACNewEnteredFieldValue=g_sACCurrentInputFieldValue;
	g_iACCompleteDivRows=O; //sets the properties of div (no of rows)
	g_sACNewEnteredFieldValue=g_sACCurrentInputFieldValue;
	valueAtKPress=g_sACCurrentInputFieldValue;
		if(g_sACCurrentInputFieldValue==""||O==0){ //if no any input value hide div
			hideACDivElement()
		}
}

//hide div element
function hideACDivElement(){
  if(document.getElementById("completeDivIFrame" )!=null)
  	document.getElementById("completeDivIFrame" ).style.visibility = "hidden";
	document.getElementById(g_oACApplyDivElement.id).style.visibility="hidden";
	g_iACNoOfRecords=0;
}

//show div element
function showACDivElement(){ //show div
 	document.getElementById("completeDivIFrame" ).style.visibility="visible";
	document.getElementById(g_oACApplyDivElement.id).style.visibility="visible";
	document.getElementById(g_oACApplyDivElement.id).style.height=(g_iACNoOfRecords*15) +"px" //sets the height of the Div according to the results :15=>line-height from HTML
	document.getElementById(g_oACApplyDivElement.id).style.top=calculateACOffsetTop(g_oACInputField)+g_oACInputField.offsetHeight-1+"px"; //sets the space between text box and Div in Mozilla
		if(g_bACHasSecondArray){
		document.getElementById(g_oACApplyDivElement.id).style.width=(g_sACMaximumLengthValue.length*8 +g_sACMaxValOfExtraArray.length*8)+"px" //sets the width of the Div according to the maximum size of the results :15=>font-size from HTML
		}else{
		document.getElementById(g_oACApplyDivElement.id).style.width=(g_sACMaximumLengthValue.length*8)+"px" //sets the width of the Div according to the maximum size of the results :15=>font-size from HTML
		}
	document.getElementById(g_oACApplyDivElement.id).style.left=calculateACOffsetLeft(g_oACInputField)+"px";
  var frameEle= document.getElementById("completeDivIFrame");
  if ( frameEle )
  {
    frameEle.style.left=calculateACOffsetLeft(g_oACInputField)+"px";
    frameEle.style.top=calculateACOffsetTop(g_oACInputField)+g_oACInputField.offsetHeight-1+"px";
	if(g_bACHasSecondArray){
	frameEle.style.width=(g_sACMaximumLengthValue.length*11 +g_sACMaxValOfExtraArray.length*11+10)+"px";
	}else{
	frameEle.style.width=(g_sACMaximumLengthValue.length*11 +10)+"px";
	}
	frameEle.style.height=(g_iACNoOfRecords*15+20) +"px";
  }
}

//sets the Div position in correct place in top
function calculateACOffsetTop(p_sInputStringValue){
	return getACCorrectPosition(p_sInputStringValue,"offsetTop")
}

 //place the Div at the correct place
function calculateACOffsetLeft(p_sInputStringValue){
	return getACCorrectPosition(p_sInputStringValue,"offsetLeft")
}

//returns the coordinates of the place of the Div
function getACCorrectPosition(p_sInputStringValue,p_sPosition){
	var kb=0;
		while(p_sInputStringValue){
			kb+=p_sInputStringValue[p_sPosition];
			p_sInputStringValue=p_sInputStringValue.offsetParent
		}
	return kb
}

//integer parameter which tells the position of the item need to highlight half of full
function highlightACNewValue(g_iACPostionOfSelectedValue){
	g_sACCurrentInputFieldValue=g_sACNewEnteredFieldValue; //selected value rom arrow key displays as g_sACNewEnteredFieldValue
	g_oACInputField.value=g_sACNewEnteredFieldValue;  //set new heighlighted value to the input field
		if(g_iACHighlightedSuggestionIndex!=-1&&g_iACPostionOfSelectedValue!=g_iACHighlightedSuggestionIndex){ //check whether item selected or not
			setACStyleForElement(g_oACHighlightedSuggestionDiv,"aAutoComplete"); //select only 1 item at a time when key press
			g_iACHighlightedSuggestionIndex=-1
		}
		if(g_iACPostionOfSelectedValue<0){ //if no any item selected execute this
			g_iACHighlightedSuggestionIndex=-1;
			g_oACInputField.focus();
			return
		}
	g_iACHighlightedSuggestionIndex=g_iACPostionOfSelectedValue;  //sets the position of the selected item to the variable g_iACHighlightedSuggestionIndex
	g_oACHighlightedSuggestionDiv=g_oACCompleteDivList.item(g_iACPostionOfSelectedValue);//select the item that selected using its position as object
	setACStyleForElement(g_oACHighlightedSuggestionDiv,"bAutoComplete"); //set styles for the given style
	g_iACInputLength=g_sACCurrentInputFieldValue.length; //find the length of the currently heighlighted value
	g_oACInputField.value=getACSelectedItem(g_oACHighlightedSuggestionDiv,"cAutoComplete") //set this heighlighted value to the input field
		if(g_sACValueAtKeyPress!="null" || g_sACValueAtKeyPress!=""){	 //if value contain at key press store those values as finally get values in variables
			g_sACFinalValueSelected=g_sACValueAtKeyPress
			g_iACFinalPosition=g_iACHighlightedSuggestionIndex //final position selected
			setACStyleForElement(g_oACHighlightedSuggestionDiv,"bAutoComplete");
		}
		g_sACValueAtKeyPress=g_oACInputField.value
		if(g_sACValueAtKeyPress=="null"||g_sACValueAtKeyPress==""){
			g_oACInputField.value=g_sACFinalValueSelected  //when no value at keypress set finally selected value to the input field
			g_sACValueAtKeyPress=g_oACInputField.value
			g_iACHighlightedSuggestionIndex=g_iACFinalPosition-1;
			g_oACHighlightedSuggestionDiv=g_oACCompleteDivList.item(g_iACHighlightedSuggestionIndex);//select the item that selected using its position as object
			setACStyleForElement(g_oACHighlightedSuggestionDiv,"bAutoComplete");
		}
	g_iACTotalLengthOfItem=g_sACValueAtKeyPress.length; //find the total length of the selected item
	g_iACPostionOfSelectedValue=g_iACFinalPosition-1
	selectACRestOfText(g_iACInputLength,g_iACTotalLengthOfItem); //call select charaters function
}

//p_iInputLength=>character length input by keyboard,  p_iTotalLength=>total length of the selected item
//this fuction will highlight the rest of the text gets from item list to allow type above it if no need
function selectACRestOfText(p_iInputLength,p_iTotalLength){
	if (g_oACInputField.createTextRange) { //this used for IE to heighlight characters
		var oRange = g_oACInputField.createTextRange();
		oRange.moveStart("character", p_iInputLength);
		oRange.moveEnd("character", p_iTotalLength - p_iInputLength); //select the range need to heighlighted
		oRange.select(); //select
	} else if (g_oACInputField.setSelectionRange) { //this use by Mozilla to heighlight characters
		g_oACInputField.setSelectionRange(p_iInputLength, p_iTotalLength);
	}
	g_oACInputField.focus(); //focue to the input field
}

//call at mouse events
function callACAtMouseEvents(p_oFrameElement){
		if(!p_oFrameElement) {
			return null;
		}
	return getACSelectedItem(p_oFrameElement,"cAutoComplete") //returns the selected item value at mouse move
}

//returns the currently highligted value
function getACSelectedItem(p_oFrameElement,p_sStyleType){
		if(!p_oFrameElement) {
			return null;
		}
	var spanTag="span";
	var ga=p_oFrameElement.getElementsByTagName(spanTag);
		if(ga){
			for(var f=0; f<ga.length; ++f){
				if(ga[f].className==p_sStyleType){
					var value=ga[f].innerHTML;//write item values one by one to the html
					return value  //return item value selected
				}
			}
		}else{
			return""
		}
}

//sets properties for the items in the list
function setACStyleForElement(p_oCreatedObject,p_sClassOfStyle){
		if ( !p_oCreatedObject )
		{
			return;
		}
	p_oCreatedObject.className=p_sClassOfStyle; //defines the object selected
	switch(p_sClassOfStyle.charAt(0)){ //get the first character of the style given to set the properties
		case "l":
			p_oCreatedObject.style.display="block";//block only the value selected by arrow key
			p_oCreatedObject.style.overflow="hidden";//heighlight selected value in Mozilla
		break;
		case "a":
			p_oCreatedObject.style.backgroundColor="white";//sets background color of div to white
			p_oCreatedObject.style.color="black";
      break;
		break;
		case "b":
			p_oCreatedObject.style.backgroundColor="#3366cc";//sets the heighlight colour to blue
			p_oCreatedObject.style.color="white";
		break;
		case "c":
			p_oCreatedObject.style.cssFloat="left";//sets the space between items in the list in proper way for mozilla
			p_oCreatedObject.style.textAlign="left"; // align text to left
			p_oCreatedObject.style.cursor="default"; // set cursor style to arrow when move along text
		break;
		case "d":
			p_oCreatedObject.style.cssFloat="right"; //right align extra data field
			p_oCreatedObject.style.color="#999999"; //sets its colour to grey
			p_oCreatedObject.style.styleFloat="right"; //align text to right side
			p_oCreatedObject.style.cursor="default"; // set cursor style to arrow when move along text
		break;
	}
}

//sets the highlight value to appear in th e text box
function selectACEntry(p_sSelectedValue){
	g_oACInputField.value=p_sSelectedValue; //sets select value to the input field at every time this function executed
	g_oACSelectEntry=p_sSelectedValue
}

/**
 * Abort the operations of the Autocomplete. Close Any Suggestion window.
 * By Buddhika on 2007-01-16
 */
function abortACOperations()
{
	if(g_oACXmlHttp == null)
	{
		return;
	}
	if((g_oACXmlHttp.readystate!=0)&&(g_oACXmlHttp.readystate!=4))
	{
		g_oACXmlHttp.abort();
		hideACDivElement();
	}

}




// JavaScript Document
function sessionId()
{
    var sURL = window.location.href;
    var sTemp = sURL.substring(sURL.indexOf(';') + 1);

    if(sTemp.indexOf('?') > -1)
    {
    sTemp = sTemp.substring(0,sTemp.indexOf('?'));
    }

    return sTemp;

}

/**
 * @param accomId
 * @param action
 * @param room
 */
function showFacility(accomId, action, room)
{
    if( !room )
    {
        var facilityDiv = document.getElementById('hotelFacilities_' + accomId);
        var oParentNode = facilityDiv.parentNode;
        if( action.indexOf('hide') > -1 )
        {
            oParentNode.style.display = 'none';
            facilityDiv.style.display = 'none';
            document.getElementById('showHotelFacilities_' + accomId).style.display = '';
            document.getElementById('hideHotelFacilities_' + accomId).style.display = 'none';
            document.getElementById('FacilitiesPlus_' + accomId).style.display = '';
            document.getElementById('FacilitiesMinus_' + accomId).style.display = 'none';
            document.getElementById('hideFacTbl_' + accomId).style.display = 'none';
            document.getElementById('showFacTbl_' + accomId).style.display = '';
        }
        if( action.indexOf('show') > -1 )
        {
            facilityDiv.style.display = '';
            oParentNode.style.display = '';
            document.getElementById('showHotelFacilities_' + accomId).style.display = 'none';
            document.getElementById('hideHotelFacilities_' + accomId).style.display = '';
            document.getElementById('FacilitiesPlus_' + accomId).style.display = 'none';
            document.getElementById('FacilitiesMinus_' + accomId).style.display = '';
            document.getElementById('hideFacTbl_' + accomId).style.display = '';
            document.getElementById('showFacTbl_' + accomId).style.display = 'none';
        }
    }
    else
    {
        var facilityDiv = document.getElementById('roomFacilities_' + accomId);
        if( action.indexOf('hide') > -1 )
        {
            facilityDiv.style.display = 'none';
            document.getElementById('showRoomFacilities_' + accomId).style.display = '';
            document.getElementById('hideRoomFacilities_' + accomId).style.display = 'none';
            document.getElementById('FacilitiesPlusRoom_' + accomId).style.display = '';
            document.getElementById('FacilitiesMinusRoom_' + accomId).style.display = 'none';
            document.getElementById('hideFacTblRoom_' + accomId).style.display = 'none';
            document.getElementById('showFacTblRoom_' + accomId).style.display = '';
        }
        if( action.indexOf('show') > -1 )
        {
            facilityDiv.style.display = '';
            document.getElementById('showRoomFacilities_' + accomId).style.display = 'none';
            document.getElementById('hideRoomFacilities_' + accomId).style.display = '';
            document.getElementById('FacilitiesPlusRoom_' + accomId).style.display = 'none';
            document.getElementById('FacilitiesMinusRoom_' + accomId).style.display = '';
            document.getElementById('hideFacTblRoom_' + accomId).style.display = '';
            document.getElementById('showFacTblRoom_' + accomId).style.display = 'none';
        }
    }
}

/**
 * Used to change the class name attribute of child nodes of the given node, to the given value depending on the level
 * @para p_oParentNode Parent node
 * @para p_sValue new value of the class
 * @para p_nLevel level to which the method should be executed (terminates if -1)
 */
function changeChildAttribute( p_oParentNode, p_sValue, p_nLevel )
{
    if( p_nLevel > -1 )
    {
        var oChildNodes = p_oParentNode.childNodes;
        for( var x = 0; x < oChildNodes.length; x++ )
        {
            var oElement = oChildNodes[x];
            oElement.className =  p_sValue;
            changeChildAttribute( oElement, p_sValue, ( p_nLevel - 1 ) );
        }
    }
}

/**
 * Used to replace a given text by a given replace text repetedly from a geven string
 * @para Source source string
 * @para stringToFind text to be removed
 * @para stringToReplace text to be replaced
 */
function ReplaceAll( Source, stringToFind, stringToReplace )
{
    var temp = Source;
    var index = temp.indexOf(stringToFind);
    while( index != -1 )
    {
        temp = temp.replace(stringToFind, stringToReplace);
        index = temp.indexOf(stringToFind);
    }
    return temp;
}


//chat Application
function openBrWindow( winName, features )
{
    var chatWindow;
    var sessionId = document.getElementById('SessionId').value;
    var cssPath = document.getElementById('cssPath').value;
    var baseUrl = document.getElementById('onlineChatUrl').value;

    if(!sessionId)
    {
        sessionId = getCookie('jsid');
    }
    if(!baseUrl)
    {
        baseUrl = getCookie('chatUrl');
    }
    if(!cssPath)
    {
        cssPath = getCookie('cssPath');
        if(!cssPath)
        {
            cssPath = 'CHK';
        }
    }
    var isCheckinto = "";
    if( cssPath.indexOf('CHK') > -1 )
    {
        isCheckinto = "&checkInto=yes";
    }
    var theURL = "";
    chatWindow = window.open(theURL, winName, features);

    if( chatWindow.document.getElementById('ChatOpen') == null )
    {

        var chatUrl = baseUrl + "onlinechat/VisitorLogin.po?id=register&VisitorUniqueId=" + sessionId + isCheckinto;
        chatWindow.document.writeln("<html><head><title>" + winName + "</title></head><body style='margin:0;' >");
        chatWindow.document.writeln("<input type='hidden' id='ChatOpen'>");
        chatWindow.document.writeln("<table border='0' height='100%' cellspacing='0' cellpadding='0' width='600'>");
        chatWindow.document.writeln("<tr><td height='100%' valign='top' align='center'>");
        chatWindow.document.writeln("<iframe scrolling='no' frameborder='0' width='601' height='508' src='" + chatUrl + "'></iframe>");
        chatWindow.document.writeln("</td></tr>");
        chatWindow.document.writeln("</table>");
        chatWindow.document.writeln("</body></html>");
    }

    chatWindow.focus();
}

/**
 * Used to add a comma to a number (1,000)
 * @para nStr Number string
 **/
function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function directParent(sUrl){
   //top.location.href = sUrl;
   window.location.href = sUrl;
}
