var metlinkRoutes = {"200":2994, "201":2997, "202":728, "203":3000, "205":730, "207":3003, "235":1876, "237":1901, "238":1902, "246":1903, "250":3006, "251":3009, "253":3012, "270":748, "271":1961, "273":750, "279":751, "280":1960, "281":1954, "282":1959, "284":754, "285":1282, "286":756, "293":759, "295":760, "301":3015, "302":3018, "303":3021, "304":3024, "305":3027, "306":3030, "307":3036, "308":3033, "309":3039, "313":773, "315":774, "316":775, "318":3042, "319":3045, "340":1913, "350":1907, "364":779, "366":781, "367":782, "688":930, "689":931, "690":932, "694":935, "695":3357, "697":937, "699":939, "701":942, "703":943, "704":944, "706":2517, "732":948, "733":949, "734":950, "735":951, "736":952, "737":953, "738":954, "740":955, "742":956, "745":957, "753":959, "754":960, "755":961, "757":962, "758":963, "765":964, "766":965, "767":966, "768":4801, "903":1695, "966":1886, "968":1817};

function dataStore(){
	this.testString = "Hello There!";	
	this.routeNumber = null;
	this.direction = null;
	this.routecode = null;
	this.stop = null;
	this.stopname = null;
	this.directions = null;

	this.finishedLoadingStep1 = false;

}


/* -----------------------------------------------------------------------------------------

	Step Object
	
   ----------------------------------------------------------------------------------------- */


function Step(divId,stepNum,initFn,actionFn) {
	
	//Property List
	this.divName = divId;
	this.divPointer = document.getElementById(divId);
	this.stepNum = stepNum;
	
	// Methods
	this.disableStep = disableStep;		//hide and show
	this.enableStep = enableStep;
		
	this.initialise = initFn;			// Perform any setup, eg, populating with routes
	this.action = actionFn;				// Perform any action on select, eg, move to next step
	
	// "Constructor"
	this.disableStep();
}

function disableStep(){
	this.divPointer.style.display = "none";
}

function enableStep(){
	//this.divPointer.className = "step inactive";
	this.divPointer.style.display = "block";
}

/* Specific Step Functions */

// Step 1
var timerStep1 = null; // Acck! Global!!

function step1Init(){
	
	$("#step1routes").empty();

	$("<option>" + "Please Select" + "</option>").attr("value","-1").appendTo("#step1routes");
	$("<option>" + "----------------------------------" + "</option>").attr("value","-1").appendTo("#step1routes");
	
	// populateSelect("step1routes",1); // Dummy data
	
	$.getJSON("http://www.venturabus.com.au/cgi-bin/venturabus/nextbus/nextbus.pl?action=step1",
		function(data){
			var j = 0;
			$.each(data.venturaroutes.routes, function(i,route){
				y = (externalRouteNumber == i) ? " selected=\"selected\"" : "";
				$("<option" + y + ">" + route + "</option>").attr("value",i).appendTo("#step1routes");
				//$("<option>" + route + "</option>").attr("value",i).appendTo("#step1routes");
			}); // end each

			venturaData.finishedLoadingStep1 = true;

		}); // end function and end $.getJSON operation

		// The "A" in "AJAX" stands for "asynchronous". It means we can't depend on
		// the callback function being called before any following calls or statements.
		// So... we have to wait around for it to finish!

}



function step1InitOld(){
	
	$("#step1routes").empty();

	$("<option>" + "Please Select" + "</option>").attr("value","-1").appendTo("#step1routes");
	$("<option>" + "----------------------------------" + "</option>").attr("value","-1").appendTo("#step1routes");
	
	// populateSelect("step1routes",1); // Dummy data
	
	$.getJSON("http://www.venturabus.com.au/cgi-bin/venturabus/nextbus/nextbus.pl?action=step1",
		function(data){
			var j = 0;
			$.each(data.venturaroutes.routes, function(i,route){
				$("<option>" + route + "</option>").attr("value",i).appendTo("#step1routes");
				venturaData.Routes.push(route);
				if (j < 2) {
					alert(venturaData.testString); j++; 
				}
			}); // end each
		}); // end function and end $.getJSON operation
}

function check(){

	//var n = document.getElementById("step1routes");
	//alert(n.length);

	alert("Testing: " + venturaData.Routes);
}
function step1Do(){
	
	var listbox = document.getElementById("step1routes"); // reference to the <select> in the page
	var value = listbox[listbox.selectedIndex].value; // get the value for the selected item

	if(value > 0){
		venturaData.routeNumber = value;
		return true;
	} else {
		return false;
	}
}


