//Station name autocomplete
//AJAX script 
//RRowson Sep 2008
//Version 1.5
//Version 1.3 addresses onkeyup behaviour in Safari and Chrome, and prevent submit
//Version 1.4 handles problems not being able to submit when form focus lost unexpectedly
//Version 1.5 don't show empty lists and handle slow connections better

//change mainform to be the name of the form being used

function updatefield(fieldref,evt) {
	//this function called everytime a key is pressed in the main field
    var mainfield=fieldref+"field";
	var selectfield=fieldref+"dropdown";
	var hiddenfield=fieldref+"hidden";
	var divfield=fieldref+"select";
	var RETURN = 13;
	var TAB = 9;
	var ESC = 27;
	var ARROWUP = 38;
	var ARROWDN = 40;
	var key;
	var letters = document.getElementById(mainfield).value;

	if(evt) {
		var key=evt.keyCode? evt.keyCode : evt.charCode;
		}
	if(window.event){
		var key = (window.event) ? window.event.keyCode : ev.keyCode;
		}

	if((key!=RETURN) && (key!=TAB)) {
		if (letters.length>1) 	lookup(fieldref);
		}
		
	if(key==ARROWDN) {
		if ((document.getElementById(hiddenfield).value*1)>0) {
			document.getElementById(hiddenfield).value=(document.getElementById(hiddenfield).value*1)+1;
			showdropdown(divfield, hiddenfield, selectfield); 
			if(document.getElementById(selectfield).options[1].value!='') {
				setTimeout("document.getElementById('mainform').onsubmit = new Function('return false;');",25);
				document.getElementById(selectfield).focus();
				}
			}
		}
	if(key==ESC) {
		cleardropdown(divfield);
		document.getElementById(hiddenfield).value="0";
		}
	if(key!=TAB) {		
		if (letters.length<2) {
			cleardropdown(divfield);
			document.getElementById(hiddenfield).value="0";
			}
		}

}

function updatedropdown(fieldref,evt) {
	//this function called everytime a key is pressed in the drop down list

	var mainfield=fieldref+"field";
	var selectfield=fieldref+"dropdown";
	var divfield=fieldref+"select";
	var hiddenfield=fieldref+"hidden";
	var RETURN = 13;
	var TAB = 9;
	var ESC = 27;
	var ARROWUP = 38;
	var ARROWDN = 40;

	if(evt) {
		var key=evt.keyCode? evt.keyCode : evt.charCode;
		}
	if(window.event){
		var key = (window.event) ? window.event.keyCode : ev.keyCode;
		}
	
	if(key==RETURN) {
			bi=document.getElementById(selectfield).selectedIndex;
			if(bi>-1) document.getElementById(mainfield).value=document.getElementById(selectfield).options[bi].value;
			document.getElementById(hiddenfield).value="0";
			cleardropdown(divfield);
			
			document.getElementById(mainfield).focus();
			//2909 next two lines added to improve the moving of focus when selected
			if(fieldref=='from') setTimeout("document.getElementById('tofield').focus()",25);
			if(fieldref=='to' && document.getElementById('ttl-f34344a1-44a7-45fd-a116-e9f82e2d1517')) setTimeout("document.getElementById('ttl-f34344a1-44a7-45fd-a116-e9f82e2d1517').focus()",25);
			
			//SI778 for SBT sites  - next two lines added to improve the moving of focus when selected 
			if(fieldref=='ifrom') setTimeout("document.getElementById('itofield').focus()",25);
			if(fieldref=='ito' && document.getElementById('ttl-f34344a1-44a7-45fd-a116-e9f82e2d1517')) setTimeout("document.getElementById('ttl-f34344a1-44a7-45fd-a116-e9f82e2d1517').focus()",25);
			}
	if(key==ESC) {
			document.getElementById(hiddenfield).value="0";
			cleardropdown(divfield);
			document.getElementById(mainfield).focus();
			}
	if(key==TAB) {
			bi=document.getElementById(selectfield).selectedIndex;
			if(bi>-1) document.getElementById(mainfield).value=document.getElementById(selectfield).options[bi].value;
			document.getElementById(hiddenfield).value="0";
			cleardropdown(divfield);
			
			document.getElementById(mainfield).focus();
			//2909 next two lines added to improve the moving of focus when selected
			if(fieldref=='from') setTimeout("document.getElementById('tofield').focus()",25);
			if(fieldref=='to' && document.getElementById('ttl-f34344a1-44a7-45fd-a116-e9f82e2d1517')) setTimeout("document.getElementById('ttl-f34344a1-44a7-45fd-a116-e9f82e2d1517').focus()",25);
			
			//SI778 for SBT sites  - next two lines added to improve the moving of focus when selected 
			if(fieldref=='ifrom') setTimeout("document.getElementById('itofield').focus()",25);
			if(fieldref=='ito' && document.getElementById('ttl-f34344a1-44a7-45fd-a116-e9f82e2d1517')) setTimeout("document.getElementById('ttl-f34344a1-44a7-45fd-a116-e9f82e2d1517').focus()",25);
			}
}


function updatedropdownclick(fieldref) {
	//this function called everytime the mouse clicks on the drop down

	var mainfield=fieldref+"field";
	var selectfield=fieldref+"dropdown";
	var divfield=fieldref+"select";
	var hiddenfield=fieldref+"hidden";

	document.getElementById(mainfield).focus();
	bi=document.getElementById(selectfield).selectedIndex;
	document.getElementById(mainfield).value=document.getElementById(selectfield).options[bi].value;
	document.getElementById(hiddenfield).value="0";
	cleardropdown(divfield);
}


