/********************************
Trim function for String objects
********************************/
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

/********************************
Buscar las rutas con los destinos
provistos
********************************/
function LoadRutas(IdSalida, IdLlegada, IdDivItinerario)
{
	var DdlSalida = document.getElementById(IdSalida);
	var DdlLlegada = document.getElementById(IdLlegada);
	var DivItinerario = document.getElementById(IdDivItinerario);
	
	load = function (param)
	{
		if(DivItinerario != null)
		{
			DivItinerario.innerHTML = '';
			
			var DivItinerary = document.getElementById(IdDivItinerario);	
			
			DivItinerary.innerHTML = param;
		}
	}
	
	ExecuteCommand('GetItinerario', load, DdlSalida.value, DdlLlegada.value);
}
/********************************
Buscar las rutas con los destinos
provistos
********************************/
function LoadRutasWithOpenDate(IdChkOpenDate, IdSalida, IdLlegada, IdDivItinerario)
{
	var ChkOpenDate = document.getElementById(IdChkOpenDate);
	
	if(ChkOpenDate.checked)
	{
		var DdlSalida = document.getElementById(IdSalida);
		var DdlLlegada = document.getElementById(IdLlegada);
		var DivItinerario = document.getElementById(IdDivItinerario);
		
		load = function (param)
		{
			if(DivItinerario != null)
			{
				DivItinerario.innerHTML = '';
				
				var DivItinerary = document.getElementById(IdDivItinerario);	
				
				DivItinerary.innerHTML = param;
			}
		}
		
		ExecuteCommand('GetOptionsForRuta', load, DdlSalida.value, DdlLlegada.value);
	}
	else
	{
		LoadRutas(IdSalida, IdLlegada, IdDivItinerario);	
	}	
}
/********************************
Cargar del DropDownList de Fechas una vez que
se selecciona la ruta
********************************/
function LoadFechas(IdRuta, IdDdlFechaSalida, IdDivItinerario)
{
	var DdlFechaSalida = document.getElementById(IdDdlFechaSalida);
	var DivItinerario = document.getElementById(IdDivItinerario);
	
	DdlFechaSalida.IdRuta = IdRuta;
	
	load = function (param)
	{
		if(DivItinerario != null)
		{
			if(DivItinerario != null)
			{
				DivItinerario.innerHTML = '';
			}
			
			LoadOptionsIntoDdl(DdlFechaSalida, param);			
		}
	}
	
	ExecuteCommand('GetViajeDesdeSalida', load, IdRuta);
}
/********************************
Cargar del DropDownList de Destinos de Llegada
cuando se seleccionan el destino de salida
********************************/
function LoadDestinosLlegadas(IdSalida, IdLlegada, IdDivItinerario)
{
	var DdlSalida = document.getElementById(IdSalida);
	var DdlLlegada = document.getElementById(IdLlegada);
	var DivItinerario = document.getElementById(IdDivItinerario);
	
	load = function (param)
	{
		if(DivItinerario != null)
		{
			DivItinerario.innerHTML = '';
		}

		LoadOptionsIntoDdl(DdlLlegada, param);		
	}
	
	ExecuteCommand('GetDestinosLlegada', load, DdlSalida.value);
}

/********************************
Cargar el itinerario
********************************/
var IdDivItineraryGlobal = '';
function LoadItinerario(IdSalida, IdLlegada, IdFechasRutas, IdDivItinerary)
{
	var DdlSalida = document.getElementById(IdSalida);
	var DdlLlegada = document.getElementById(IdLlegada);
	var DdlFechasRutas = document.getElementById(IdFechasRutas);
	
	IdDivItineraryGlobal = IdDivItinerary;

	load = function (param)
	{
		var DivItinerary = document.getElementById(IdDivItineraryGlobal);	
		
		DivItinerary.innerHTML = param;
	}
	
	ExecuteCommand('GetItinerario', load, DdlSalida.value, DdlLlegada.value, DdlFechasRutas.value);
}