// Step 2

function step2Init(){
	//alert("step2Init");
	// populateSelect("step2direction",2); // Dummy Data
	//if(debug){console.log("step2Init: Step 2 Initialising.")}
	venturaData.directions = new Array();
	$("#step2directions").empty();

	$("<option>" + "Please Select" + "</option>").attr("value","").appendTo("#step2directions");
	$("<option>" + "----------------------------------" + "</option>").attr("value","").appendTo("#step2directions");

	$.getJSON("http://www.venturabus.com.au/cgi-bin/venturabus/nextbus/nextbus.pl?action=step2&routenumber=" + venturaData.routeNumber,
		function(data){
			$.each(data.venturadirections.directions, function(i,route){
				$("<option>" + route + "</option>").attr("value",route).appendTo("#step2directions");
			}); // end each

			$.each(data.venturadirections.codes, function(i,code){
				venturaData.directions.push(code);
			});

	}); // end function and end $.getJSON operation

}

function step2Do(){
	var listbox = document.getElementById("step2directions"); // reference to the <select> in the page
	var value = listbox[listbox.selectedIndex].value; // get the value for the selected item

	if(value != ""){
		venturaData.direction = value;
		return true;
	} else {
		return false;
	}
	//return (value > 0) ? true : false;
}


// Step 3

function step3Init(){
	//populateSelect("step3stops",3);

	var queryStr = "routenumber=" + venturaData.routeNumber + "&direction=" + escape(venturaData.direction);
	var divname = "#step3stops";
	$(divname).empty();

	$("#step3messages").empty();
	$("<option>" + "Please Select" + "</option>").attr("value","").appendTo(divname);
	$("<option>" + "----------------------------------" + "</option>").attr("value","").appendTo(divname);

	$.getJSON("http://www.venturabus.com.au/cgi-bin/venturabus/nextbus/nextbus.pl?action=step3&" + queryStr,
		function(data){
			if(data.venturastops.additional.error == ""){
				$("#step3messages").css("display", "none");
				$("#step3content").css("display", "block");
				venturaData.routecode = data.venturastops.additional.routecode;
				$.each(data.venturastops.stops, function(i,stop){
					$("<option>" + stop + "</option>").attr("value",i).appendTo(divname);
				}); // end each
			} else {
				// Hide the content, and show the messages, with an error message
				$("#step3content").css("display", "none");
				$("<p>" + data.venturastops.additional.error + "</p>").appendTo("#step3messages");
				var links = "";
				for(var i = 0; i < venturaData.directions.length; i++){
					links += "<li><a href=\"http://www.venturabus.com.au/" + venturaData.directions[i][0] + "\">" + venturaData.directions[i][1] + "</a></li>"
				}
				$("<ul>" + links + "</ul>").appendTo("#step3messages");
				$("#step3messages").css("display", "block");
			}
		}); // end function and end $.getJSON operation
}


function step3Do(){
	
	// now, all we need is the route code, and the stop line, to show the time!!

	$("#step4clock ul").empty();
	$("#step4messages").empty();
	$("#step4legendcontent").empty();

	var listbox = document.getElementById("step3stops"); // reference to the <select> in the page
	var value = listbox[listbox.selectedIndex].value; // get the value for the selected item

	if(value != ""){
		if(countdownTimer != null){
			clearInterval(countdownTimer);
			countdownTimer = null;
		}
		venturaData.stop = value;
		venturaData.stopname = listbox.options[listbox.selectedIndex].text;
		return true;
	} else {
		return false;
	}
}