function lookup(fieldref) {
	//this function called when needing to get XML data
				
	var hiddenfield=fieldref+"hidden";
	var mainfield=fieldref+"field";
	document.getElementById(hiddenfield).value=1;
	
	//get letters from the form
	var letters = document.getElementById(mainfield).value.toLowerCase();
	var firstletter = letters.substr(0,1);

	//set the URL to check
	var url =  "/cm/xmlfull/" + firstletter + "_stations.xml";

	//set-up the xml feed
	var httpRequest;
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
            if (httpRequest.overrideMimeType) {
                httpRequest.overrideMimeType('text/xml');
            }
        } 
        else if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } 
                catch (e) {
                           try {
                                httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                               } 
                             catch (e) {}
                          }
                                       }

        if (!httpRequest) {
            //alert('Cannot connect to station data');
            return false;
        }

        httpRequest.onreadystatechange = function() { dataReceived(httpRequest, fieldref); };
	httpRequest.open('GET', url, true);
	httpRequest.send(null);

}

function dataReceived(httpRequest, fieldref) {
	//this function called once data received ok
	
	var mainfield=fieldref+"field";
	var selectfield=fieldref+"dropdown";
	var divfield=fieldref+"select";
	var hiddenfield=fieldref+"hidden";

	if (httpRequest.readyState == 4) {
	    // everything is good, the response is received
		if (httpRequest.status == 200) {
		    // perfect
	                //alert(httpRequest.responseText);
			var xmldoc = httpRequest.responseXML;
			var root_node = xmldoc.getElementsByTagName('NumberOfResults').item(0);
			j=root_node.firstChild.data;
			k=0;
			var letters = document.getElementById(mainfield).value.toLowerCase();
			l=letters.length;
			for (i=0;i<j;i++) {
				var root_node = xmldoc.getElementsByTagName('stationName').item(i);
				m=root_node.firstChild.data;
				minfo=root_node.getAttribute('info');
				crs=root_node.getAttribute('crs');
				if(minfo=="") minfo=m;
				if(crs<999) crs=1;
				if(crs!=1) minfo=minfo+" ["+crs+"]";
				n=m.substr(0,l);
				if(letters.toUpperCase()==n) {
					newoption = new Option(minfo, m, false, false);
					document.getElementById(selectfield).options[k] = newoption;
					k=k+1;
					crs='';
					if(k>25)i=j;
					}
				//next bits handles the London lookups
				if("LONDON "+letters.toUpperCase()==m.substr(0,(l+7))) {
					newoption = new Option(minfo, m, false, false);
					document.getElementById(selectfield).options[k] = newoption;
					k=k+1;
					crs='';
					if(k>25)i=j;
					}
				//next bits handles the CRS code lookups
				if(letters.toUpperCase()==crs) {
					newoption = new Option(minfo, m, false, false);
					document.getElementById(selectfield).options[k] = newoption;
					k=k+1;
					if(k>25)i=j;
					}
				}
			for (i=k;i<26;i++) {
				newoption = new Option("", "", false, false);
				document.getElementById(selectfield).options[i] = newoption;
				}
			if(j==1) {
				if(document.getElementById(selectfield).options[0].value.toLowerCase()==document.getElementById(mainfield).value.toLowerCase()) cleardropdown(divfield);
				}
			//2909 added the next three lines to prevent empty lists being shown	
			if(k==0) {
				cleardropdown(divfield);
				}
			if(k>0) {
				//make the dropdown visible
				showdropdown(divfield, hiddenfield, selectfield);
				}
		} else {
		    // there was a problem with the request,
		    // for example the response may be a 404 (Not Found)
		    // or 500 (Internal Server Error) response codes
	            return false;
		}
	} else {
	    // still not ready
            return false;
	}
	

}

function updatefocus(fieldref) {
	//this function locks the drop down if the user highlights on the dropdown - to prevent it going away
	var hiddenfield=fieldref+"hidden";	
	document.getElementById(hiddenfield).value=2;
    
}

function lostfoc(fieldref) {
	//this function hides the drop down if the user clicks away
	//wait 200ms though incase they are clicking on the drop down itself
	var hiddenfield=fieldref+"hidden";
	if (fieldref=='to') setTimeout("cleardropdownconditional('to');",200);
    if (fieldref=='from') setTimeout("cleardropdownconditional('from');",200);
	
	//SI778 for All Corporate SBT'S
	if (fieldref=='ito') setTimeout("cleardropdownconditional('ito');",200);
    if (fieldref=='ifrom') setTimeout("cleardropdownconditional('ifrom');",200);
	
}

function cleardropdownconditional(fieldref) {
	var hiddenfield=fieldref+"hidden";
	var divfield=fieldref+"select";
	
	if((document.getElementById(hiddenfield).value*1)<2) {
		document.getElementById(divfield).style.visibility = "hidden";
		setTimeout("document.getElementById('mainform').onsubmit = new Function('');",200);
	}
	//stop the field being shown
	document.getElementById(hiddenfield).value="0";
}


function cleardropdown(itemname) {
            document.getElementById(itemname).style.visibility = "hidden";
            setTimeout("document.getElementById('mainform').onsubmit = new Function('');",200);
}

function showdropdown(itemname, hiddenname, selectfield) {
		if((document.getElementById(hiddenname).value>0) && (document.getElementById(selectfield).options[1].value!='')){
            document.getElementById(itemname).style.visibility = "visible";
			setTimeout("document.getElementById('mainform').onsubmit = new Function('return false;');",200);

            }
}


