//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.mainform[mainfield].value;
	if (letters.length>1) 	lookup(fieldref);

	if(evt) {
		var key=evt.keyCode? evt.keyCode : evt.charCode;
		}
	if(window.event){
		var key = (window.event) ? window.event.keyCode : ev.keyCode;
		}

	if(key==ARROWDN) {
		document.mainform[hiddenfield].value="1";
		showdropdown(divfield); 
		document.mainform[selectfield].focus();
		}
	if(key==ESC) {
		cleardropdown(divfield);
		document.mainform[hiddenfield].value="0";
		}
	if(key!=TAB) {
		if (letters.length<2) {
			cleardropdown(divfield);
			document.mainform[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(key==RETURN) {
			document.mainform[mainfield].focus();
			bi=document.mainform[selectfield].selectedIndex;
			document.mainform[mainfield].value=document.mainform[selectfield].options[bi].value;
			document.mainform[hiddenfield].value="0";
			cleardropdown(divfield);
			document.mainform[mainfield].focus();
			mapplotlookup(fieldref);
			}
		if(key==ESC) {
			document.mainform[mainfield].focus();
			}
		if(key==TAB) {
			document.mainform[hiddenfield].value="0";
			cleardropdown(divfield);
			document.mainform[mainfield].focus();
			}
		}
	if(window.event){
		var key = (window.event) ? window.event.keyCode : ev.keyCode;

		if(key==RETURN) {
			document.mainform[mainfield].focus();
			bi=document.mainform[selectfield].selectedIndex;
			document.mainform[mainfield].value=document.mainform[selectfield].options[bi].value;
			document.mainform[hiddenfield].value="0";
			cleardropdown(divfield);
			mapplotlookup(fieldref);

			}
		if(key==ESC) {
			document.mainform[mainfield].focus();
			}
		if(key==TAB) {
			document.mainform[hiddenfield].value="0";
			cleardropdown(divfield);
			document.mainform[mainfield].focus();
			}

		}
}

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.mainform[mainfield].focus();
	bi=document.mainform[selectfield].selectedIndex;
	document.mainform[mainfield].value=document.mainform[selectfield].options[bi].value;
	document.mainform[hiddenfield].value="0";
	cleardropdown(divfield);
	mapplotlookup(fieldref);

}



function lookup(fieldref) {
	//this function called when needing to get XML data

	var hiddenfield=fieldref+"hidden";
	var mainfield=fieldref+"field";

	//get letters from the form
	var letters = document.mainform[mainfield].value.toLowerCase();
	var firstletter = letters.substr(0,1);

	//set the URL to check
	var url =  "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.mainform[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');
				maplon=root_node.getAttribute('lon');
				maplat=root_node.getAttribute('lat');
				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.mainform[selectfield].options[k] = newoption;
					k=k+1;
					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.mainform[selectfield].options[k] = newoption;
					k=k+1;
					if(k>25)i=j;
					}
				//next bits handles the CRS code lookups
				if(letters.toUpperCase()==crs) {
					newoption = new Option(minfo, m, false, false);
					document.mainform[selectfield].options[k] = newoption;
					k=k+1;
					if(k>25)i=j;
					}

				}
			for (i=k;i<26;i++) {
				newoption = new Option("", "", false, false);
				document.mainform[selectfield].options[i] = newoption;
				}
			if(j==1) {
				if(document.mainform[selectfield].options[0].value.toLowerCase()==document.mainform[mainfield].value.toLowerCase()) cleardropdown(divfield);
				}
			if(k>0) {
				//make the dropdown visible
				showdropdown(divfield);
				}
		} 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;
	}
	
	//if more than two letters typed, also try geosearch for nearby stations
	if (letters.length>2) {
		//find how many stations are already in the auto-suggest list
		for (ik=0;ik<20;ik++) {
			if(document.mainform[selectfield].options[ik].value=="") {
				kl=ik+1;
				ik=99;
				}
		}

		//if less than 2, assume there are none
		if(kl<2) kl=0;
		//perform the geosearch
		getStationsFromPostcode(letters,'x',kl,selectfield,divfield);
		}

}


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";

	//unfortunately we need to list all fieldnames being used in the code below
	if(document.mainform[hiddenfield].value=="0") {
		if (fieldref=='to') setTimeout("cleardropdownconditional('to')",250);
		if (fieldref=='from') setTimeout("cleardropdownconditional('from')",250);
		if (fieldref=='lookup') setTimeout("cleardropdownconditional('lookup')",250);
		}

}


