/*
 * Global variables to manage AJAX request/response.
 */
// Div Pointers
var startIndex = -1;
var divPointer = startIndex;

var method = new function() {
	this.POST = "POST";
	this.GET = "GET";
}

var divOrgCount = 0;
var divDesCount = 0;
var request;
var sendString;
var callbackFn;
var xmlData;
var main = '/bnsf.was6/RailMiles/RMController';

/**
 * Generic function to create an XmlHttpRequest object.
 * method          - HTTP method to be used - "POST" is recommended (use capital letters for Mozilla compatibility).
 * url             - The URL of the server program.<b>
 * isAsynchronous  - "true" for all AJAX requests. 
 * callbackFn      - The function to be called on successful completion. 
 */
function createRequest(method,url,isAsynchronous,callbackFunction) {
    request = null;
	callbackFn = callbackFunction;	
	    if(window.XMLHttpRequest) {
	    request = new XMLHttpRequest();
		} else if (window.ActiveXObject){
		request =  new ActiveXObject("Microsoft.XMLHTTP");	
	}	
	if (request != null) {
		request.onreadystatechange = processXMLResponse;			
		request.open(method, url, isAsynchronous);			
		// Specify that the body of the request contains form data
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	}else{
		alert("Your browser does not support XMLHTTP.");
	}	
	sendString = "isAJAXRequest=yes";	
	return request;
	
}

/*
 * Generic callback handling function for XML response. 
 * This executes the specified callback function in turn.
 */
function processXMLResponse() {
	if (request.readyState == 4) { // Complete	
		if (request.status == 200) { // OK response
			xmlData = request.responseXML;						
			window[callbackFn]();			
		} else {
			alert("Problem while processing XML response : " + request.statusText);
		}
	}
}

