$(document).ready(function(){

	// Inicio de galeria de imagenes
	if(window.restauraBotones) restauraBotones();
	if(window.colocaImagenes) colocaImagenes();
	if(window.mueveImagenes) intval=window.setInterval("mueveImagenes(-160, 1000)",5000);
	if (window.iniciaFormulario) iniciaFormulario();
});

if(jQuery.browser.msie && parseInt(jQuery.browser.version, 10) == 6) {
  try {
    document.execCommand("BackgroundImageCache", false, true);
  } catch(err) {}
}

function verCondiciones(sucursal, veh_proveedor){
	window.open("/verCondiciones.php?vproveedor="+veh_proveedor+"&search="+xmlEncoded, "modificar", "height=490px, width=590px, scrollbars=1");
			}

function verDesglose(sucursal, veh_proveedor)
			{
				window.open("/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;
				document.formu.quoteRef.value = ref;
				//alert (document.formu.vproveedor.value);
				document.formu.action = "/quote.php";
				document.formu.submit();
			}

function reenviarClave()
	{
		document.cliForm.action="http://www.eezirent.net/cliente/reenviarclave.php";
		document.cliForm.submit();
	}

function redir(url){
	document.location.href=url;
	return false;
}

function formuPresu(veh_proveedor)
			{
				window.open("/presupuestar.php?vproveedor="+veh_proveedor+"&search="+xmlEncoded, "Quote", "height=490px, width=950px, scrollbars=1");
			}


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 = $("input[name='solo_aero']:checked").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 = $("input[name='solo_aero']:checked").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 = $("input[name='solo_aero']:checked").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 = $("input[name='solo_aero']:checked").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_init = (window['hor_init']) ? hor_init : 12;
	hor_end = (window['hor_end']) ? hor_end : 12;
	min_init = (window['min_init']) ? min_init : 0;
	min_end = (window['min_end']) ? min_end : 0;
	generaOpcionesTiempo('horas', $('#horas_init'), hor_init);
	generaOpcionesTiempo('horas', $('#horas_end'), hor_end);
	generaOpcionesTiempo('minutos', $('#minutos_init'), min_init);
	generaOpcionesTiempo('minutos', $('#minutos_end'), min_end);
}


function generaOpcionesTiempo(tipo, destino, selected){
	if (tipo=='horas'){
		inicio = 0;
		fin = 23;
		step = 1;
	}
	if (tipo=='minutos'){
		inicio = 0;
		fin = 55;
		step = 5;
	}

	for(i=inicio; i<=fin;i+=step){
		selStr = (i==selected) ? ' selected="selected"' : '';
		destino.append('<option value="' + padNum(i) + '"' + selStr + '>' + padNum(i) + '</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
	//alert (dominio + "includes/motor-selector.php?action="+action+"&idioma="+idioma+relationCod);
	$.get(dominio + "includes/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: 'http://www.hispacar.com/hispacar2009/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: 'http://www.hispacar.com/hispacar2009/img/calendar.gif',
				showAnim: 'slideDown',
				closeAtTop: false,
				yearRange: ('+0:+1'),
				showOtherMonths: false,
				numberOfMonths: 2,
				minDate: +2,
				mandatory: true
			}
		);
		
});


/* <![CDATA[ */
function restauraBotones(){
		$("#goBack").bind("click", function(){
	    window.clearInterval(intval);
		  mueveImagenes(160,1000);
		  return false;
		});
		
		$("#goForw").bind("click", function(){
		  window.clearInterval(intval);
		  mueveImagenes(-160, 1000);
		  return false;
		});
		
		$("#pause").bind("click", function(){
		  window.clearInterval(intval);
		  return false;
		});
		
		
	}
	
	function unbindBut(butName){
		butName.unbind("click");
	}
	
	
	function mueveImagenes(cantidad,intervalo){
		if (cantidad>0){
			cantPositiva=true;
			reposiciona(cantPositiva);
			
			
		}
		unbindBut($("#goForw"));
		unbindBut($("#goBack"));
		
		for (i=0;i<fotos.length;i++){
			obj = $('#'+fotos[i]);
			doCallback = false;
			if (i+1==fotos.length){
			 doCallback = true;
			}
			mueveImagen(obj, cantidad, intervalo, doCallback);
		}
	}
	
	function reposiciona(cantPositiva){
		// averiguamos valor minimo y maximo de left
		minLeft=10000;
		maxLeft=-10000;
		for (i=0;i<fotos.length;i++){
			curObj = $('#'+fotos[i]);
			curLeft = $('#'+fotos[i]).css('left');
			curLeft = parseInt(curLeft.replace('px',''));
			if (curLeft<minLeft){
				minLeft = curLeft;
				minObj = curObj;
			}
			if (curLeft>maxLeft){
				maxLeft = curLeft;
				maxObj = curObj;
			}
		}
		if (!cantPositiva){
			// Cantidad negativa - Movemos primera foto al final
			minObj.css({'left' : (maxLeft + 160) + 'px'});
			restauraBotones();
		} else {
			// Cantidad positiva - Movemos ultima foto al principio
			maxObj.css({'left' : (minLeft - 160) + 'px'});
		}
		
	}
	
	function colocaImagenes(){
		for (i=0;i<fotos.length;i++){
			$('#'+fotos[i]).css({'left' : (10+i*160) + 'px'});
			//mueveImagen("50", 1000);
		}
	}
	
	function mueveImagen(myobj, cantidad, tiempo, doCallback){
		if (cantidad>0){
			str = '+=' + cantidad;
			cantPositiva = true;
		} else {
			cantidad = Math.abs(cantidad);
			str = '-=' + cantidad;
			cantPositiva = false;
		}
		str += 'px';
		if (doCallback && !cantPositiva){
			myobj.animate({left: str}, tiempo, 'linear', function(){reposiciona(cantPositiva);});
		} else {
			myobj.animate({left: str}, tiempo, 'linear', function(){restauraBotones();});
		}
	}
/* ]]> */