function step4Init(){


	if(countdownTimer != null){
		clearInterval(countdownTimer);
		countdownTimer = null;
	}

	var queryStr = "routecode=" + escape(venturaData.routecode) + "&stop=" + escape(venturaData.stop) + "&routeno=" + escape(venturaData.routeNumber) + "&ms=" + new Date().getTime();
	var divname = "#step4clock";


	//if(debug){console.log("step4Init: Start")}
	$.getJSON("http://www.venturabus.com.au/cgi-bin/venturabus/nextbus/nextbus.pl?action=step4&" + queryStr,
		function(data){
			if(data.venturastops.messages["error"] == ""){

				// Show the next times and countdown

				$("#step4messages").css("display", "none");
				$("#step4content").css("display", "block");

				$("#step4clock ul").empty();
				$("#step4legendcontent").empty();
				$("#step4messages").empty();
				$.each(data.venturastops.nexttimes, function(i,bustime){
					$("<li>" + bustime + " hrs</li>").appendTo(divname + " ul");
				}); // end each


				if(countdownTimer != null){
					clearInterval(countdownTimer);
					countdownTimer = null;
				}
				// Initialise the clock. This is not in any kind of object because
				// IE6 wasn't playing nice, and IE6 is what Ventura use :-(

				countdownHours = data.venturastops.time.hours;
				countdownMinutes = data.venturastops.time.minutes;
				countdownSeconds = data.venturastops.time.seconds;

        			updateDisplay();
				countdownTimer = setInterval ( "updateCountdown()", 1000 );

				// Write in the Legend

				$.each(data.venturastops.legend, function(i,mark){
					$("<p>" + i + " : " + mark + "</p>").appendTo("#step4legendcontent");
				});


			} else {


				// Hide the content, and show the messages, with an error message
				$("#step4content").css("display", "none");
				$("<p>" + data.venturastops.messages["error"] + "</p>").appendTo("#step4messages");
				var links = "";
				//for(var i = 0; i < venturaData.directions.length; i++){
					//links += "<li><a href=\"http://www.venturabus.com.au/" + venturaData.directions[i][0] + "\">" + venturaData.directions[i][1] + "</a></li>"
					//links += "<li><a href=\"http://www.venturabus.com.au/timetables/" + venturaData.routeNumber + ".pdf\">Timetable for Route " +  venturaData.routeNumber + " (PDF file)</a></li>"
					links += "<li><a href=\"http://www.metlinkmelbourne.com.au/route/view/" + metlinkRoutes[venturaData.routeNumber] + "\" target=\"metlinkWindow\">Timetable for Route " +  venturaData.routeNumber + " (opens in a new window)</a></li>"
				//}
				$("<ul>" + links + "</ul>").appendTo("#step4messages");
				$("#step4messages").css("display", "block");
			}
		}); // end function and end $.getJSON operation
	
}

function step4Do(){
	return false;
}


/* -----------------------------------------------------------------------------------------

	Step Controller Object

   ----------------------------------------------------------------------------------------- */

// Requires the number of steps, and the number of the current step

function stepController(numSteps,currentStep){
	
	// Properties
	this.numSteps = numSteps;
	this.currentStep = currentStep;
	this.steps = new Array();

	
	// Methods
	this.showStep = showStep;
	this.nextStep = nextStep;
	this.addStep = addStep;
	
	this.checkStep = checkStep;
	
	this.start = start;
	this.start2 = start2;
	this.continueStep1 = continueStep1;
}


function checkStep1(){

	if(venturaData.finishedLoadingStep1){
		clearInterval(timerStep1);
		nextBusSteps.continueStep1();
	}
}

function continueStep1(){
	this.steps[this.currentStep - 1].enableStep(); // This works. It's a normal method
	var j = document.getElementById("step1routes");
	this.checkStep(1);
}

function start2(){

	// Initialise Step 1

	this.steps[this.currentStep - 1].initialise();
	timerStep1 = setInterval("checkStep1()", 200);

	// Now, we can't do much until we have the selected index, so loop...

//	var n = document.getElementById("step1routes");
//	var j = document.getElementById("step1routes");
//	while(j.length < 40){
//		j = document.getElementById("step1routes");
//	}
//	this.checkStep(1);
	//venturaData.routeNumber = externalRouteNumber;
	//this.steps[this.currentStep].initialise();


	// Set Step 1 to pStepNumber
	//alert($("#step1routes").selectedIndex);
	//$("#step1routes").selectedIndex = 5;
	//$("#step1routes").selectedIndex
	// Execute Step1Do
}

function start(){
	/*	for(i in this.steps[this.currentStep - 1]){
			alert(i + " : \n" + this.steps[this.currentStep - 1][i]);		
		}*/
	this.steps[this.currentStep - 1].initialise();
	this.steps[this.currentStep - 1].enableStep(); // This works. It's a normal method

	$("#infoStepNum").html(this.currentStep);
}

function addStep(step){
	this.steps.push(step);
}


function checkStep(stepNo){
	
	// Check if the step just triggered is the same as the current step that the script knows about
	// It's possible to change step 1, even though you are at step 4. If this is the case, the script
	// will back up to the altered step .
	
	if(stepNo < this.currentStep){
	
		this.currentStep = stepNo; // Set Current Step to this step
		this.showStep(); // Hide all steps afterwards

		// Reset the steps. We need to call checkStep again so that any actions on the previous
		// step are executed (eg: choosing a new route at Step 1 while on Step 2. If you don't,
		// it sits there like a pudding.

		//if(debug){console.log("Resetting Steps; Recursing ... ");}
		this.checkStep(this.currentStep);
	} else {
	
		// Check the return value of the steps action function. This'll test if someone has selected
		// the right thing (or not).
	
		if(this.steps[this.currentStep - 1].action()){
			this.nextStep();
		}	 
		//alert("Doing nothing");
	
		$("#infoStepNum").html(this.currentStep);
	}
}