function LoadItinerarioWithRuta(DdlFechaSalida, IdRdBtnRuta, IdDivItinerary)
{
	var RdBtnRuta = document.forms[0].elements[IdRdBtnRuta];
	var IdRuta = getCheckedValue(RdBtnRuta);
	
	if(IdRuta == "")
	{
		IdRuta = RdBtnRuta.value;
	}
	
	load = function (param)
	{
		var DivItinerary = document.getElementById(IdDivItinerary);	
		
		DivItinerary.innerHTML = param;
	}
	
	ExecuteCommand('GetItinerario', load, '', '', DdlFechaSalida.value, IdRuta);
}
/****************************************************************
Checkea si todos los dropdownlists tiene un valor asignado de los dias
****************************************************************/
function CheckDataBeforeSubmit(IdTotalDestinos, PrefixIdDdlDias, IdViajeFechaSalida, IdRuta, url, ExecuteScript)
{
	var HidTotalDestinos = document.getElementById(IdTotalDestinos);
	var HidViajeFechaSalida = document.getElementById(IdViajeFechaSalida);
	var HidRuta = document.getElementById(IdRuta);
	
	var ok = true;
	
	if(HidTotalDestinos)
	{
		var IdsViajes = document.getElementById('IdsViajes');
		IdsViajes.value = HidViajeFechaSalida.value;

		for(i = 0; i < HidTotalDestinos.value; i++)
		{
			var Ddl = document.getElementById(PrefixIdDdlDias + i);
			if(Ddl != null)
			{
				if(Ddl.value == 0 ||  Ddl.value == '')
				{
					ok = false;
				}
				else
				{
					IdsViajes.value += ';' + Ddl.value;
				}		
			}
		}
	}
	else
	{
		ok = false;
	}
	if(ok)
	{
		var form = document.forms[0];

		if(url == null || url == '')
		{
			url = window.location.href;		
		}

		url = new String(url);

		if(url.indexOf('?') > 0)
		{
			url += 	'&IdsViajes=' + IdsViajes.value + '&IdRuta=' + HidRuta.value;
		}
		else
		{
			url += 	'?IdsViajes=' + IdsViajes.value + '&IdRuta=' + HidRuta.value;
		}

		form.action = url;

		if(ExecuteScript != null)
		{
			eval(ExecuteScript);
		}		

		form.submit();
	}	
	else
	{
		alert('You must select a number of days for each destination.');
	}
}
/****************************************************************
Checkea si todos los dropdownlists tiene un valor asignado de los dias
****************************************************************/
function CheckDataBeforeSubmitWithOpenDate(IdChkOpenDate, IdTotalDestinos, PrefixIdDdlDias, IdViajeFechaSalida, IdRuta, url, ExecuteScript)
{
	var chkOpenDate = document.getElementById(IdChkOpenDate);
	if(!chkOpenDate.checked)
	{
		CheckDataBeforeSubmit(IdTotalDestinos, PrefixIdDdlDias, IdViajeFechaSalida, IdRuta, url, ExecuteScript);
	}
	else
	{
		var HidRuta = document.getElementById(IdRuta);

		var form = document.forms[0];

		if(url == null || url == '')
		{
			url = window.location.href;		
		}

		url = new String(url);

		form.action = url;

		if(ExecuteScript != null)
		{
			eval(ExecuteScript);
		}
		else
		{	
			form.submit();
		}
	}
}