/* Navigates the drop down using up and down arrow keys */
function navigateDrpDwn(event,type,value) {

	var arrValues = null;
	var originObj = document.forms[0].elements["txtOrigin"];
	var destnObj = document.forms[0].elements["txtDestination"];
	var keyCode =(window.Event) ? event.which : event.keyCode;

	if(type == 'Origin'){

		arrValues = document.getElementById("Origin_ID");

		if('' != arrValues.innerHTML){

			var Len = arrValues.getElementsByTagName("Div").length;

			if (keyCode == 40) {

		  		if (Len > divPointer && divPointer > -2) {

					if(divPointer == startIndex){
						divPointer++;
						currDivObj = document.getElementById("divBoxOrg"+divPointer);
						optionsOver(currDivObj);
						originObj.value = currDivObj.innerHTML;
						currDivObj.scrollIntoView(false);
						
					}else if(divPointer == Len-1){
						currDivObj = document.getElementById("divBoxOrg0");
						prvDivObj = document.getElementById("divBoxOrg"+(Len-1));
						optionsOver(currDivObj);
						optionsOut(prvDivObj);
						originObj.value = currDivObj.innerHTML;
						currDivObj.scrollIntoView(false);
						divPointer = 0;
						
					}else{
						divPointer++;
						currDivObj = document.getElementById("divBoxOrg"+divPointer);
						prvDivObj = document.getElementById("divBoxOrg"+(divPointer-1));
						optionsOver(currDivObj);
						optionsOut(prvDivObj);
						originObj.value = currDivObj.innerHTML;
						currDivObj.scrollIntoView(false);
						
					}
		   			return;
		  		}else{

		  			divPointer = startIndex;
		  		}
		  		
			}else if (keyCode == 38) {
		  		if (Len > divPointer && divPointer > -2) {

					if(divPointer == 0 || divPointer == startIndex){
						currDivObj = document.getElementById("divBoxOrg"+(Len-1));
						prvDivObj = document.getElementById("divBoxOrg0");
						optionsOut(prvDivObj);
						optionsOver(currDivObj);
						divPointer = Len-1;
						originObj.value = currDivObj.innerHTML;
						currDivObj.scrollIntoView(false);
						
					}else{
						divPointer--;
						currDivObj = document.getElementById("divBoxOrg"+divPointer);
						prvDivObj = document.getElementById("divBoxOrg"+(divPointer+1)); 
						optionsOver(currDivObj);
						optionsOut(prvDivObj);
						originObj.value = currDivObj.innerHTML;
						currDivObj.scrollIntoView(false);
						
					}

		   			return;
		  		}else{		  		
		  			divPointer = startIndex;
		  		}

			}else if(keyCode == 13){

				arrValues.style.display = 'none';
				arrValues.innerHTML = '';
				divPointer = startIndex;
				destnObj.focus();
				return;

			}else if((keyCode == 27) || (keyCode== 9)){

				arrValues.style.display = 'none';
				arrValues.innerHTML = '';
				divPointer = startIndex;
				return;
			}

		}

	}else if(type == 'Destination'){

		arrValues = document.getElementById("Destination_ID");

		if('' != arrValues.innerHTML){

			var Len = arrValues.getElementsByTagName("Div").length;

			if (keyCode == 40) {

		  		if (Len > divPointer && divPointer > -2) {

					if(divPointer == startIndex){
						divPointer++;
						currDivObj = document.getElementById("divBoxDes"+divPointer);
						optionsOver(currDivObj);
						destnObj.value = currDivObj.innerHTML;
						currDivObj.scrollIntoView(false);
						
					}else if(divPointer == Len-1){
						currDivObj = document.getElementById("divBoxDes0");
						prvDivObj = document.getElementById("divBoxDes"+(Len-1));
						optionsOver(currDivObj);
						optionsOut(prvDivObj);
						destnObj.value = currDivObj.innerHTML;
						currDivObj.scrollIntoView(false);
						divPointer = 0;
						
					}else{
						divPointer++;
						currDivObj = document.getElementById("divBoxDes"+divPointer);
						prvDivObj = document.getElementById("divBoxDes"+(divPointer-1));
						optionsOver(currDivObj);
						optionsOut(prvDivObj);
						destnObj.value = currDivObj.innerHTML;
						currDivObj.scrollIntoView(false);
						
					}
		   			return;
		  		}else{

		  			divPointer = startIndex;
		  		}
		  		
			}else if (keyCode == 38) {
		  		if (Len > divPointer && divPointer > -2) {

					if(divPointer == 0 || divPointer == startIndex){
						currDivObj = document.getElementById("divBoxDes"+(Len-1));
						prvDivObj = document.getElementById("divBoxDes0");
						optionsOut(prvDivObj);
						optionsOver(currDivObj);
						divPointer = Len-1;
						destnObj.value = currDivObj.innerHTML;
						currDivObj.scrollIntoView(false);
						
					}else{
						divPointer--;
						currDivObj = document.getElementById("divBoxDes"+divPointer);
						prvDivObj = document.getElementById("divBoxDes"+(divPointer+1)); 
						optionsOver(currDivObj);
						optionsOut(prvDivObj);
						destnObj.value = currDivObj.innerHTML;
						currDivObj.scrollIntoView(false);
						
					}

		   			return;
		  		}else{		  		
		  			divPointer = startIndex;
		  		}

			}else if(keyCode == 13){

				arrValues.style.display = 'none';
				arrValues.innerHTML = '';
				divPointer = startIndex;
				return;

			}else if((keyCode == 27) || (keyCode == 9)){

				arrValues.style.display = 'none';
				arrValues.innerHTML = '';
				divPointer = startIndex;
				return;
			}

		}
	}
}

