var currentForm = null;
var lastForm = null;

var origenMsgError = null;
var destinoMsgError = null;
var fechaSalidaMsgError = null;
var fechaRegMsgError = null;
var tresDestinosMsgError = null;
var url_auto = null;
var diasAntelacion = null;
var difDias = null;
var iDiasT = null;
var MULTI_DESTINOS_CANTIDAD_SALTOS = 3;

function set_form (current_form) {
	lastForm = currentForm
	currentForm = current_form;
}

function set_configuration (origen,destino,fechaSal, 
		fechaReg, tresDestinos, auto, diasAnte, difD, diasT) {
	origenMsgError = origen;
	destinoMsgError = destino;
	fechaSalidaMsgError = fechaSal;
	fechaRegMsgError = fechaReg;
	tresDestinosMsgError = tresDestinos;
	url_auto = auto;
	diasAntelacion = diasAnte;
	difDias = difD;
	iDiasT = diasT;
}

function bind_fancy_buscador () {
	$("#busquedaAvanzada").fancybox({
		'autoDimensions' : 	false,
		'transitionIn'	:	'none',
		'transitionOut'	:	'none',
		'speedIn'		:	600, 
		'speedOut'		:	200, 
		'width'			: 	510,
		'height'		: 	430,
		'overlayShow'	:	true,
		'scrolling'		: 	'no',
		'overlayOpacity':	0.4,
		'padding'		: 	5,
		'showCloseButton': true,
		'enableEscapeButto': true,
		'onComplete'	: function () {
			set_form ($("#busquedaVuelosModalForm"));
			setBuscadorParamsFor($(lastForm).serialize() );
			init_buscador ();
		    $.fancybox.center();
		},
		'onCleanup'		: function () {
			set_form ($("#busquedaVuelosForm"));
			setBuscadorParamsFor($(lastForm).serialize() );
			init_buscador ();
		}
	});	
	
}

