//jquery en modo no conflicto
var $ = jQuery.noConflict();


// inicializacion de variables
var idioma='uk';



$(document).ready(function(){
	if (window.iniciaFormulario) iniciaFormulario();
});




function iniciaFormulario(){

	// Actualizamos fechas
	
	var f = new Date();
	f.setDate(f.getDate() + 2);
	fec = padNum(f.getDate()) + "/" + padNum((f.getMonth() +1)) + "/" + f.getFullYear();
	f.setDate(f.getDate() + 7);
	fec2 = padNum(f.getDate()) + "/" + padNum((f.getMonth() +1)) + "/" + f.getFullYear();
	if (document.getElementById('fechaRecogida').value==''){
		document.getElementById('fechaRecogida').value = fec;
	}
	if(document.getElementById('fechaDevolucion').value==''){
		document.getElementById('fechaDevolucion').value = fec2;
	}



	// Carga inicial de paises, si no
	air = $('#solo_aero').val(); 

	if (pickupDest=='' || pickupDest=='null')
	{
		if (pickupCountry){
			cargaSelector('pais',$('#Country'),pickupCountry);
			cargaSelector('destinos',$('#destinooculto'),pickupCountry, air);
			cargaSelector('destinos',$('#destinosdevolucion'),pickupCountry, air);
		} else {
			cargaSelector('paises',$('#Country'));
			yaCargado=false;
		}
	} else {
		cargaSelector('paisDestino',$('#Country'), pickupDest);
		cargaSelector('destino',$('#destinooculto'), pickupDest);
		cargaSelector('destino',$('#destinosdevolucion'), dropoffDest);
		yaCargado=false;
	}

	// Si se selecciona pais se carga y habilita todo
	$('#Country').change(function () {
		air = $('#solo_aero').val();
		 if ($("#Country option:selected").val()=='reload')
		 {
			 cargaSelector('paises',$('#Country'));
		 } else {
			 idPais = $("#Country option:selected").val();
			 cargaSelector('destinos',$('#destinooculto'),idPais, air);
			 cargaSelector('destinos',$('#destinosdevolucion'),idPais, air);
			 $('#form_btn').attr("disabled",false);
			 yaCargado=true;
		 }
		 
	 })

	// Si se cambia casilla aeropuertos

	$("input[name='solo_aero']").change(function () {
		air = $("input[name='solo_aero']:checked").val(); 
		idPais = $("#Country option:selected").val();

		if (idPais!='null' && idPais!='reload')
		{
			cargaSelector('destinos',$('#destinooculto'),idPais, air);
			cargaSelector('destinos',$('#destinosdevolucion'),idPais, air);
			$('#form_btn').attr("disabled",false);
			yaCargado=true;
		}
		 
     })




	 // Si se cambia destino de recogida
	 $('#destinooculto').change(function () {
		air = $('#solo_aero').val();
		if ($("#destinooculto option:selected").val()=='reload')
		{
			idPais = $("#Country option:selected").val();
			 cargaSelector('destinos',$('#destinooculto'),idPais, air);
			 cargaSelector('destinos',$('#destinosdevolucion'),idPais, air);
			 $('#form_btn').attr("disabled",false);
			 yaCargado=true;

		} else {
			selVal = $("#destinooculto option:selected").text();
			$("#destinosdevolucion option:contains("+selVal+")").attr("selected",true);
		}
	 })

		 // Si se cambia destino de devolucion a reload
	 $('#destinosdevolucion').change(function () {
		air = $('#solo_aero').val();
		if ($("#destinosdevolucion option:selected").val()=='reload')
		{
			idPais = $("#Country option:selected").val();
			 cargaSelector('destinos',$('#destinosdevolucion'),idPais, air);
			 $('#form_btn').attr("disabled",false);
			 yaCargado=true;

		} 
	 })




	// Rellenamos selectores de horas / minutos
	hor_min_init = (window['hor_min_init']) ? hor_min_init : '12:00';
	hor_min_end = (window['hor_min_end']) ? hor_min_end : '12:00';
	if (document.getElementById("horas_minutos_init").length<1){
		generaOpcionesTiempo($('#horas_minutos_init'), hor_min_init);
	}
	if (document.getElementById("horas_minutos_end").length<1){
		generaOpcionesTiempo($('#horas_minutos_end'), hor_min_end);
	}
}


function generaOpcionesTiempo(destino, selected){

	for(i=0; i<=23;i+=1){
		for (j=0; j<=45 ; j+=15 ){
			cmpStr = padNum(i) + ':' + padNum(j);
			selStr = (cmpStr==selected) ? ' selected="selected"' : '';
			destino.append('<option value="' + cmpStr + '"' + selStr + '>' + cmpStr + '</option>');
		}
		
	}
}

