// TIMETABLE CORE
//
// DESC: frontend for the language specific data pile
// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 

// GLOBALS

var ssurl = '/cgi-bin/timetable/wttlist.cgi';


//
// convert html select object to prototype hash
//
function htmlSelectToHash( pSelect ) {
	var tempHash = new String();
	tempHash += 'var tempHash = $H({';
	for (var i=0; i<pSelect.options.length; i++) 
	{
		tempHash += pSelect.options[i].value + ': "' + pSelect.options[i].text + '"';
		if (i != pSelect.options.length-1) { tempHash += ', '; }
	}
	tempHash += '});';
	eval(tempHash);
	return tempHash;
}


//
// convert string to prototype hash (usually from location.search)
//

String.prototype.toHash = function () {
	var tempHash = new String();
	var locSrc = this;
	
	if (locSrc.indexOf('?') == 0) { locSrc = locSrc.substr(1,locSrc.length); }
	rExp = new RegExp("['\\/;(){}:]", "gi");
	locSrc = locSrc.replace(rExp,'',locSrc);
	
	var lSplit = locSrc.split('&');
	tempHash += 'var tempHash = $H({';
	
	for (var i=0; i<lSplit.length; i++) 
	{
		var kval = lSplit[i].split('=');
		if (kval[0] != '')
		{
			if (!kval[1]) { kval[1] = ''; }
			tempHash += kval[0] + ': "' + kval[1] + '"';
			if (i != lSplit.length-1) { tempHash += ', '; }
		}
	}
	tempHash += '});';
	eval(tempHash);
	return tempHash;
}



//
// look up abbreviation if possible
//
lookupCityAbbrev = function( pAbbrev ) {
	if ((Dests.indexOf(pAbbrev) == -1) || (pAbbrev == 0))
	{ 
		return null; 
	} else { 
		return (eval('s'+pAbbrev)); 
	}
}


//
// build simple select box (option = value)
//
function buildSimpleSelectBox( pSelectBox, pStringArray ) {
	var targetSelBox = $(pSelectBox);
	if (targetSelBox != null) 
	{
		var targetSelBox = $(pSelectBox);
		targetSelBox.length = 0;
		
		pStringArray.each( function(stringItem){
			if (stringItem != '')
			{   
			    displayedStringItem = stringItem.split(' ');
			    displayedStringItem0 = displayedStringItem[0].split('.');
			    displayedStringItem1 = displayedStringItem[1].split('.');
			    // new date format dd/mm/yy
				targetSelBox.options[targetSelBox.options.length] = 
					new Option(displayedStringItem0[2]+"/"+displayedStringItem0[1]+"/"+displayedStringItem0[0]+" - "+displayedStringItem1[2]+"/"+displayedStringItem1[1]+"/"+displayedStringItem1[0], stringItem, false, false);
			}
		});
		
		targetSelBox.disabled = false;
		targetSelBox.rebuilt = true;
		
		targetSelBox.options[0].selected = "selected";
		if (targetSelBox.onchange) targetSelBox.onchange();
	}
}


//
// build select box with array of abbreviations
//
function buildSelectBox( pSelectBox, pAbbrevArray ) {
	var targetSelBox = $(pSelectBox);
	if (targetSelBox != null) 
	{
		var buffer = null;
		if ( targetSelBox.className.indexOf('jsProtectfirst') != -1 )
			{ buffer = targetSelBox.options[0]; }
		
		targetSelBox.length = 0;
		if (buffer != null) { targetSelBox.options[0] = buffer; }
		
		pAbbrevArray.each( function(abbrev){
			cityName = lookupCityAbbrev(abbrev);
			if (cityName != null)
			{
				targetSelBox.options[targetSelBox.options.length] = 
					new Option(cityName, abbrev, false, false);
			}
		});
		
		targetSelBox.disabled = false;
		targetSelBox.rebuilt = true; //do we need this here?
		
		targetSelBox.options[0].selected = "selected";
		if ((targetSelBox.onchange) && (targetSelBox.disabled == false)) targetSelBox.onchange();
	}
}


//
// simple frontend for build select box
//
function buildSelectBoxFE( pSelectBox, pHtmlSelect ) {
	abbrev = (pHtmlSelect.options[pHtmlSelect.selectedIndex].value);
	if (lookupCityAbbrev(abbrev) != null)
	{
		buildSelectBox(pSelectBox,eval('a'+abbrev));
	}
}

function stepOption( pTarget, pDelta) {
	selBox = $(pTarget);
	selI = selBox.options.selectedIndex;
	selOld = selI;
	selI += pDelta;
	
	if (selI < 0) selI = 0;
	if (selI > selBox.options.length-1) selI = selBox.options.length-1;
	
	selBox.options.selectedIndex = selI;
	if (selI != selOld) selBox.onchange();
	return false;
}

//---------------------------------
// xmlhttp related logic
//---------------------------------