function init_buscador () {
	
	var mxDate=new Date();
	mxDate.setDate(mxDate.getDate()+330);
	
	$.datepicker.regional['es'];
	$.datepicker.setDefaults({
		buttonText: 'Calendario',
		fistDay: 1,
		changeMonth: true,
		changeYear: true,
		numberOfMonths: 2,
		showOn: 'button', buttonImageOnly: true, buttonImage: '../img/calendario.gif',
		defaultDate: diasAntelacion,
		minDate: diasAntelacion,
		maxDate: mxDate
	});
		
	$(currentForm).find("#fechaSalida1").datepicker("destroy").datepicker({
		onSelect: function(date, i){
			var fromDate = new Date($.datepicker.parseDate('dd/mm/yy', date));
			$(currentForm).find("#fechaSalida1").datepicker('setDate', new Date($.datepicker.parseDate('dd/mm/yy', date)));
			$(currentForm).find("#fechaSalida2").datepicker('option', 'minDate', fromDate);
			$(currentForm).find("#fechaSalida3").datepicker('option', 'minDate', fromDate);
			$(currentForm).find("#fechaSalida4").datepicker('option', 'minDate', fromDate);
			
		}
	});
	
	$(currentForm).find("#fechaSalida2").datepicker("destroy").datepicker({
		onSelect: function(date, i){
			var fromDate = new Date($.datepicker.parseDate('dd/mm/yy', date));
			$(currentForm).find("#fechaSalida2").datepicker('setDate', new Date($.datepicker.parseDate('dd/mm/yy', date)));
			$(currentForm).find("#fechaSalida3").datepicker('option', 'minDate', fromDate);
			$(currentForm).find("#fechaSalida4").datepicker('option', 'minDate', fromDate);			
		}
	});
		
	
	$(currentForm).find("#fechaSalida3").datepicker("destroy").datepicker({
		onSelect: function(date, i){
			var fromDate = new Date($.datepicker.parseDate('dd/mm/yy', date));
			$(currentForm).find("#fechaSalida3").datepicker('setDate', new Date($.datepicker.parseDate('dd/mm/yy', date)));
			$(currentForm).find("#fechaSalida4").datepicker('option', 'minDate', fromDate);			
		}
	});
	
	
	$(currentForm).find("#fechaSalida4").datepicker("destroy").datepicker({
		onSelect: function(date, i) {
		$(currentForm).find("#fechaSalida4").datepicker('setDate', new Date($.datepicker.parseDate('dd/mm/yy', date)));
		}	
	});

	
	$(currentForm).find("#fechaSal").datepicker("destroy").datepicker({
		onSelect: function(date, i) {
			var selectedDate = new Date($.datepicker.parseDate('dd/mm/yy', date));
			var toDate = new Date( selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate()-0+difDias);
			$(currentForm).find("#fechaReg").datepicker('option', 'minDate', toDate);
			var fechaRegDate = new Date($.datepicker.parseDate('dd/mm/yy', $(currentForm).find("#fechaReg").val() ));
			if (toDate > fechaRegDate) {
				$(currentForm).find("#fechaReg").datepicker('setDate', toDate);
			}
			
			$(currentForm).find("#fechaSal").datepicker('setDate', new Date($.datepicker.parseDate('dd/mm/yy', date)));
			
		}	
	});
	
	$(currentForm).find("#fechaReg").datepicker("destroy").datepicker({
		defaultDate: iDiasT,
		minDate: iDiasT,
		onSelect: function(date, i) {
		$(currentForm).find("#fechaReg").datepicker('setDate', new Date($.datepicker.parseDate('dd/mm/yy', date)));
		}
	});

	$(currentForm).find(".autocompletable").autocomplete(
			url_auto, 
			{
				minChars: 3, 
				max: 150,
				mustMatch: true,
				matchContains: false,
				formatResult: 
					function(data,value) {
						return getSelectionId(value);
					}
			});
		
	$(".ui-datepicker-trigger").css("cursor","pointer");

	$("#ui-datepicker-div").css("z-index", 2000);

	/* Ida y Vuelta */
	$(currentForm).find(".idayvuelta").click (function () {
		if ( $(this).attr('id') == 'h1' ) {
			//$(currentForm).find(".regreso input, .regreso select").removeAttr("disabled");
			$(currentForm).find(".regreso input, .regreso select").css("background-color", "");
			//$(currentForm).find("#chkflexible").removeAttr("disabled");
			//$(currentForm).find("#fechaReg").datepicker("enable");
			$(currentForm).find("#trRegreso").css("visibility", "");
			$(currentForm).find("#chkflexible_td").css("visibility", "");
			$(".ui-datepicker-trigger").css("cursor","pointer");
			
		}
		else
		{
			//$(currentForm).find(".regreso input, .regreso select").attr("disabled", true);
			$(currentForm).find(".regreso input, .regreso select").css("background-color", "#D4D0C8");
			//$(currentForm).find("#chkflexible").attr("disabled", true);
			//$(currentForm).find("#fechaReg").datepicker("disable");
			$(currentForm).find("#trRegreso").css("visibility", "hidden");
			$(currentForm).find("#chkflexible_td").css("visibility", "hidden");
		}
	});		

	
	$(currentForm).find("#destino_multiple").scroll(function () { 
		$(currentForm).find('#fechaSalida1').datepicker('hide');
	});
	
	if ($(lastForm).find("#check_multiples").is(":checked") ) {		
		$(currentForm).find('#check_multiples').attr("checked", "checked");
		toggle_display_destinos();
	}
	else
	{		
		//$(currentForm).find('#check_multiples').attr("checked", "");
		toggle_display_destinos();
	}
	
	if (lastForm != null) {
		if ($(lastForm).find("#h1").is(":checked") ) {
			$(currentForm).find('#h1').attr("checked", "checked");
			//$(currentForm).find(".regreso input, .regreso select").removeAttr("disabled");
			$(currentForm).find(".regreso input, .regreso select").css("background-color", "");
			//$(currentForm).find("#chkflexible").removeAttr("disabled");
			$(currentForm).find("#chkflexible_td").css("visibility", "");
		}
		else
		{
			$(currentForm).find('#h2').attr("checked", "checked");
			//$(currentForm).find(".regreso input, .regreso select").attr("disabled", true);
			$(currentForm).find(".regreso input, .regreso select").css("background-color", "#D4D0C8");
			//$(currentForm).find("#fechaReg").datepicker("disable");
			//$(currentForm).find("#chkflexible").attr("disabled", true);
			$(currentForm).find("#trRegreso").css("visibility", "hidden");
			$(currentForm).find("#chkflexible_td").css("visibility", "hidden");
		}
	}
	
	if($(currentForm).find("#h2").attr("checked")){
		$(currentForm).find("#h2").click();
	}
}

    function toggle_display_destinos () {
		if ($(currentForm).find("#check_multiples").is(":checked") ){
			$(currentForm).find('#destino_multiple').show();
			$(currentForm).find('#destino_simple').hide();		
		}else{
			$(currentForm).find('#destino_multiple').hide();
			$(currentForm).find('#destino_simple').show();
		}
	}
	

  //Se utiliza para copiar valores de un campo a otro, si el destino esta vacio
  function pasarValores(idDestino, idOrigen){
  	//if ($(currentForm).find("#"+idDestino).val() == ''){
  		$(currentForm).find("#"+idDestino).val($(currentForm).find("#"+idOrigen).val());
  		$(currentForm).find("#"+idDestino+"ID").val($(currentForm).find("#"+idOrigen+"ID").val());
  	//}
  }
    
    
	//Validacion Motor Aereos
	function validate_and_send_aereos_form(){
		if ($(currentForm).find('#check_multiples').attr("checked") ) {
			if ($(currentForm).find("#origen1").val() == '') {
				alert(origenMsgError);
				$(currentForm).find("#origen1").focus();
				return false;
			}
			if ($(currentForm).find('#destino1').val() == '') {
				alert(destinoMsgError);
				$(currentForm).find("#destino1").focus();
				return false;
			}
			if ($(currentForm).find("#fechaSalida1").val() == '') {
				alert(fechaSalidaMsgError);
				return false;
			}
		}else{
			if ($(currentForm).find('#origen').val() == '') {
				alert(origenMsgError);
				$(currentForm).find('#origen').focus();
				return false;
			}
			if ($(currentForm).find('#destino').val() == '') {
				alert(destinoMsgError);
				$(currentForm).find('#destino').focus();
				return false;
			}
			if ($(currentForm).find('#fechaSal').val() == '') {
				alert(fechaSalidaMsgError);
				return false;
			}
			if ($(currentForm).find('#h1').is("checked") ){
				if ($(currentForm).find('#fechaReg').val() == '') {
					alert(fechaRegMsgError);
					return false;
				}
			}
		}
		
		if ( $(currentForm).find("#check_multiples").is(":checked") ) {	
		      var destinosCompletos = 0;
		      var inputCompletosCounter = 0;
		      var numIdAnterior = 0;
		      $(currentForm).find(".destinomult").find("input:text").each (
				      function(index, el){
					      var elementId =  $(el).attr('id');
					      var numeroId = elementId.substring ( elementId.length - 1, elementId.length);
					      	if (numeroId == numIdAnterior) {
								if ( $(el).val() != '' ) {
									inputCompletosCounter ++;
									if (	inputCompletosCounter == 3)
										destinosCompletos++;		
								}
					      	}
					      	else
					      	{
					      		numIdAnterior = numeroId;
					      		inputCompletosCounter = 0;
					      		if ( $(el).val() != '' ) 
									inputCompletosCounter ++;
					      	}	   
					});

				if (destinosCompletos >= MULTI_DESTINOS_CANTIDAD_SALTOS) {							
					currentForm.submit();
					displayChat();							
				}
				else {
					var msg =tresDestinosMsgError;
					alert (msg);
					return false;
				}
		}
		
		if($(currentForm).find('#paxs').val() < $(currentForm).find('#paxs_INF').val()){
			alert ("Cada infante debe ir acompa\u00F1ado por un adulto.");
			return false;
		}
		
		$(currentForm).submit();
	}
	
	// Se utiliza para copiar valores de un campo a otro, si el destino esta vacio
	function set_value_on_next(idDestino, valor){
		if ($(currentForm).find("#"+idDestino).val() == ''){
			$(currentForm).find("#"+idDestino).val(valor);
		}
	}


	function getSelectionId(value) {
		doIEhackForCombos(null);
		
		return value.split("'")[1];
	}
	