/****************************************************************

****************************************************************/
function OpenDateOnChange(IdChkOpenDate, IdDivCantPasajeros, IdDivItinerario, IdDdlDestinoLlegada)
{
	var chkOpenDate = document.getElementById(IdChkOpenDate);
	var divCantPasajeros = document.getElementById(IdDivCantPasajeros);
	var divItinerario = document.getElementById(IdDivItinerario);
	var DdlDestinoLlegada = document.getElementById(IdDdlDestinoLlegada); 

	if(chkOpenDate.checked)
	{
		divCantPasajeros.style.display = 'block';
	}
	else
	{
		divCantPasajeros.style.display = 'none';
	}
	
	if(DdlDestinoLlegada)
	{
		DdlDestinoLlegada.selectedIndex = 0;
	}
	
	divItinerario.innerHTML = '';
}
/****************************************************************
 Carga todos los DropDownList posteriores al modificado en el itinerario para mostrar
 opciones disponibles de cantidad de dias de estadía.
*****************************************************************/
function LoadDdlsRelativos(indexDdlModificado, PrefixIdDdlDias, PrefixIdDivFecha, FechaSalida, TotalDestinos, IdRuta, IdControlCantPasajeros, IdPrimerViajeFecha)
{
	var FechaSalidaStr = new String(FechaSalida);
	var FechaSalidaStrArr = FechaSalidaStr.split('-');

	var Fecha = new Date();
	Fecha.setFullYear(FechaSalidaStrArr[0], FechaSalidaStrArr[1] - 1, FechaSalidaStrArr[2]);
	
	var indexDdlProximo = indexDdlModificado * 1 + 1;
	
	var DivProcesando = document.getElementById('DivProcesando');
	DivProcesando.style.display = 'block';
	
	var ControlCantPasajeros = document.getElementById(IdControlCantPasajeros);	

	if(indexDdlModificado < TotalDestinos - 2)
	{		
		var DdlModificado = document.getElementById(PrefixIdDdlDias + indexDdlModificado);	
		var DdlProximo = document.getElementById(PrefixIdDdlDias + indexDdlProximo);

		var IdViajeFechaAnterior = IdPrimerViajeFecha;
		
		if(indexDdlModificado > 0)
			IdViajeFechaAnterior = DdlModificado.value
		
		load = function (param)
		{
			var result = new String(param);
			result = result.trim();

			LoadOptionsIntoDdl(DdlProximo, param);
			if(result != '' && result != null)
			{
				DdlProximo.style.backgroundColor = '#FFFFFF';
				LoadDdlsRelativos(indexDdlProximo, PrefixIdDdlDias, PrefixIdDivFecha, FechaSalida, TotalDestinos, IdRuta, IdControlCantPasajeros);
			}
			else
			{
				DdlProximo.style.backgroundColor = '#FF0000';
				alert("There are no buses available for this itinerary in the destination marked in red.\n Please change some of the number of days to find one that is.");
				DivProcesando.style.display = 'none';
			}
		}
		
		ExecuteCommand('UpdateViajesProximos', load, IdRuta, IdViajeFechaAnterior, ControlCantPasajeros.value);
	}
	else if(indexDdlModificado == TotalDestinos - 2)
	{		
		LoadFechasWithDias(PrefixIdDdlDias, PrefixIdDivFecha, FechaSalida, TotalDestinos);
		DivProcesando.style.display = 'none';
	}
}
/****************************************************************
 Actualiza las fecha en funcion de la cantidad de dias seleccionados en los DropDownLists
*****************************************************************/
function LoadFechasWithDias(PrefixIdDdlDias, PrefixIdDivFecha, FechaSalida, TotalDestinos)
{	
	var FechaSalidaStr = new String(FechaSalida);
	var FechaSalidaStrArr = FechaSalidaStr.split('-');

	var Fecha = new Date();
	Fecha.setFullYear(FechaSalidaStrArr[0], FechaSalidaStrArr[1] - 1, FechaSalidaStrArr[2]);

	lastViajeWasNoche = false;

	for(i = 0; i < TotalDestinos; i++)
	{
		var Ddl = document.getElementById(PrefixIdDdlDias + i);
		var Div = document.getElementById(PrefixIdDivFecha + i);

		if(Ddl != null)
		{
			var text = new String(GetSelectedText(Ddl));
			var textTemp = text;
			var days = 0;
			text = text.replace('(NightBus)', '');
			text = text.trim();
			
			if(lastViajeWasNoche)
				days = text * 1 + 1;
			else
				days = text * 1;
			
			if(textTemp.indexOf('(NightBus)') >= 0)
				lastViajeWasNoche = true;
			else
				lastViajeWasNoche = false;

			Fecha.setDate(Fecha.getDate() + days);
						
			Div.innerHTML = FriendlyFormat(Fecha);
		}
		else if(i == TotalDestinos - 1)
		{
			var Ddl = document.getElementById(PrefixIdDdlDias + (i - 1));
			var text = new String(GetSelectedText(Ddl));
			if(text.indexOf('(NightBus)') >= 0)
			{
				Fecha.setDate(Fecha.getDate() + 1);
			}

			Div.innerHTML = FriendlyFormat(Fecha);
		}
	}
}

/****************************************************************
Obtiene el valor del texto de la opcion seleccionada de un DropDownList
*****************************************************************/
function GetSelectedText(Ddl)
{
	var w = Ddl.selectedIndex;
	return Ddl.options[w].text;
}

/********************************************
Devuelve una fecha en formato [Nombre mes], [Dia#]
********************************************/
function FriendlyFormat(Fecha)
{
	var MonthNames = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
	
	return MonthNames[Fecha.getMonth()] + ', ' + Fecha.getDate();
}
/********************************************************
Carga un dropDownList con una cadena que tiene las opciones separadas por ';'
y la key y el value por '|'.
********************************************************/
function LoadOptionsIntoDdl(Ddl, OptionsStr)
{
	var pairs = OptionsStr.split(';');
	
	var selectedText = '';
	
	if(Ddl.selectedIndex >= 0)
		selectedText = Ddl.options[Ddl.selectedIndex].text;
	
	Ddl.options.length = 0;
	
	for(i = 0; i < pairs.length; i++)
	{
		var pairStr = new String(pairs[i]);
		var pair = pairStr.split('|');
		
		var id = pair[0];
		var description = pair[1];
		if(id != '' && id != null)
		{
			opt = new Option(description, id);
			Ddl.options[Ddl.options.length] = opt;
			
			if(description == selectedText)
			{
				Ddl.selectedIndex = Ddl.options.length - 1;
			}
		}
	}	
}
/********************************************************
Esconde el elemento cuyo id es pasado por parametro
********************************************************/
function Hide(IdElement)
{
	var Element = document.getElementById(IdElement);
	if(Element)
	{
		Element.style.display = 'none';
	}
}