function updatefocus(fieldref) {
	//this function hides the drop down if the user highlights on the dropdown - to prevent it going away
	var hiddenfield=fieldref+"hidden";
	document.mainform[hiddenfield].value="1";

}

function cleardropdownconditional(fieldref) {
	//hides the drop down - called from a timer
	var hiddenfield=fieldref+"hidden";
	var divfield=fieldref+"select";
	if(document.mainform[hiddenfield].value=="0") {
		document.getElementById(divfield).style.visibility = "hidden";
	}
}

function cleardropdown(itemname) {
	document.getElementById(itemname).style.visibility = "hidden";

}

function showdropdown(itemname) {
	document.getElementById(itemname).style.visibility = "visible";
}

function mapplotlookup(fieldref) {
	//this function called when plotting a specific station on the map
	//we read the data by AJAX call referencing the selected station name  

	var mainfield=fieldref+"field";

	//get letters from the form
	var letters = document.mainform[mainfield].value.toLowerCase();
	var firstletter = letters.substr(0,1);

	//set the URL to check
	var url =  "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() { mapplotdataReceived(httpRequest, fieldref); };
	httpRequest.open('GET', url, true);
	httpRequest.send(null);

}

function mapplotdataReceived(httpRequest, fieldref) {
	//this function called once map plotting data received ok

        var map = new GMap2(document.getElementById("map_canvas"));
	var mapControl = new GMapTypeControl();
	map.addControl(mapControl);
	map.addControl(new GLargeMapControl());

	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.mainform[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');
				maplon=root_node.getAttribute('lon');
				maplat=root_node.getAttribute('lat');
				maplon=maplon*1;
				maplat=maplat*1;
				if(minfo=="") minfo=m;
				if(crs<999) crs=1;
				if(crs!=1) minfo=minfo+" ["+crs+"]<BR>&nbsp;<BR>Plan journey <A HREF=\"javascript:fs('"+m+"');\">from here</A> | <A HREF=\"javascript:ts('"+m+"');\">to here</A> ";
				n=m.substr(0,l);

				//next bit handles the mapping
				if(m==document.mainform[mainfield].value.toUpperCase()) {
				//alert(maplon+" "+maplat);
				if(maplon==0) alert('Sorry we do not have any mapping details for this station at the moment');

				map.setCenter(new GLatLng(maplon, maplat), 12);
				var point = new GLatLng(maplon, maplat);
				map.addOverlay(new GMarker(point));
				map.openInfoWindowHtml(point, minfo);
				}

				}
		} 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 searchfortown(fieldname) {
	//this function finds long lat for a station name, then calls a function to plot nearby stations
	//then call a function to plot nearby stations
    var townname = document.getElementById(fieldname).value;
	usePointFromPostcode(townname,townname);

}

function loadGoogleMap() {
      var initialize = function () {
        map = new google.maps.Map2(document.getElementById("map_canvas"));
        map.setCenter(new google.maps.LatLng(54.795, -2.2419), 5);
      }
      google.load("maps", "2.x", {"callback": initialize});
}


function testForEnter() 
{    
//not useded
         
} 

function fs(stationname) {
	//set the value of origin station from a hyperlink
	document.getElementById('OriginStation').value=stationname;

}

function ts(stationname) {
	//set the value of destination station from a hyperlink
	document.getElementById('DestinationStation').value=stationname;


}



function getStationsFromPostcode(postcode,title,appendat,selectfield,divfield) { 
//this function adds items to the autocomplete list based on postcode etc
		var localSearch = new GlocalSearch(); 
             		localSearch.setSearchCompleteCallback(null, 
                                function() { 
                                        if (localSearch.results[0]) 
                                        { 
						var resultLat = localSearch.results[0].lat; 
                                                var resultLng = localSearch.results[0].lng; 
						
						var headID = document.getElementsByTagName("head")[0];
						var newScript = document.createElement('script');
						newScript.type = 'text/javascript';
						newScript.src = 'http://www.fairlyuseful.co.uk/qjump/stationmaps/stationcompletepostcodejs.php?clong=' + resultLat + '&clat=' + resultLng + '&appendat=' + appendat + '&selectfield=' + selectfield;
						headID.appendChild(newScript);

						showdropdown(divfield);
                                        }else{ 
						//alert('Could not find this town or postcode');
                                        } 
				});
                        localSearch.execute(postcode + ", UK"); 
                } 


