function loadPage(){
	try{
		updateClock(true);
	}catch(err){}
	try{
	scrollStations();
	}catch(err){}
	try{
	loadSlugs();
	}catch(err){}
}

var recSlugs = new Array();

function loadSlugs(){
	for(var i = 0; i < slugs.length; i++){
		var slug = slugs[i];
		var ajax = getAjaxObj();
		var handlerFunction = getReadyStateHandler(ajax, receiveTimeTable);
		ajax.open("POST", "TimeTableFetch?route=" + slug.route + "&direction=" + slug.direction + "&stop=" + slug.stop + "&timeStamp=" + slug.timeStamp, true);
		ajax.onreadystatechange = handlerFunction;
		ajax.send(null);
	}
	if(geoLocSupported && slugs.length > 1){
		geoSortSlugs();
	}
}

var stopGeoLocs;
function geoSortSlugs(){
	var ajax = getAjaxObj();
	var handlerFunction = getReadyStateHandler(ajax, receiveStopGeos);
	ajax.open("POST", "GeoFetch?killCache=" + (new Date()).getTime(), true);
	ajax.onreadystatechange = handlerFunction;
	ajax.send(null);
}

function receiveStopGeos(ajax){
	if(ajax.readyState == 4){
		var geoResponse = eval("(" + ajax.responseText + ")");
		if(typeof geoResponse != "undefined" && typeof geoResponse.data != "undefined" && geoResponse.data.length == slugs.length){
			stopGeoLocs = geoResponse.data;
			navigator.geolocation.getCurrentPosition(geoSortEls, function(){}, {maximumAge:300000});
		}
	}
}

var currentLon;
var currentLat;
function geoSortEls(position){
	currentLat = position.coords.latitude;
	currentLon = position.coords.longitude;
	stopGeoLocs.sort(locSort);
	console.debug(stopGeoLocs);
	for(var i = 0; i < stopGeoLocs.length - 1; i++){
		var dest = document.getElementById("pos_" + i);
		var src = document.getElementById(stopGeoLocs[i].timeStamp).parentNode;
		swapElements(src, dest);
	}
	if(isWebkit){
		for(var i = 0; i < slugs.length; i++){
			//have to thread jump for css to transition effect correctly
			setTimeout("document.getElementById(\"pos_" + i + "\").style.opacity = \"0\";document.getElementById(\"pos_" + i + "\").style.webkitTransition = \"opacity 0.5s linear\";", 1);
		}
		setTimeout("raiseTimeTables()", 1501);
	}
}

function raiseTimeTables(){
	for(var i = 0; i < slugs.length; i++){
		var raise = document.getElementById("pos_" + i);
		raise.style.webkitTransition = "opacity 1s linear";
		raise.style.opacity = "1";
	}
}

function swapElements(el1, el2){
	var idSwap = el1.id;
	var el1p = el1.parentNode;
	var el2p = el2.parentNode;
	el1p.appendChild(el2);
	el2p.appendChild(el1);
	el1.id = el2.id;
	el2.id = idSwap;
}

function locSort(a, b){
	var aDistance = Math.pow((currentLat - a.lat), 2) + Math.pow((currentLon - a.lon), 2);
	var bDistance = Math.pow((currentLat - b.lat), 2) + Math.pow((currentLon - b.lon), 2);
	return (aDistance - bDistance);
}

var geoLocSupported = false;
try{
	geoLocSupported = typeof navigator.geolocation != "undefined";
}catch(err){geoLocSupported = false;}

var isWebkit = false;
try{
	isWebkit = navigator.userAgent.indexOf("AppleWebKit") != -1;
}catch(err){isWebkit = false;}

function scrollStop(){
	try{
		if(geoLocSupported && stopGeosIndex > 8){
			navigator.geolocation.getCurrentPosition(scrollStopCallback, function(){}, {maximumAge:300000});
		}
	}catch(err){}
}

function scrollStopCallback(position){
	var latFound = position.coords.latitude;
	var lonFound = position.coords.longitude;
	var closestDistance = Number.MAX_VALUE;
	var closestIndex = -1;
	for(var i = 0; i < stopGeos.length; i++){
		var lat = stopGeos[i].stopLat;
		var lon = stopGeos[i].stopLon;
		var newDistance = Math.pow((latFound - lat), 2) + Math.pow((lonFound - lon), 2);
		if(newDistance < closestDistance){
			closestIndex = i;
			closestDistance = newDistance;
		}
	}
	if(closestIndex != -1){
		var closest = stopGeos[closestIndex];
		if(closest.stopGeosIndex > 7){
			//back up three to be more centered around the current location
			var centeredHashIndex = closest.stopGeosIndex - 3;
			for(var i = 0; i < stopGeos.length; i++){
				if(centeredHashIndex == stopGeos[i].stopGeosIndex){
					if(isWebkit){
						var stopForm = document.getElementById("stopForm");
						stopForm.style.webkitTransition = "opacity 1s linear";
						stopForm.style.opacity = "0";
						setTimeout("raiseStopForm()", 1000);
					}
					window.location.hash = stopGeos[i].stopId;
				}
			}
		}
	}
}

function raiseStopForm(){
	var stopForm = document.getElementById("stopForm");
	stopForm.style.webkitTransition = "opacity 1s linear";
	stopForm.style.opacity = "1";
}


function getAjaxObj(){
	if(window.XMLHttpRequest){
		return new XMLHttpRequest();//Not IE
	}
	else{
		try
	    {
	        return new ActiveXObject("Msxml2.XMLHTTP");
	    }   
	    catch (err)
	    {
	        try
	        {
	            return new ActiveXObject("Microsoft.XMLHTTP");
	        }
	        catch (err2)
	        {
	        }
	    }
	}
}