function padNum(num){
	var num = '' + num;
	if (num.length<2){
		num = '0' + num;
	}
	return num;
}





function cargaSelector(fuente,destino,cod, air){
	switch (fuente){
		case 'pais':
			action = 'getPais';
			relationCod = '&countryCod='+cod;
		break;

		case 'paises':
			action = 'getPaises';
			relationCod = '';
		break;

		case 'destinos':
			action = 'getDestinos';
			relationCod = '&parent='+cod+'&air='+air;
		break;

		case 'paisDestino':
			action = 'getPaisDestino';
			relationCod = '&locationCod='+cod;
		break;

		case 'destino':
			action = 'getDestino';
			relationCod = '&locationCod='+cod;
		break;
	}
	
	// Vacia receptor
	destino.attr('disabled',true);
	if (destino.attr('id')=='destinooculto' || destino.attr('id')=='destinosdevolucion')
		destino.append('<option selected>------ loading --------</option>');

	// Llamada AJAX
	dominio = '/includes/';
	$.get(dominio + "motor-selector.php?action="+action+"&idioma="+idioma+relationCod,{},function(xml){
		
		destino.empty();
		
		

		// Recorre documento XML y asigna valores
		$('option',xml).each(function(i) {
			name = $(this).find("name").text();
			value = $(this).find("value").text();
			selected = $(this).attr("selected");
			//alert (name+value); 
			optionHTML = themeOption(value, name, selected);
			destino.append(optionHTML);
			//alert (optionHTML);
		});

		destino.attr("disabled",false);
		
	});

}


function themeOption(value,name,selected){
	selTxt='';
	if (selected==1) selTxt = ' selected';
	retHTML = '<option value="' + value + '"' + selTxt + '>' + name + '</option>';
	return retHTML;
}

function reloadPickup(pVal){
	pVal = (pVal) ? 'on' : '';
	document.getElementById('cpickup').value = pVal;
	document.formu.submit();
}

function validateSrchFrm(){
	numError = 0;
	//alert ('valida');

	if (document.getElementById('destinooculto')){
		elm = document.getElementById('destinooculto');
		idx = document.getElementById('destinooculto').selectedIndex;
		txt = elm.options[idx].value;
		if (txt=='null')
		{
			alert(label_seleccione_ciudad_recogida);
			return false;
		}
	}

	if (document.getElementById('destinosdevolucion')){
		elm = document.getElementById('destinosdevolucion');
		idx = document.getElementById('destinosdevolucion').selectedIndex;
		txt = elm.options[idx].value;
		if (txt=='null')
		{
			alert(label_seleccione_ciudad_devolucion);
			return false;
		}
	}
}



// Control de fechas
$(function()
{
	$('#fechaRecogida')
		.datepick(
			{	
				showOn: 'both', 
				buttonImage: '/wp-content/themes/coches-en/img/calendar.gif',
				showAnim: 'slideDown',
				closeAtTop: false,
				yearRange: ('+0:+1'),
				showOtherMonths: true,
				selectOtherMonths: true,
				numberOfMonths: 2,
				minDate: +2,
				mandatory: true
			}
		);

	$('#fechaDevolucion')
		.datepick(
			{	
				showOn: 'both', 
				buttonImage: '/wp-content/themes/coches-en/img/calendar.gif',
				showAnim: 'slideDown',
				closeAtTop: false,
				yearRange: ('+0:+1'),
				showOtherMonths: false,
				numberOfMonths: 2,
				minDate: +2,
				mandatory: true
			}
		);
		
});

function formuPresu(veh_proveedor){
	window.open("http://www.eezirent.net/carhireserver/presupuestar.php?vproveedor="+veh_proveedor+"&search="+xmlEncoded+"&af_cod=99", "Quote", "height=490px, width=950px, scrollbars=1");
}

function verDesglose(sucursal, veh_proveedor){
	window.open("http://www.eezirent.net/carhireserver/verDesglose.php?vproveedor="+veh_proveedor+"&search="+xmlEncoded, "modificar", "height=490px, width=680px, scrollbars=1");
}

function direccionarPresupuesto(sucursal, veh_proveedor, ref){
	if ($("#destinooculto option:selected").val()=='' || $("#destinosdevolucion option:selected").val()=='') return false;

	document.formu.vproveedor.value = veh_proveedor;
	if (ref){
		document.formu.quoteRef.value = ref;
	}
	
	document.formu.action = "http://www.eezirent.net/carhireserver/quote.php?af_cod=99";
	document.formu.submit();
}