/*
Copyright (c) 2008, Red Universal de Marketing y Bookings Online, S.A. (Rumbo) All rights reserved.
version: 0.3b
*/

function loadStations(select, sourceData, text, defaultValue, loadingContainer, form)
{
    if (form) {
        select += ('-' + form);
    }
    
	var xhr=createXHR();
	var targetContainer = document.getElementById(select);
	if (loadingContainer)
	{
		document.getElementById(loadingContainer).style.visibility = 'visible';
	}
	xhr.open('GET', stationsJson, true);
	xhr.onreadystatechange=function() 
	{
		if (xhr.readyState == 4) 
		{
			if (xhr.status != 404) 
			{
				targetContainer.options.length = 0;
				targetContainer.options[0] = new Option(text,'XXX');
				var data=eval("(" + xhr.responseText + ")");
				var i=0;
				var defaultIndex = 0;
				stationsList = data.stations[sourceData];
				while (i<stationsList.length)
				{
					var station = stationsList[i];
					targetContainer.options[i+1] = new Option(data.stations.routes[station].description,station);
					if(defaultValue && defaultValue==station)
					{
						defaultIndex = i+1;
					}
					i=i+1;
				}
				targetContainer.selectedIndex = defaultIndex;
				if (loadingContainer)
				{
					document.getElementById(loadingContainer).style.visibility = 'hidden';
				}
			}
		}
	}
	xhr.send(null);
}
function loadRoutes(source, target, sourceData, text, loadingText, loadingContainer) 
{
	var targetContainer = document.getElementById(target);
	var sourceContainer = document.getElementById(source);
	if (sourceContainer.value == 'XXX')
	{
		loadStations(target, sourceData, text);
	}
	else
	{
		if (loadingContainer)
		{
			document.getElementById(loadingContainer).style.visibility = 'visible';
		}
		var xhr=createXHR();
		xhr.open('GET', stationsJson, true);
		xhr.onreadystatechange=function() 
		{
			if (xhr.readyState == 4) 
			{
				if (xhr.status != 404) 
				{
					targetContainer.options.length = 0;
					targetContainer.options[0] = new Option(text,'XXX');
					var data=eval("(" + xhr.responseText + ")");
					var i=0;
					var sourceStation = data.stations.routes[sourceContainer.value];
					while (i<sourceStation.destinations.length)
					{
						var destination = sourceStation.destinations[i];
						targetContainer.options[i+1] = new Option(data.stations.routes[destination].description,destination);
						i=i+1;
					}
					if (loadingContainer)
					{
						document.getElementById(loadingContainer).style.visibility = 'hidden';
					}
				}
			}
		}
		xhr.send(null);
	}
}
