/*   CREACION DE SUBMITS PARA FORMULARIO  ----------------------------------------------------------------------*/
	var pdf = function(){
		jQuery('#formReseCont').append('<input type="hidden" name="pdfrecu" value="creapdf" />');
		document.forms[0].submit();
		return false;
	}
	var pdf2 = function(){
		jQuery('#formconfirm').append('<input type="hidden" name="pdfrecu2" value="creapdf2" />');
		document.forms[0].submit();
		return false;
	}

/*   COLAPSABLES Y APPEARS GENERALES ---------------------------------------------------------------------------*/
var proto = {
	calendario : function(){
		/*$j.map($j(".cale"),function(e){
			$j("#" + e.id).calendar({ autoPopUp: 'both', buttonImageOnly: true,buttonImage: 'https://www.monterilla.cl/templates/default/imag/auxi/auxiCale.gif', buttonText: '&Iacute;cono de calendario para fecha de inicio',firstDay: 1,dayNames: ['D','L','M','M','J','V','S'],monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agoto','Septiembre','Octubre','Noviembre','Diciembre'],currentText:'Hoy',nextText:'Sig&#187;',prevText:'&#171;Ant',closeText:'Cerrar',clearText:'Limpiar'});
		})*/
	},
	queEsVali : function(){
		jQuery('#oculVali').toggle();
	},
	queSkype : function(){
		jQuery('#oculSkype').toggle();
	},
	oculRss : function(){
		jQuery('#oculRss').toggle();
	},
	oculRssGene : function(){
		jQuery('#oculRssGene').toggle();
	},
	vali : function(){
		jQuery('#subValida').toggle();
	},
	linkRese : function(){
		jQuery('#linkRese').slideToggle();
	},
	verCond : function(){
		if (jQuery('#oculCond')[0].style.display=='none'){
			if(jQuery('#acepEn').length > 0){
				jQuery('#linkCond')[0].innerHTML="(Hide conditions)";
			}
			else{
				jQuery('#linkCond')[0].innerHTML="(Ocultar condiciones)";
			}
		}
		else{
			if(jQuery('#acepEn').length>0){
				jQuery('#linkCond')[0].innerHTML="(View conditions)";
			}
			else{
				jQuery('#linkCond')[0].innerHTML="(Ver Condiciones)";
			}
		}
		jQuery('#oculCond').slideToggle();
	},
	verPoli : function(){
		if (jQuery('#oculPoli')[0].style.display=='none'){
			jQuery('#linkPoli')[0].style.display='none';
			jQuery('#strongPoli')[0].style.display='';
		}
		else{
			jQuery('#linkPoli')[0].style.display='';
			jQuery('#strongPoli')[0].style.display='none';
		}
		jQuery('#oculPoli').slideToggle();
	},
	paso3 : function(){
		if(jQuery('#acep')[0].checked==true){
			jQuery('#paso3').removeAttr('disabled').addClass('boton').removeClass('botonInac');
		}
		else{
			jQuery('#paso3').attr('disabled', 'disabled').addClass('botonInac').removeClass('botonInac');
		}
	},
	numePasa : function(responseXMLCli){
		var item=responseXMLCli.responseXML.documentElement.getElementsByTagName('contenido')[0];
		var pasajero=item.getElementsByTagName('pasajero')[0].firstChild.data;
			if(pasajero==0){
				$('numePasa').update('1');
				$('plural').update('');
			}
			if(pasajero==1){
				$('numePasa').update('1');
				$('plural').update('');
			}
			else{
				$('numePasa').update(pasajero);
				$('plural').update('s');
			}
	},
	cm: function (texto) {
		var moneda = "";
		texto = parseInt(texto);
		texto = "" + texto;
		dec=0;
		for ( i=(texto.length-1); i>=0 ; i-- ) {
		if ( dec == 3 ) {
		moneda = "." + moneda;
		dec = 1;
		} else
		dec++;
		moneda = texto.charAt(i) + moneda;
		}
		moneda = moneda;

		return moneda;
	}
	//~ adds:function(){
		//~ if (!$('oferta')){
			//~ $('cargando').hide();

		//~ var F = $('formReseCont').serialize(true);
		//~ var precio=F.habitacion;
		//~ var dolar=F.dolar;
		//~ /*calculamos los dias*/
		//~ var r = F.intime.split("/");
		//~ var e = F.outtime.split("/");
		//~ t = Math.floor((new Date(e[2],e[1],e[0]).getTime() - new Date(r[2],r[1],r[0]).getTime()) / (1000*60*60*24));
		//~ if (t < 0 || !t){ var t=0;}
		//~ //alert(e);
		//~ $('peso').update(proto.cm(precio*t));
 		//~ $('dolar').update(Math.floor( ( (precio*t) / (119/100) ) /dolar ) );
		//~ var h=$('habitacion').selectedIndex;
		//~ var hab=$('habitacion').options[h].text;
		//~ if (hab=="Doble Estándar" ||  hab=="Doble Superior" || hab=="Suite" || hab=="Standard Double" || hab=="Special Double") $('estaPref').show();
		//~ else $('estaPref').hide();
		//~ var pars = 'pasajeros='+hab;
		//~ var url = '/getajax.php';
		//~ var myAjax = new Ajax.Request(
		//~ url,{
			//~ method: "get",
			//~ parameters: pars,
			//~ onComplete: proto.numePasa
		    //~ }
		//~ );
		//~ }
	//~ }
};
/*
	* Función menuCamp
	* Función encargada de paginar los contenidos de campanas y promociones full
	* @param {string} Contienen el elemento [objeto] al que se le ha hecho click
*/
var porid = {
	idname: function(e) {
		if(e.target.id){
			if(eval("this."+e.target.id)!=undefined){
				eval("this."+e.target.id)(e.target);
				}
			}
	},
	menuCont : function(){
		jQuery(".seccCamp").hide();
		if(document.URL.match(/#n/)){
			url = document.URL.split("#");
			jQuery("#"+url[1]).show();
			jQuery("#link-"+url[1]).parent().addClass("acti");
		}
		else{
			jQuery("#n1").show();
			jQuery("#link-n1").parent().addClass("acti");
		}
	},
	linkMenuCont : function(e){
		url = e.target.href.split("#");
		jQuery(".seccCamp").hide();
		jQuery("#menuCont li").removeClass("acti");
		jQuery("#"+url[1]).show();
		jQuery("#"+e.target.id).parent().addClass("acti");
	},
	startImagTop : function(){
		jQuery('.contImag').innerfade({
			animationtype: 'fade',
			speed: 200,
			timeout: 4000,
			type: 'random_start',
			containerheight: '336px'
		});},
	startPlanTop : function(){
		jQuery('.contPlan').innerfade({
			animationtype: 'fade',
			speed: 200,
			timeout: 4000,
			type: 'random_start',
			containerheight: '336px'
		});
	},
	stopImagTop : function(e){
		clearTimeout(time);
		jQuery("#imagThum li").removeClass("acti");
		imag = e.target.id.split("-");
		jQuery(".contImag li").fadeOut(200)
		jQuery("#"+imag[1]).fadeIn(200);
		jQuery("#"+e.target.id).parent().parent().addClass("acti");
	},
	stopPlanTop : function(e){
		clearTimeout(time);
		jQuery("#planThum li").removeClass("acti");
		imag = e.target.id.split("-");
		jQuery(".contPlan li").fadeOut(200)
		jQuery("#"+imag[1]).fadeIn(200);
		jQuery("#"+e.target.id).parent().parent().addClass("acti");
	}
}

var porclass = {
	boxShow : function(e){
		var id = e.target.id.split("link-");
		jQuery("#ocul-"+id[1]).fadeIn(500);
	},
	boxHide : function(e){
		var id = e.target.id.split("link-");
		jQuery("#ocul-"+id[1]).fadeOut(500);
	}
}

/*   DETECCION DE EVENTOS GENERALES  ------------------------------------------------------------------------*/
	 jQuery.noConflict();
	//inicializamos todo

window.onload = function() {
	jQuery(".hide").hide();

	jQuery(".cruiOfer").change(function(e){
		jQuery(this).parents('fieldset').children('input[type=submit]').removeAttr('disabled').removeClass('botonInac').addClass('boton');
		var entrada = e.target.value;
		var r = entrada.split("/");
		var salida =  parseInt(r[0]) + 1 + "/" + r[1]  + "/" +r[2];
		jQuery('#outtime1').val(salida);
	});

	if( document.getElementById("menuCont") ){
		porid.menuCont();
		porid.startImagTop();
		porid.startPlanTop();
		jQuery("#menuCont li a").bind("click",function(e){ porid.linkMenuCont(e); return false; });
		jQuery("#imagThum li a").bind("click",function(e){ porid.stopImagTop(e); return false; });
		jQuery("#planThum li a").bind("click",function(e){ porid.stopPlanTop(e); return false; });
	}

	jQuery("select[name=intime]").change(function(e){
		if ( jQuery(this).val()!='Fecha de Ingreso' ){
			var intime0 = jQuery(this)[0].selectedIndex;
			jQuery(this).next('select').children('option:eq('+intime0+')').attr('selected', 'selected');
			jQuery(this).siblings('input[type=submit]').removeAttr('disabled').removeClass('botonInac').addClass('boton').next().attr('disabled','disabled');
			
		}
		else{
			if ( jQuery.trim( jQuery(this).val() ) == '' ) {
				jQuery(this).siblings('input[type=submit]').attr('disabled', 'disabled').addClass('botonInac').removeClass('boton');
			}
		}
	});

        jQuery("select[name=outtime]").change(function(e){
	      if ( jQuery(this).val()!='Fecha de Salida' ){
		var outtime0 = jQuery(this)[0].selectedIndex;
		jQuery(this).prev('select').children('option:eq('+outtime0+')').attr('selected', 'selected');
                jQuery(this).siblings('input[type=submit]').removeAttr('disabled').removeClass('botonInac').addClass('boton').next().attr('disabled','disabled');

	      } else {
		  if ( jQuery.trim( jQuery(this).val() ) == '' ) {
                       jQuery(this).siblings('input[type=submit]').attr('disabled', 'disabled').addClass('botonInac').removeClass('boton');
                  }
	      }	
	});

			jQuery('#queBlogA, #queEsVali, #queRssGene').attr('href', 'javascript:;');
			jQuery('#subValida, #oculCond, #oculPoli, #linkReseOcul').hide();
			if(jQuery('#estaPref').length>0){
				var h= jQuery('#habitacion')[0].selectedIndex;
				var hab= jQuery('#habitacion')[0].options[h].text;
				if (hab!="Doble Estándar" &&  hab!="Doble Superior" && hab!="Suite" && hab!="Standard Double" && hab!="Special Double") jQuery('#estaPref').hide();
			}
			
		jQuery('.js').bind("click", function(e){porid.idname(e); return false;});
		jQuery('.boxShow').mouseover(function(e){porclass.boxShow(e); return false;});
		jQuery('.boxShow').mouseout(function(e){porclass.boxHide(e); return false;});


	/*proto*/
		jQuery('#queEsVali, #cerrarVali').click(function(){ proto.queEsVali(); });
		jQuery('#queSkype, #cerrarSkype').click(function(){ proto.queSkype(); });
		jQuery('#queBlog, #cerrarRss').click(function(){ proto.oculRss(); });
		jQuery('#queRssGene, #cerrarRssGene').click(function(){ proto.oculRssGene(); });
		jQuery('#valida').click(function(){ proto.vali(); });
		jQuery('#linkCond').click(function(){ proto.verCond(); });
		jQuery('#linkReseOcul').click(function(){ proto.linkRese(); });
		jQuery('#linkPoli, #linkPoliSec').click(function(){ proto.verPoli(); });
		jQuery('#acep').click(function(){ proto.paso3(); });
	/*end proto*/
	/*formularios calculos*/
	/*end formularios calculos*/
	
		jQuery('#pdf1').click( function(){ pdf() });
		jQuery('#pdf2').click( function(){ pdf2() });

		// Deshabilitamos el formulario
		if ( jQuery.trim( jQuery('#intime').val() ) == '' ) {
			jQuery("#paso0, #outtime").attr('disabled','disabled');
		}
		//~ jQuery("#outtime").attr('disabled','disabled');
		//~ jQuery("#habitacion").attr('disabled','disabled');
		
		/*		
			Función para el widget de la portada de la reserva
			@author: Fabian Ramirez
			@email: <framirez@ayerviernes.com>
			@version: 1.0 Stable
					  0.x Alpha <Max Villegas & Basilio Caceres>
		*/
		
		if(!jQuery('#dolarHide').val() != 0 && document.getElementById('intime') != null) {			

			jQuery("#intime").datepicker(
			{
				showOn: 'both',			
				buttonImage: location.protocol+'//monterilla.cl/templates/default/imag/auxi/auxiCale.gif',
				buttonImageOnly: false,
				dateFormat: "dd/mm/yy",
				minDate: new Date(),
				onSelect: function() {
					jQuery("#outtime").removeAttr('disabled').datepicker("destroy");
					checkOutDate = Date.parse(jQuery(this).datepicker("getDate"));
					checkOutDate = new Date(checkOutDate);
					checkOutDate.setDate(checkOutDate.getDate() + 1);	

						jQuery("#outtime").datepicker(
						{
							minDate: checkOutDate,
							showOn: 'both',						
							buttonImage: location.protocol+'//monterilla.cl/templates/default/imag/auxi/auxiCale.gif',
							buttonImageOnly: false,
							dateFormat: "dd/mm/yy",
							onSelect: function() {
								jQuery("#paso0, #habitacion").removeAttr('disabled');
								jQuery("#ui-datepicker-div").hide();							
							}
						}).focus();

				}
			});
		} else {
						
			/*
			
				Función para el primer paso de la reserva
				@author: Fabian Ramirez
				@email: <framirez@ayerviernes.com>
				@version: 1.0 Stable
			*/
			
			// Funcion que calcula los días entre la entrada y la salida
			var calcularDias = function() {
			 	return  ((Date.parse(jQuery("#outtime").datepicker("getDate")) - Date.parse(jQuery("#intime").datepicker("getDate"))) / (1000*60*60*24));
			}							
			// Función para formatear los numeros en miles con punto
			var formatearNumerosConPunto = function(str)
			{
				str = str.toString();
				var num = str.replace(/\./g,"");
				if(!isNaN(num)){
					num = num.toString().split("").reverse().join("").replace(/(?=\d*\.?)(\d{3})/g,"$1.");
					num = num.split("").reverse().join("").replace(/^[\.]/,"");
					return num;
				}else{
					return num.replace(/[^\d\.]*/g,"");
				}
			}
			// Función que calcula el nuevo precio de la habitación al jugar con los inputs
			var calcularNuevoPrecio = function() {
				if(parseInt(jQuery("#habitacion :selected").val()) != 0) {
					jQuery("#paso1, #precio").show();
					jQuery.ajax({
					    type: "GET",
						url: "/getajax.php?pasajeros=" + encodeURIComponent(jQuery("#habitacion :selected").text()),
						dataType: "xml",
						success: function(xml) {
							jQuery(xml).find('contenido').each(function(){												

								// Tomamos los valores de las variables traidos via XML
								pasajeros = jQuery(this).find('pasajero').text();	
								precio_pesos = parseInt(jQuery(this).find('pesos').text()) * calcularDias();
								precio_dolares = parseInt(jQuery(this).find('dolares').text());
								
								precio_dolares = Math.floor((precio_pesos/(119/100))/precio_dolares);
								
								precio_pesos = formatearNumerosConPunto(precio_pesos);									
								precio_dolares = formatearNumerosConPunto(precio_dolares);

								// Modificamos los valores del HTML											
								jQuery("#numePasa").html(pasajeros);
								jQuery("#peso").html(precio_pesos);
								jQuery("#dolar").html(precio_dolares);

								if(pasajeros > 1) {
									jQuery("#plural").html('s');
								} else {
									jQuery("#plural").html('');
								}
							});
						}
					});	
				} else {
					jQuery("#paso1, #precio").hide();
				}
				
			}
			
			// Fecha de entrada	
			if(document.getElementById('intime')) {
			jQuery("#intime").datepicker(
			{
				regional: 'es',
				showOn: 'button', 
				buttonImage: location.protocol+'//monterilla.cl/templates/default/imag/auxi/auxiCale.gif',
				buttonImageOnly: false,
				dateFormat: "dd/mm/yy",
				minDate: new Date(),
				onSelect: function() {
					jQuery("#outtime").removeAttr('disabled').datepicker("destroy");
					checkOutDate = Date.parse(jQuery(this).datepicker("getDate"));
					checkOutDate = new Date(checkOutDate);
					checkOutDate.setDate(checkOutDate.getDate() + 1);	
					jQuery("#paso1").hide();						
					
						// Fecha de salida regenerada
						jQuery("#outtime").datepicker(
						{
							minDate: checkOutDate,
							showOn: 'both',						
							buttonImage: location.protocol+'//monterilla.cl/templates/default/imag/auxi/auxiCale.gif',
							buttonImageOnly: false,
							dateFormat: "dd/mm/yy",
							onSelect: function() {
								calcularNuevoPrecio();
								jQuery("#paso0, #habitacion").removeAttr('disabled');
								jQuery("#ui-datepicker-div").hide();
							}
						}).focus();
				}
			});
			
			
			// Necesito tomar la fecha de llegada, para desabilitarlo de la fecha de salida como fecha minima
			checkInDate = Date.parse(jQuery("#intime").datepicker("getDate"));
			checkInDate = new Date(checkInDate);
			checkInDate.setDate(checkInDate.getDate() + 1);
			
			// Fecha de salida
			jQuery("#outtime").datepicker(
			{
				showOn: 'button', 
				buttonImage: location.protocol+'//monterilla.cl/templates/default/imag/auxi/auxiCale.gif',
				buttonImageOnly: false,
				dateFormat: "dd/mm/yy",
				minDate: checkInDate,
				onSelect: function() {
					calcularNuevoPrecio();
				}
			});

			// Cuando se modifique el select
			jQuery("#habitacion").change(function() {
				calcularNuevoPrecio();
			});
			
			// Cuando el valor del tipo de habitaciones este vacio, entonces escondemos los controles
			if(parseInt(jQuery("#habitacion :selected").val()) == 0) {
				jQuery("#paso1, #precio").hide();
			// Si no esta vacio, mostramos los controles
			} else {
				calcularNuevoPrecio();
			}
			
		}	}

};