function lookAndFeelForHome () {
		if (jQuery.browser.msie ) {
			$(".menu_busqueda_columna").css ("padding-top", 0);
			$(".menu_busqueda_columna").css ("padding-top", 0);
		}
		
		if ($(".menu_busqueda").height() != null) { 
			$("#fixedCuerpoIzquierda").height ( $(".menu_busqueda").height() );
		}
}


function lookAndFeelForFloatSearch () {
	//$(".menu_busqueda_columna").css('padding-left', '20px');
	//$(".menu_busqueda_opciones").css('margin-left', -20);
	$(".menu_busqueda").css('width', 285);	
}



function cleanIFrame () {
	$("#iFrameCentro").attr("src", "");
}

function showBusquedaAvanzada () {
	displayAvanzada();
	cleanIFrame();
	setBuscadorParams();	
}

function functionalitiesForHome () {	
	$("#vuelos-tab").click (function (){
		$.ajax({
		    type: "POST",
		    url: "/busquedaVuelos/busquedaVuelos_init.do?method=initOnly",	    
		    success: function(response) {
		      $("#cuerpoIzquierda").html (response);
		      functionalitiesForHome();
		    }
		  });
	});
	
	$("#hoteles-tab").click (function (){
		$.ajax({
		    type: "POST",
		    url: "/busquedaHoteles/busquedaHoteles_init.do?method=initOnly",	    
		    success: function(response) {
		      $("#cuerpoIzquierda").html (response);
		      functionalitiesForHome();
		    }
		  });
		
	});
	
}