function nextStep(){
	
	if(this.currentStep < this.numSteps){
		this.currentStep++;
	}
	this.steps[this.currentStep - 1].initialise();
	this.showStep();

	$("#infoStepNum").html(this.currentStep);
}

// Function: showStep
// Turns on/off a series of sequential <div>s according to number of divs, and 

function showStep(){
	
	for(var i = 1; i < this.numSteps; i++){
		
		// Get a reference to the <div> with an ID of step/n/
		var stepdiv = document.getElementById("step" + i);
		// If it's the current step or a previous step, it should stay on; otherwise it should be turned off
		if( i > this.currentStep){
			stepdiv.style.display = "none";
		} else {
			stepdiv.style.display = "block";	
		}
	}// END for
}



/* COUNTDOWN OBJECT */


function Countdown(pHour,pMin,pSec,pDivname){
	
	// Property List
	this.hours = pHour;
	this.minutes = pMin;
	this.seconds = pSec;
	this.divname = pDivname;
	this.timer = null;
	
	// Methods
	
	this.initCountdown = initCountdown;
	this.updateCountdown = updateCountdown;
	this.updateDisplay = updateDisplay;
	this.clearCountdown = clearCountdown;
}



function initCountdown(){
	
	// A few workarounds since setInterval() doesn't work so great in an Object context
	
	var thisObject = this;
	
	this.updateDisplay();
	this.timer = setInterval(function(){thisObject.updateCountdown()},1000);
}

function clearCountdown(){
	clearInterval(this.timer);
	this.timer = null;
}

function updateCountdown(){
	
		// This code is flawed and will need fixing, but it works okay
		// as a temporary approximation.
	
		if(countdownHours <= 0 && countdownMinutes <= 0 && countdownSeconds <= 0){
			clearInterval(countdownTimer);
			countdownTimer = null;
			setTimeout("nextbusSteps.step4Init()",10000);
		}
		else {
			// If you don't have the > 0 bit, when initialised
			// with, say, 00:00:25, it quickly goes negative!!!

			if(countdownMinutes == 0 && countdownHours > 0){
				countdownHours--;
				countdownMinutes == 59;
			}
			
			if(countdownSeconds == 0 && countdownMinutes > 0){
				countdownMinutes--;
				countdownSeconds = 59;
			}
			
			countdownSeconds--;
		}
		
		updateDisplay();
}


function updateDisplay(){
	document.getElementById("nextclock").innerHTML = "<p>" + pad(countdownHours,2) + " hours, " + pad(countdownMinutes,2) + " mins, " + pad(countdownSeconds,2) + " seconds.</p>"
}



function pad(number, length) {
   
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
   
    return str;

}


// This function randomly adds a couple of random items to a select box

var colours = new Array("red", "blue", "violet", "indigo", "yellow", "lime", "brown" ,"black", "grey", "orange", "green", "pink", "purple");

var elements = new Array ("pawn", "rook", "knight", "bishop", "queen", "king", "wand", "pentacle", "cup", "joker", "diamond", "heart", "club", "spade", "page");

var zodiac = new Array("scorpio", "cancer", "virgo", "gemini", "aries", "taurus", "capricorn", "pisces", "leo", "libra", "sagittarius", "aquarius");
	
function populateSelect(selectID,stepNo) {

	var selectBox = document.getElementById(selectID);
	
	$(selectBox).empty();
	
	$("<option>" + "Please Select" + "</option>").attr("value","-1").appendTo(selectBox);
	$("<option>" + "----------------------------------" + "</option>").attr("value","-1").appendTo(selectBox);
	
	var numberOptions = Math.ceil(5 * Math.random()) + 2;
	var valueNumber = 100;
	
	for(var i = 0; i < numberOptions; i++){
	
		var rndColour = colours[Math.ceil((colours.length - 1) * Math.random())];
		var rndElement = elements[Math.ceil((elements.length -1) * Math.random())];
		var rndZodiac = zodiac[Math.ceil((zodiac.length -1) * Math.random())];
		
		var newString = "STEP " + stepNo + ": " + rndElement + " " + rndColour + " " + rndZodiac;
		var newOption = Math.ceil(700 * Math.random());
		
		$("<option>" + newString + "</option>").attr("value",valueNumber+=5).appendTo(selectBox);
		
	}
}