/* To get the list box values by submitting the the textbox value alone  */
function getValues(event,type) {

	var arrValues = null;
	var originObj = document.forms[0].elements["txtOrigin"];
	var destnObj = document.forms[0].elements["txtDestination"];

	//var eventKeyCode = window.event.keyCode;
	
	var eventKeyCode =(window.Event) ? event.which : event.keyCode;
	
	var isValidChar = false;
	// Escape if tab is pressed
	if((eventKeyCode > 64 && eventKeyCode < 91) || (eventKeyCode > 96 && eventKeyCode < 123)
		|| (eventKeyCode > 47 && eventKeyCode < 58) || (eventKeyCode == 32) || (eventKeyCode == 8)){

			isValidChar = true;
	}

	if(!isValidChar){
		return;
	}

	if(type == 'Origin'){

		arrValues = document.getElementById("Origin_ID");

		var prvArrValues = document.getElementById("Destination_ID");
		if(null != prvArrValues){
			prvArrValues.style.display = 'none';
			prvArrValues.innerHTML = '';
		}	

//		if(null != arrValues){
//			arrValues.style.display = 'none';
//			arrValues.innerHTML = '';
//		}	
		if ( trim(originObj.value) == "" || originObj.value.length < 3){ 
			return;
		}	

	}else if(type == 'Destination'){

		arrValues = document.getElementById("Destination_ID");

		var prvArrValues = document.getElementById("Origin_ID");
		if(null != prvArrValues){
			prvArrValues.style.display = 'none';
			prvArrValues.innerHTML = '';
		}	

//		if(null != arrValues){
//			arrValues.style.display = 'none';
//			arrValues.innerHTML = '';	
//		}		

		if ( trim(destnObj.value) == "" || destnObj.value.length < 3){ 
			return;
		}

	}	
	
	var reqst = null;			
	reqst = createRequest(method.POST,main,true,"updateValues");	
	
	if ( reqst != null ) {
		if(type == 'Origin'){			
			sendString += "&origin=" + trim(originObj.value) +"&isOrigin=yes";
		}else if(type == 'Destination'){			
			sendString += "&destination=" + trim(destnObj.value) +"&isDestination=yes";
		}			
		reqst.send(sendString);
	}
	
}
/* This is the call back function for the  values that are got.*/
function updateValues() {
	var list = null;
	// Get the elements from the document
	var elemDoc = '';
	var typeVal = '';
	var typeValue = '';
	var divId = '';
	var errMessage = "An error occurred while retrieving the Origin or Destination values";

	if (null != xmlData) {

		elemDoc = xmlData.getElementsByTagName("list")[0];

		if (null != elemDoc) {
			typeValue = elemDoc.getElementsByTagName("type")[0];
			
			if (null != typeValue) {
				typeVal = typeValue.firstChild.nodeValue;
				divPointer = startIndex
			}
		}else{
			var errorMsg = xmlData.getElementsByTagName("error")[0];
			
			if (null != errorMsg){
				errorMsg = errorMsg.firstChild.nodeValue;

				errMessage = errMessage + " \n\n" + "Error Details: \n";
				errMessage = errMessage + errorMsg;
				alert(errMessage);
				return false;

			}else{
				alert(errMessage);
				return false;
			}

		}

	}else{
		alert(errMessage);
		return false;
	}

	// Clear the HTML list used to display the contents
	if(typeVal == 'Origin'){		
		document.getElementById("Origin_ID").innerHTML = '';
		list = document.getElementById("Origin_ID");
		divOrgCount = 0;							
	}else if(typeVal == 'Destination'){
		document.getElementById("Destination_ID").innerHTML = '';	
		list = document.getElementById("Destination_ID");
		divDesCount = 0;					
	}
	
	// Loop over the values.	
	var arrVal = null;
	if (null != elemDoc) {
		arrVal = elemDoc.getElementsByTagName("opt");
	
	}
	if(null == arrVal || arrVal.length == 0){
		list.style.display = 'none';
	}else{
		list.style.display = '';
	}
	for (var i = 0 ; i < arrVal.length ; i++) {
		var val = arrVal[i];
		// Extract the text nodes from the name and quantity elements
		var name = val.getElementsByTagName("name")[0].firstChild.nodeValue;		
		var value = val.getElementsByTagName("value")[0].firstChild.nodeValue;
			
		var control = document.createElement("input");
		control.setAttribute("type","hidden");
		if(typeVal == 'Origin'){
			control.setAttribute("id","hidOrgDiv"+i);			
			control.setAttribute("name","hidOrgDiv"+i);						
		}else if(typeVal == 'Destination'){
			control.setAttribute("id","hidDesDiv"+i);			
			control.setAttribute("name","hidDesDiv"+i);					
		}		
		control.setAttribute("value",value);
		list.appendChild(control);
			
		var optionElement = document.createElement("<DIV>");
		if(typeVal == 'Origin'){
			optionElement.id = 'divBoxOrg'+i;
			divOrgCount++;							
		}else if(typeVal == 'Destination'){
			optionElement.id = 'divBoxDes'+i;
			divDesCount++;					
		}	
		optionElement.innerHTML = name;
		optionElement.onmouseover = function(){ optionsOver(this) }
		optionElement.onmouseout = function(){ optionsOut(this) }
		optionElement.onclick = function(){optionsValue(this);list.style.display = 'none'; }
		optionElement.value = value;
		list.appendChild(optionElement);		
	}	
}
function optionsOut(item){		
	item.className='div';
}
function optionsOver(item){		
	item.className='current';
}
function optionsValue(val){
		if(val.id.substring(0,9) == 'divBoxOrg'){				
			document.forms[0].elements["txtOrigin"].value = val.value;			
		}else if(val.id.substring(0,9) == 'divBoxDes'){
			document.forms[0].elements["txtDestination"].value = val.value;
		}
	
}