function functionalitiesForFloatSearch () {	
	
	$("#vuelos-tab").click (function (){
		//window.location.href="/contenedorBusquedaVuelosAction.do";
		$.ajax({
		    type: "POST",
		    url: "/busquedaVuelos/busquedaVuelos_init.do?method=initOnly",	    
		    success: function(response) {
		      $("#menu_buscador").html (response);
		      functionalitiesForFloatSearch();
		    }
		  });
	});
	
	$("#hoteles-tab").click (function (){
		//window.location.href="/contenedorBusquedaHotelesAction.do";
		$.ajax({
		    type: "POST",
		    url: "/busquedaHoteles/busquedaHoteles_init.do?method=initOnly",	    
		    success: function(response) {
		      $("#menu_buscador").html (response);
		      functionalitiesForFloatSearch();
		    }
		  });
		
	});
	
	
	 $("#btnAvanzada").click (function (event) {
		 displayAvanzada() ;
	    });

	    $("#btnBasica").click (function (event) {
	    	$('#cuerpoIzquierda').css('position', 'relative');
	    	$(".td_btnBasica").hide();
	    	$(".td_btnAvanzada").show();						
	    	$(".avanzada").hide();
	    		    	
	    	$("#single").show(); 
	    	$("#double").hide();
	    	$("#aero2").hide();	  
	    	

	    	 $('.menu_busqueda').animate({
	    		    width: 285 }, 500, 'linear', function() {
	    		    	$(".aeroAvanzada").css("display", "none");
	    		  });
	    });				   				    
}
 

function cambiarEtapa(estiloPaso1,estiloPaso2,estiloPaso3){

	$(".stepsRSS td span").removeClass("currentStep");
	
	if (estiloPaso1){
		//$(".stepRSS").css ('background-image','url(background: url(../img/step1.png) ;)')
		$("#step1RSS").addClass("currentStep");
	}
	
	if (estiloPaso2){
		//$(".stepRSS").css ('background-image','url(background: url(../img/step2.png);)')
		//$("#step2RSS").addClass("currentStep");
	}
	
	if (estiloPaso3){
		//$(".stepRSS").css ('background-image','url(background: url(../img/step3.png) ;)')
		//$("#step3RSS").addClass("currentStep");
	}
	
}


function getById(obj) {
	return document.getElementById(obj);
}

function HsetRooms(obj){
	num = obj.value;
	tot = obj.options.length;
	
	for(var i=(Number(num)+1); i<=tot; i++){
		getById('a' + i + '_ADTs').style.visibility='hidden';
		getById('a' + i + '_CHDs').style.visibility='hidden';
		getById('a' + i + '_Age1').style.visibility='hidden';
		getById('a' + i + '_Age2').style.visibility='hidden';
		getById('textAge1').style.visibility='hidden';
		getById('textAge2').style.visibility='hidden';
	
	}
	var i=1;
	for(i=1; i<=num; i++){
		getById('a' + i + '_ADTs').style.visibility='visible';
		getById('a' + i + '_CHDs').style.visibility='visible';
		var chd = getById('a' + i + '_CHDs');
		for(var j=1; j<=chd.value; j++){
			getById('a'+ i + '_Age' + j).style.visibility='visible';
			getById('textAge' + j).style.visibility='visible';
		}

	
	}
	

}

