//LibManager.require("frame.prototype.form");
LibManager.require("scheduler");


LibManager.isLoaded(
	['Scheduler'],
	function() { 
		Scheduler.schedule( 'ticketCode2', 'delayScript();');
	}
);

function delayScript() {
	setTimeout( 'TicketController.getTicketValues();', 150 );
}

var TicketController = {

	tickets: null,

	/*
	** Uses the value of the ticket code select box to create an array of tickets codes which will be
	** seperated into two selects
	*/
	getTicketValues: function( ) {
		var stationList = $('ticketCode2');
		//var ticketArray = new Array()
		var tickets = {};
		
		for(var i = 0; i < stationList.options.length; i++) {
			var tempArray = stationList.options[i].text.split(' - ');
			
			if( typeof tickets[ tempArray[0] ] != 'object' ) tickets[ tempArray[0] ] = {};
			tickets[ tempArray[0] ][ tempArray[1] ] = stationList.options[i].value;
		}
		
		this.tickets = tickets;
		
		this.createTicketTypeSelectBox(  );
		this.createStationsSelectBox( stationList );
		
		Event.observe("ticketType", "change", this.replaceTicketValues.bindAsEventListener( this ), false);
		Event.observe("ticketCode2", "change", this.replaceTicketValues.bindAsEventListener( this ), false);
	},

	/*
	** Create a new select box inside the Virgin Invisible Fares form to allow users to choose a ticket class
	*/
	createTicketTypeSelectBox: function (  ) {
		var newSelect = document.createElement("select");
		newSelect.setAttribute("id","ticketType");
	
		var railForm = document.getElementById("railForm");
		var refSelect = railForm.getElementsByTagName("div").item(1);
		railForm.insertBefore(newSelect,refSelect);
		
		var ticketType = $('ticketType');
		ticketType.options.length = 0;
		ticketType.options.add(new Option( "Standard" , "Standard"), 0);
		ticketType.options.add(new Option( "First Class" , "First Class"), 1);
	},
	
	/*
	** Alters the ticket code select box to just display the station name
	*/
	createStationsSelectBox: function(  stationList ) {
		stationList.options.length = 0;
		
		for( var location in this.tickets ) {
			stationList.options.add(new Option( location , this.tickets[ location ][ "Standard" ]));
		}
	},
	
	/*
	** Replaces the value of the ticket code with the correct code for the selected ticket class
	*/
	replaceTicketValues: function() {
		var ticketType = $('ticketType');
		var ticketLocation = $('ticketCode2');
		
		var location = ticketLocation.options[ticketLocation.selectedIndex].text;
		var ticket = ticketType.value
		
		ticketLocation.options[ticketLocation.selectedIndex].value = this.tickets[ location ][ ticket ];
		
		//console.log( ticketLocation.options[ticketLocation.selectedIndex].value );
	}

};