function replay() {
	//replay should be called step by step, so this all at once version is disabled for now
	/*
	if ($('jsDepartureSave').value)
		{ $('jsDeparture').selectedIndex = $('jsDepartureSave').value; $('jsDeparture').onchange(); }
	if ($('jsArrivalSave').value)
		{ $('jsArrival').selectedIndex = $('jsArrivalSave').value; $('jsArrival').onchange(); }
	if ($('jsWotSave').value)
		{ $('jsWot').selectedIndex = $('jsWotSave').value; $('jsWot').onchange(); }
	*/
}


//
// parses "?from=AAA&to=BBB" GET parameter
//
function parseExternalParams() {
	var valFromPos;
	var valToPos;
	
	var locHash = location.search.toUpperCase().toHash();
	var hEjsDeparture = $('jsDeparture');
	var hEjsArrival   = $('jsArrival');

	//convert select to hash and fetch index of key
	valFromPos = 
		htmlSelectToHash(hEjsDeparture).keys().indexOf( locHash['FROM'] );
	
	if (valFromPos != -1)
	{
		hEjsDeparture.selectedIndex = valFromPos;
		hEjsArrival.suspended = true; //suspend auto trigger
		hEjsDeparture.onchange();
		
		valToPos = 
			htmlSelectToHash(hEjsArrival).keys().indexOf( locHash['TO'] );
		if (valToPos != -1)
		{
			hEjsArrival.selectedIndex = valToPos;
		}
		
		hEjsArrival.suspended = false;
		hEjsArrival.onchange();
	}
}

//
// lock/release input fields
//
function inputsDisabled ( pForm, pState ) {
	var htmlElements = $A($(pForm).getElementsByTagName('*'));
	htmlElements.each( function(htmlElement){
		var tn = htmlElement.tagName;
		if (((tn == 'INPUT') || (tn == 'SELECT')) && (htmlElement.type != 'hidden'))
			{ htmlElement.disabled = pState; }
	});
}


//
// initiate in-progress event handling
//
var globalHandlers = {
	onCreate: function(){
		Element.show('divPlsWait');
		inputsDisabled('ttForm',true);
	},

	onComplete: function() {
		if(Ajax.activeRequestCount == 0){
			Element.hide('divPlsWait');
			inputsDisabled('ttForm',false);
		}
	}
};

Ajax.Responders.register(globalHandlers);


//
// communicate with the server
//
function ajaxEvent( pStage ) {
	var language  = $F('jsLang');
	var departure = $F('jsDeparture');
	var arrival   = $F('jsArrival');
	var wot       = 0; 
	var url       = ssurl;
	var pars = 'mtrand=' + Math.floor(Math.random()*9999) + '&lang=' + language + '&departure=' + departure + '&arrival=' + arrival;
	if ($('jsWot').rebuilt == true) { wot = $F('jsWot'); }
	
	if (pStage == 1)
	{
		var ttAjax = new Ajax.Request( url, { method: 'get', parameters: pars, onComplete: buildWot });
	}
	
	if (pStage == 2)
	{
		if (wot != "0")
		{
			pars += '&wot=' + wot; 
			var ttHtmlAjax = new Ajax.Request( url, { method: 'get', parameters: pars, onComplete: buildTtTable });
		}
	}
	
}

//
// oncomplete (stage 1): build week of travel select
//
function buildWot(originalRequest) {
	var response;
	var responseArr;
	
	response = originalRequest.responseText;
	if ((response.replace(/\s/g,'').length) > 0)
	{
		response = response.replace(/_/g,' ');
		buildSimpleSelectBox('jsWot',response.split('|'));
	}
}

//
// oncomplete (stage 2): inject html
//
function buildTtTable(originalRequest) {
	var response = originalRequest.responseText;
	//do we want to do anything else here?
	$('injectZone').innerHTML = response;
}

//---------------------------------
// html events
//---------------------------------

function jsDeparture_onChange( pSelf ) {
	buildSelectBoxFE('jsArrival',pSelf);
	$('jsDepartureSave').value = pSelf.selectedIndex;
}

function jsArrival_onChange( pSelf ) {
	if (!pSelf.suspended) 
	{
		ajaxEvent(1);
		$('jsArrivalSave').value = pSelf.selectedIndex;
	}
}

function jsWot_onChange( pSelf ) {
	ajaxEvent(2);
	$('jsWotSave').value = pSelf.selectedIndex;
	$('wotText').innerHTML = $('wotTextPrefix').value + ': ' + pSelf.options[pSelf.selectedIndex].innerHTML;
	
	if (pSelf.selectedIndex == 0) { $('jsBtnPrev').className = 'buttonOff'; }
		else { $('jsBtnPrev').className = 'button'; }
	
	if (pSelf.selectedIndex == pSelf.options.length-1) { $('jsBtnNext').className = 'buttonOff'; }
		else { $('jsBtnNext').className = 'button'; }
}