function HsetAge(obj){
	getById('textAge1').style.visibility='visible';
	getById('textAge2').style.visibility='visible';
	num = obj.value;

	id = obj.name.substr(1,2).replace('_','');
	switch(num){
		case "0":
			getById('a' + id + '_Age1').style.visibility='hidden';
			getById('a' + id + '_Age2').style.visibility='hidden';
			getById('textAge1').style.visibility='hidden';
			getById('textAge2').style.visibility='hidden';
		break;

		case "1":
			getById('a' + id + '_Age1').style.visibility='visible';
			getById('a' + id + '_Age2').style.visibility='hidden';
			getById('textAge1').style.visibility='visible';
			getById('textAge2').style.visibility='hidden';
		break;

		case "2":
			getById('a' + id + '_Age1').style.visibility='visible';
			getById('a' + id + '_Age2').style.visibility='visible';
			getById('textAge1').style.visibility='visible';
			getById('textAge2').style.visibility='visible';
		break;
	}
	/*
	_textAge1=0;
	for(var i=1;i<=3;i++){
		if(getById('a'+i+'_Age1').style.visibility=='hidden'){
			_textAge1++;
		}
	}
	if(_textAge1>2){
		getById('textAge1').style.visibility='hidden';
	}

	_textAge2=0;
	for(var i=1;i<=3;i++){
		if(getById('a'+i+'_Age2').style.visibility=='hidden'){
			_textAge2++;
		}
	}
	if(_textAge2>2){
		getById('textAge2').style.visibility='hidden';
	}
	*/
}

function updateSelectNoches(desde, hasta, selectDias){
	
	$(hasta).datepicker('hide');
	var d = $(desde).datepicker('getDate');
	var h = $(hasta).datepicker('getDate');
	var sd = parseInt($(selectDias).val());
	var dias = (h.getTime() - d.getTime()) / 86400000;

	if ( !($(selectDias + ' option[value=' + dias + ']').length > 0) ) {
		$(selectDias).append("<option value=" + dias + ">" + dias + "</option>");
	}
	$(selectDias).val(dias);
}

function updateDateHotel(desde, hasta, selectDias){
	
	var d = $(desde).datepicker('getDate');
	var h = $(hasta).datepicker('getDate');
	var dias = parseInt($(selectDias).val());
	var toDate = new Date(h.getFullYear(), h.getMonth(), h.getDate());
	var toChange = new Date(d.getFullYear(), d.getMonth(), d.getDate()-0+dias);
	
	$(hasta).datepicker('setDate', toChange);
	$(hasta).datepicker('hide');
}


function setBuscadorParams(){	 
	  var url = window.location.search;	  
	    var strQueryString = url.substr(url.indexOf("?"));
	    var aQueryString = strQueryString.split("&");
	    for ( var aParam = 0; aParam < aQueryString.length; aParam++ ){
	    	var valuePairParam = aQueryString[aParam].split("=");
	    	$("*[name=" + valuePairParam[0] +"]").val (unescape (valuePairParam[1] ).replace ("+", " ") );	
	    }
}

function setBuscadorParamsFor(params){
	    var strQueryString = params;
	    var aQueryString = strQueryString.split("&");
	    for ( var aParam = 0; aParam < aQueryString.length; aParam++ ){
	    	var valuePairParam = aQueryString[aParam].split("=");
	    	if(valuePairParam[0]!="radioIV"){
	    		$(currentForm).find("*[name=" + valuePairParam[0] +"]").val (unescape (valuePairParam[1] ).replace ("+", " ") );
	    	}
	    }
}


function slideBuscador () {
	var left = "";
	  if($("#slide_buscador_2").attr("offsetLeft") < 0){
		$("#slide_buscador").css("width","303px");
		$("#slide_buscador_2").animate({"left": "+=285px"}, "slow");
	    
	  } else {
	    $("#slide_buscador_2").animate({"left": "-=285px"}, "slow", function(){$("#slide_buscador").css("width","20px");});
	  }
	  
	  
	
}


$(document).ready(function () {
	$('#button_buscador').click (function (event) {
		slideBuscador() ;
    });
	
	if($("#busquedaHotelesForm").length == 1){
		HsetRooms($("#rooms")[0]);
	}
});