/********************************************************
Muestra el elemento cuyo id es pasado por parametro
********************************************************/
function Show(IdElement)
{
	var Element = document.getElementById(IdElement);

	if(Element)
	{
		Element.style.display = 'block';
	}
}


/********************************************************
Controla los datos ingresados
********************************************************/
function checkUserData()
{
	var Nuevo = document.getElementById('DivClienteNuevo');
	var Nombre = document.getElementById('TxtNombre');
	var Apellido = document.getElementById('TxtApellido');
	var Email = document.getElementById('TxtEmail');
	var EmailRepeat = document.getElementById('TxtEmailRepeat');
	var Ciudad = document.getElementById('TxtCiudad');
	
	if(Nuevo.style.block == 'none')
	{
		return true;
	}

	if (Nombre.value == '' ||
		Apellido.value == '' ||
		Email.value == '' ||
		EmailRepeat.value == '' ||
		Ciudad.value == '')
	{
		alert('Debe completar todos los datos del usuario.');
		return false;
	}
	else if (Email.value != EmailRepeat.value)
	{
		alert('El mail no coincide con su confirmacion.');
		return false;		
	}
	else
	{
		return true;
	}	
}

/********************************************************
Verifica que el numero ingresado se pasajeros sea valido
********************************************************/
function ControlNumPassengers(TxtCantPasajeros, indexDdlModificado, PrefixIdDdlDias, PrefixIdDivFecha, FechaSalida, TotalDestinos, IdRuta, IdControlCantPasajeros, IdPrimerViajeRuta)
{
	var MaxCantPasajeros = 13;
	var cant = TxtCantPasajeros.value * 1;
	
	var HidPrecio = document.getElementById('HidPrecio');
	var spanPrecio = document.getElementById('spanPrecio');
	
	
	var precio = TxtCantPasajeros.value * 1;
	var ok = false;
	
	if(typeof(cant) == 'NaN')
	{
		TxtCantPasajeros.value = 1;
	}
	else if(cant < 1)
	{
		TxtCantPasajeros.value = 1;
	}
	else if(cant > MaxCantPasajeros)
	{
		TxtCantPasajeros.value = MaxCantPasajeros;	
	}
	else
	{
		ok = true;
	}
	
	if(!ok)
	{
		alert('You must enter a number between 1 and ' + MaxCantPasajeros + '.');
	}
	
	LoadDdlsRelativos(0, PrefixIdDdlDias, PrefixIdDivFecha, FechaSalida, TotalDestinos, IdRuta, IdControlCantPasajeros, IdPrimerViajeRuta);
	
	spanPrecio.innerHTML = HidPrecio.value * cant;
}

/********************************************************
 Carga los puntos de venta en relacion con la ciudad
 seleccionada
********************************************************/
function LoadPuntosVenta(DdlCiudades, IdDdlPuntosVenta)
{
	var DdlPuntosVenta = document.getElementById(IdDdlPuntosVenta);
	
	load = function (param)
	{
		LoadOptionsIntoDdl(DdlPuntosVenta, param);
	}
	
	ExecuteCommand('GetPuntosVentaByCiudad', load, DdlCiudades.value);	
}

/********************************************************
 Return the value of the selected radiobutton option
********************************************************/
function getCheckedValue(radioObj) 
{
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) 
	{
		if(radioObj[i].checked) 
		{
			return radioObj[i].value;
		}
	}
	return "";
}

/********************************************************
 Return the value of the selected radiobutton option
********************************************************/
var myWindow;
function calCustom(ddlPaqId, txtFechaId)
{
	var ddlPaquetes = document.getElementById(ddlPaqId);

	if (ddlPaquetes.value)
	{
		myWindow = window.open('calendar.php?paq='+ddlPaquetes.value+'&c='+txtFechaId,'er','Width=220,Height=195,resizable=no,status=no,toolbar=no,center=yes,scrollbars=0,top=60,left=60');
	}
	else
	{
 		alert('You must select a Package.');
 		return false;
	}
}

/********************************************************
 Carga las fechas de un paquetes especifico
 ********************************************************/
function LoadFechasPaquete(DdlPaquetes, IdDdlFechasPaquete)
{
	var DdlFechasPaquete = document.getElementById(IdDdlFechasPaquete);
	
	load = function (param)
	{
		LoadOptionsIntoDdl(DdlFechasPaquete, param);
	}
	
	ExecuteCommand('GetFechasPaquetes', load, DdlPaquetes.value);	
}