//
//
// Conjunto de funciones que buscan listas de precios en Sidetours, y la colocan
// en el fichero correspondiente, que tenga los elementos "id" adecuados


var url = "/prices_xmlhttp.php";

//
// Funciones que se encargan de procesar las peticiones de listas de precios
//		LoadPrices()
//		ComponerTablaLoadPrices()


// Esta función se encarga de recolectar los precios con estacion = "stationcode"
// con el modo "Current" en la temporada,
// Se encarga también de recolectar todos los precios en todas las temporadas
function LoadPrices(stationcode) {

	// Primera llamada con las estaciones concretas y "Current" 
	$.ajax({
		mode: "queue",
   		type: "GET",
		url: url,
		data: "agencycode=ELITE&stationcode=" + stationcode + "&seasoncode=Low",
		dataType: "xml",
		success: function(xml){
			ProcesarLoadPrices(xml)
			$("div#sub_me_de").fadeIn("slow")
			$("div.banner_precio").fadeIn("slow")
//			alert("Current procesado")
		}
	});

	// Segunda llamada con las estaciones concretas y "All" 
	$.ajax({
		mode: "queue",
		type: "GET",
		url: url,
		data: "agencycode=ELITE&stationcode=" + stationcode + "&seasoncode=Current",
		dataType: "xml",
		success: function(xml){
			ProcesarLoadPrices(xml)
//			alert("All procesado")
		}
	});

} // LoadPrices


function ProcesarLoadPrices(xmlDoc) {

	var querystatus = getStaticCollectionByTagName("QueryStatus", xmlDoc)[0].childNodes[0].nodeValue;

	if (querystatus == 'Ok') {

		// Se va a hacer una búsqueda en cuatro niveles (Company no se usa de momento):
		//  Station
		//   Season (Low, Mid o High)
		//    Company (no se va a usar de momento)
		//     Group (todos los grupos disponibles)
	
		var isCurrent = getStaticCollectionByTagName("SeasonCode", xmlDoc)[0].childNodes[0].nodeValue;

		var stations = getStaticCollectionByTagName("Station", xmlDoc);
		for (var oneStation = 0; oneStation < stations.length; oneStation++) {

			var stationcode = getStaticCollectionByTagName("StationCode", stations[oneStation])[0].childNodes[0].nodeValue;
						
			var seasons = getStaticCollectionByTagName("Season", stations[oneStation]);
			for (var oneSeason = 0; oneSeason < seasons.length; oneSeason++) {
	
				var seasonname = getStaticCollectionByTagName("SeasonName", seasons[oneSeason])[0].childNodes[0].nodeValue;
				
				var groups = getStaticCollectionByTagName("Group", seasons[oneSeason]);
				for (var oneGroup = 0; oneGroup < groups.length; oneGroup++) {

					groupcode = getStaticCollectionByTagName("GroupCode", groups[oneGroup])[0].childNodes[0].nodeValue;
					currentprice = getStaticCollectionByTagName("GroupPrice", groups[oneGroup])[0].childNodes[0].nodeValue;

					if (isCurrent == "Current") {
						showedSeason = "Current";
					} else {
						showedSeason = seasonname;
					}

					// Componemos y sustituimos los precios de la temporada
					tag = 	"station_" + stationcode +
							"_season_" + showedSeason +
							"_group_" + groupcode;
							
					if (currentprice == "Unavailable") {
						currentprice_texto = "";
					} else {
						while(currentprice.length<3)currentprice="0"+currentprice; // Rellenar con ceros hasta tamaño 3
						currentprice_texto = 	currentprice.substring(0, currentprice.length - 2);
						currentprice_cents = currentprice.substring(currentprice.length - 2);
						// Mostrar los centimos solamente si no son cero
						if (currentprice_cents > 0) {
							currentprice_texto = currentprice_texto + ',' + currentprice_cents;
						}
												
					}

					if (document.getElementById(tag) != null) {
						document.getElementById(tag).innerHTML = currentprice_texto + " &euro;";
					}
					if (document.getElementById(tag + "_flash") != null) {
						document.getElementById(tag + "_flash").innerHTML = currentprice_texto + " &euro;";
					}

				} // for Group
				
			} // for Season
		
		} // for Station
			

	} // if QueryStatus == "Ok"
	

} // ComponerTablaLoadPrices


// Tranforma elementos dinámicos en estáticos (ahorrando en velocidad cuando
// se tienen muchos anidados)
function getStaticCollectionByTagName(tag, node) {
	//just like getElementsByTagName, we want to open up and optional context node 
	if (node==undefined) {
		//if it's not passed in as an argument, we set it to be document 
		node=document
	}
	//we build a variable with the original collection 
	var temp_array = node.getElementsByTagName(tag);
	//and a new array to hold them 
	var static_results = new Array;
	//then we just loop through and copy each into the new array 
	for (i=0; i<temp_array.length;i++) {
		static_results.push(temp_array[i]);
	}
	//and return it 
	return static_results;
}