function getReadyStateHandler(req, responseXmlHandler) {  
    // Return an anonymous function that listens to the   
    // XMLHttpRequest instance  
    return function () {  
    // If the request's status is "complete"  
        if (req.readyState == 4) {  
            // Check that a successful server response was received  
   
            if (req.status == 200) {                  //todo: catch 404 error.  
                // Pass the XML payload of the response to the   
                // handler function  
                responseXmlHandler(req);  
            }else{  
                // An HTTP problem has occurred  
                //alert("HTTP error: "+req.status);  
                //$('lblError').innerHTML += "HTTP error: "+req.status;  
            }  
        }  
    }  
}

function receiveTimeTable(ajax){
	if(ajax.readyState == 4){
		var timeTableResponse = eval("(" + ajax.responseText + ")");
		if(typeof timeTableResponse != "undefined" && typeof timeTableResponse.timeStamp != "undefined"){
			var loadSpan = document.getElementById(timeTableResponse.timeStamp);
			var loadParent = loadSpan.parentNode;
			loadSpan.innerHTML = "";
			if(typeof timeTableResponse.error != "undefined"){
				var errorDiv = document.createElement("div");
				errorDiv.className = "error";
				errorDiv.appendChild(document.createTextNode(timeTableResponse.error));
				loadSpan.appendChild(errorDiv);
			}
			else if(typeof timeTableResponse.times != "undefined"){
				recSlugs.push(timeTableResponse.timeStamp);
				for(var i = 0; i < timeTableResponse.times.length; i++){
					if(typeof document.createElement != "undefined"){
						var timeDiv = document.createElement("div");
						timeDiv.className = "time";
						timeDiv.appendChild(document.createTextNode(timeTableResponse.times[i]));
						loadSpan.appendChild(timeDiv);
					}
					else{
						var theInner = "<div class='time'>";
						theInner += timeTableResponse.times[i];
						theInner += "</div>";
                        loadSpan.innerHTML += theInner;
					}
				}
			}
		}
		scrollStations();
	}
}

function lookupRoute(){
	var route = document.getElementById("routeNumber");
	if(typeof route.value == "undefined" || route.value == null || route.value == ""){
		//try to focus
		route.focus();
	}
	else{
		window.location.href = "selectDirection.jsp?route=" + route.value;
	}
}

function scrollStations(){
	var stationDivs = document.getElementsByTagName("div");
	for(var i = 0; i < stationDivs.length; i++){
		if(stationDivs[i].className == "station"){
			//console.debug(parseInt(stationDivs[i].offsetWidth) > 150);// &&  > 150
		}
		if(stationDivs[i].className == "station" && parseInt(stationDivs[i].offsetWidth) > 150){
			stationDivs[i].className += " marqueeify";
		}
	}
	for(var i = 0; i < stationDivs.length; i++){
		if(stationDivs[i].className == "timeTable"){
			stationDivs[i].style.width = "150px";
		}
	}
}

function updateClock(doCheckRefesh){
	var clock = document.getElementById("clock");
	var rightNow = new Date();
	var hour = rightNow.getHours();
	if(hour > 12){
		hour -= 12;
	}
	if(hour == 0){
		hour = 12;
	}
	if(typeof document.createTextNode != "undefined"){
		clock.innerHTML = "";
		clock.appendChild(document.createTextNode(hour + ":" + padZero(rightNow.getMinutes()) + ":" + padZero(rightNow.getSeconds())));
	}
	else{
		clock.innerHTML = hour + ":" + padZero(rightNow.getMinutes()) + ":" + padZero(rightNow.getSeconds());
	}
	setTimeout("updateClock(" + doCheckRefesh + ")", 1000);
	if(doCheckRefesh){
		checkRefresh();
	}
}

var theNow = (new Date()).getTime();
var origPageLoadTime = (new Date()).getTime();
var refreshInterval = 10*60*1000;
function checkRefresh(){
	if(origPageLoadTime + (50*60*60*1000) < (new Date()).getTime()){
		try{
			//this setter should be inconsequential, but just in case it will avoid constant squelched errors
			origPageLoadTime = (new Date()).getTime();
			location.reload(true);
		}catch(err){}
	}
	else if(theNow + refreshInterval < (new Date()).getTime()){
		//timeTableResponse.timeStamp
		theNow = (new Date()).getTime();
		for(var i = 0; i < recSlugs.length; i++){
			var timeTableSpan = document.getElementById(recSlugs[i]);
			timeTableSpan.innerHTML = "Loading...";
		}
		loadSlugs();
	}
}

function padZero(num){
	if(num < 10){
		return "0" + num;
	}
	return num;
}

function submitStopForm(stop, stopName){
	document.getElementById("stop").value = stop;
	document.getElementById("stopName").value = escape(stopName);
	document.getElementById("stopForm").submit();
}

function changeTheme(theTheme){
	eraseCookie("THEME");
	createCookie("THEME",theTheme,800)
	window.location.reload();
}

function resetCity(){
	eraseCookie("TRANSIT_CITY");
	deleteSavedRoutes(false);
	window.location.href = "selectCity.jsp";
}

function deleteSavedRoutes(redirectToIndex){
	for(var i = 0; i < slugTokens.length; i++){
		eraseCookie(slugTokens[i]);
	}
	if(redirectToIndex){
		window.location.href = "index.jsp";
	}
}

function createCookie(name,value,days) {
	if(days){
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else{
		var expires = "";
	}
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}