// <![CDATA[
	var textoEstudio;
	$(document).ready(
		function() {
			$('#pinpin').click(function(){
				if($('#pines').css('display')=='none'){
					$('#errorpin').hide();
					$('#pines').fadeIn();
				}
			});
			$('.cancelarReserva').click(function(){
			     if($(this).hasClass("pagar")){
			         $(this).parent().attr('action','pagos.php').attr('target','_blank');
			         $(this).parent().submit();
			     }else{
			        if(confirm(cancelarMensaje)){
					   $(this).parent().submit();
    				}else{
    					return false;
    				} 
			     }
			
			});
			$('.factPrint').click(function(){
				$(this).parent().submit();
			});
			$('.masOpt').click(function(){
						$(this).parent().parent().next('.opts').animate({height:'toggle'},'fast').show('fast');
						$(this).hide();
						$(this).parent().children('.menosOpt').show();
					});
			$('.menosOpt').click(function(){
				$(this).parent().parent().next('.opts').animate({height:'toggle'},'fast').hide('normal');
				$(this).hide();
				$(this).parent().children('.masOpt').show();
			});
			$("#idCiudad").each(function() {
				$.ajax({
					type	: "POST",
					cache	: false,
					url		: "../includes/buscazona.php",
					data	: "ciudad_id="+$("#idCiudad :selected").val(),
					success: function(data) {
						$("#zona").html('');
						$("#zona").html(data);
						$("#zonas").change(function(){
							$('#mascaraZona').each(
									function() {$(this).text($(this).parent().children('#zonas').children(':selected').text())}
								);
						});
					}
					});
				
			});
			$("#idCiudad").change(function() {
				$.ajax({
					type	: "POST",
					cache	: false,
					url		: "../includes/buscazona.php",
					data	: "ciudad_id="+$("#idCiudad :selected").val(),
					success: function(data) {
						$("#zona").html('');
						$("#zona").html(data);
						$("#zonas").change(function(){
							$('#mascaraZona').each(
									function() {$(this).text($(this).parent().children('#zonas').children(':selected').text())}
								);
						});
					}
					});
				
			});			
			$("select[name*=tipo_alojamiento]").change(function(){ 
				var elegido=$(this).children(":selected").val();
				if(elegido>1){
					textoEstudio=$("select[name*=idHabitacion]").find("option[value='0']").text();
					$("select[name*=idHabitacion]").find("option[value='0']").remove();
				}else{
					if($("select[name*=idHabitacion] option[value=0]").length == 0){
						$("select[name*=idHabitacion]").append($(document.createElement("option")).attr("value","0").text(textoEstudio));
						$("select[name*=idHabitacion]").html($("select[name*=idHabitacion] option").sort(function (a, b) {
						    var aValue = parseInt(a.value);
						    var bValue = parseInt(b.value);
						    return aValue == bValue ? 0 : aValue < bValue ? -1 : 1;
						}));
						 
						// Reselect the first option*/
						$('select[name*=idHabitacion]').val('-1');
					}
				}
				
			});
			$("#colaboradorRegistro").click(function(){
				$("#colaboradores").hide();
				$(".frmAltaPropietario").show();
			});
			
			//Enviar por AJAX del boton a suscribir al newsletter
			$("#SendNews").click(function() {  
				var mail = $('#newsMail').val();  
				//alert(mail);  
				$.ajax({  
				  type: "POST",  
				  url: "includes/procesaNewsletter.php",  
				  data: "mail="+mail,  
				  success: function(msg) {
						if(msg){
							$("#newsLetta").hide();
							$('p').removeClass('no');
						}else{
							$('span#newsError').removeClass('no');
						}
				   /* $('#contact_form').html("<div id='message'></div>");  
				    $('#message').html("<h2>Contact Form Submitted!</h2>")  
				    .append("<p>We will be in touch soon.</p>")  
				    .hide()  
				    .fadeIn(1500, function() {  
				      $('#message').append("<img id='checkmark' src='images/check.png' />");  
				    });*/  
						//alert("resultado:" + msg);
					}  
				});  
				return false;
			  });
			$("#newsMail").keyup(function(){
				$('#newsError').addClass('no');
			});
			//Fin del newsletter
			
			//mostar ocultar
			//slides
			$('#coda-slider-1').codaSlider();
			$('#banner1').jqGalScroll({
				ease: null,
				speed: 800,
				height: 350,
				width: 552,
				direction : 'horizontal',
				autoplay: true,
				autoplaySpeed: 4000,
				titleOpacity : 0
			});
			$('#banner2').jqGalScroll({
				ease: null,
				speed: 800,
				height: 420,
				width: 310,
				direction : 'vertical',
				autoplay: false,
				autoplaySpeed: 4000,
				titleOpacity : 0
			});
			//coso para que no meta controles si solo hay una foto... por Pablini
			if($('#banner2 li').length==1){
				($('#banner2').parent().next().attr('style','display:none;')); 
			}
			if($('#banner1 li').length==1){
				($('#banner1').parent().next().attr('style','display:none;')); 
			}
			
			//fin sliders
			$('.vervideo a').click(function() {
				$('.formatoparafoto').hide();
				$('.formatoparavideo').fadeIn();
			});
			$('.verfoto a').click(function() {
				$('.formatoparavideo').hide();
				$('.formatoparafoto').fadeIn();
			});
			
			// carga imagenes
			function cargaImg(sID, sURL) {
				$(sID).unbind("load");
				$(sID).bind("load", function() { $(this).fadeIn(250); } )
				$(sID).stop(true, true).fadeOut(250, function () { $(sID).attr('src', sURL); } );
			}
			// le saca los puntitos de m*** a los links en IE
			if ($.browser.msie) {
				$('a').focus(
					function() {
						$(this).blur()
					}
				);
			}
			// transparencia IE6
			if (es_IE6) { 
				DD_belatedPNG.fix('.transparente, .jScrollArrowDown, .jScrollArrowUp, .jScrollPaneDrag');
			}
			// scrollbars
			if (!es_IE6){
			$('#texto-estilo').jScrollPane({showArrows:true});
			}
			/* estilos para los selects */
			/* ni vale la pena hacer esto en IE 6 */
			if (!es_IE6) {
				$('.select-estilo').css('filter', 'alpha(opacity=0)');
				$('.select-estilo').css('opacity', '0');
				$('.select-estilo').change(function() {
					var opcion = $(this).children(":selected").text();
					$(this).parent().children('.span-estilo').text(opcion);
				});
				$('.select-oferta1').css('filter', 'alpha(opacity=0)');
				$('.select-oferta1').css('opacity', '0');
				$('.select-oferta1').change(function() {
					var opcion = $(this).children(":selected").text();
					$(this).parent().children('.seo-span-estilo1').text(opcion);
				});
				$('.select-oferta2').css('filter', 'alpha(opacity=0)');
				$('.select-oferta2').css('opacity', '0');
				$('.select-oferta2').change(function() {
					var opcion = $(this).children(":selected").text();
					$(this).parent().children('.seo-span-estilo2').text(opcion);
				});
				/* que ponga automáticamente el texto del que este seleccionado */

				$('.span-estilo').each(
					function() {$(this).text($(this).parent().children('.select-estilo').children(':selected').text())}
				);
				$('.seo-span-estilo2').each(
					function() {$(this).text($(this).parent().children('.select-oferta2').children(':selected').text())}
				);
				$('.seo-span-estilo1').each(
					function() {$(this).text($(this).parent().children('.select-oferta1').children(':selected').text())}
				);
			}
			// calendario
			$('#cal-3, #cal-4, #cal-1, #cal-2, #cal-5, #cal-6').datepicker({
				onSelect: function(dateText, inst) { 
							
					$(this).parent().find('.txt-form').val(dateText);
// obtengo en un array las fechas y creo un objeto DATE que contendra las fechas elegida
					var fecha = dateText.split('-');
					// ajuste de fecha
					if(fecha[0][0]==0)
						fecha[0]=fecha[0][1];
					var fs = new Date(fecha[2],(fecha[1]-1),(parseInt(fecha[0]) + 1));
					// obtengo el dia mes y anio por separado
					var dia = fs.getDate();
					var mes = (fs.getMonth()+1);
					var anio = fs.getFullYear();
					// en caso de que el mes o el dia sean menor a 10 en cado caso debo agregar un 0 adelante
					if (dia<10)
						dia = '0' + dia;
					if(mes<10)
						mes = '0' + mes;
					fecha = dia + '-' + mes + '-' + anio;
					// verifico el calendario seleccionado, si es el primero, debo actualizar el segundo con la fecha + 1 y modifico la fecha minima del calendario 2
					if("#"+$(this).attr("id")=='#cal-1'){
						$(this).parent().parent().find('#cal-2').parent().find('.txt-form').val(fecha);
						$('#cal-2').datepicker('option', 'minDate', fs);
				}
// verifico el calendario seleccionado, si es el tercero, debo actualizar el cuarto con la fecha + 1 y modifico la fecha minima del calendario 4
					else if("#"+$(this).attr("id")=='#cal-3'){
						$('#cal-4').datepicker('option', 'minDate', fs);
						$(this).parent().parent().parent().find('#cal-4').parent().find('.txt-form').val(fecha);
								
					} else if("#"+$(this).attr("id")=='#cal-5'){
						$('#cal-6').datepicker('option', 'minDate', fs);
						$(this).parent().parent().parent().find('#cal-6').parent().find('.txt-form').val(fecha)};
					if(("#"+$(this).attr("id")=='#cal-1') || ("#"+$(this).attr("id")=='#cal-2')){
                        getNoches();
					}
					
					getDias(fs.getFullYear(),fs.getMonth()+1,'#cal-4');				
					getDias(fs.getFullYear(),fs.getMonth()+1,'#cal-3');	
					 $(this).slideUp(delay_calendario);
				}
			});
            
			$("#cal-internas").datepicker();
			$("#cal-1, #cal-2, #cal-internas, #cal-3, #cal-4, #cal-5, #cal-6").datepicker('option', 'dayNamesMin', ['D', 'L', 'M', 'M', 'J', 'V', 'S']);
			$("#cal-1, #cal-2, #cal-internas, #cal-3, #cal-4, #cal-5, #cal-6").datepicker('option', 'monthNames', ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre']);
			$('#cal-1, #cal-2, #cal-internas, #cal-3, #cal-4, #cal-5, #cal-6').datepicker('option', 'firstDay', 0);
			$('#cal-1, #cal-2, #cal-internas, #cal-3, #cal-4, #cal-5, #cal-6').datepicker('option', 'dateFormat', 'dd-mm-yy');
			$('#cal-1, #cal-2, #cal-internas, #cal-3, #cal-4, #cal-5, #cal-6').datepicker('option', 'minDate', new Date());

			/** INI :: Sentencias para tachar el calendario **/
			$('#cal-internas, #cal-3, #cal-4').datepicker('option', 'onChangeMonthYear',
				function(year, month, inst) {					
					getDias(year, month, '#' + this.id);
				} 
			);
			/*$('#cal-internas, #cal-3, #cal-4, #cal-1, #cal-2').datepicker('option', 'onSelect',
				function(dateText, inst) {
					getDias(dateText.substring(6,10), dateText.substring(3,5), '#' + this.id);
					alert("hey");
				} 
			);*/

			//iniciaCalendarios();
			/** END :: Sentencias para tachar el calendario **/
			var fs = new Date();
					// obtengo el dia mes y anio por separado
			var mes = (fs.getMonth()+1);
			var anio = fs.getFullYear();
			getDias(anio, mes, '#cal-internas');
			getDias(anio, mes, '#cal-3');
			getDias(anio, mes, '#cal-4');


			var delay_calendario = 250;
			function ocultaCalendarios() {
				$('.calendario-absoluto').each(
					function() {
						$(this).slideUp(delay_calendario);
					}
				);
			}
			$('a.a-calendario').click(
				function() {
					ocultaCalendarios();
					$(this).parent().find('.calendario-absoluto').slideDown(delay_calendario);
					return false;
				}
			);
			$('.buscar .txt-form, ul.ul-reservar li input.txt-form').focus(
				function() {
					ocultaCalendarios();
					$(this).parent().find('.calendario-absoluto').slideDown(delay_calendario);
					return false;
				}	  
			);
			$('a.cerrar-cal').click(
				function() {
					$(this).parent().slideUp(delay_calendario);
					return false;
				}
			);
			/* slideshow */
			/* setup */
			var delay_ss = 5000;
			function setupInicial() {
				$('#prev').attr('href', $('ul.navegador li:last').prev().children('a').attr('href'));
				$('#next').attr('href', $('ul.navegador li:first').next().next().children('a').attr('href'));
				$('ul.navegador li:first').next().addClass('activo');
				cargaImg('#foto', $('ul.navegador li:first').next().children('a').attr('href'));
			}
			setupInicial();
			/* funcionamiento */
			$('ul.navegador li.normal a').click(
				function() {
					$('ul.navegador li.activo').removeClass('activo');
					$('#prev').attr('href', $(this).parent().prev().children('a').attr('href'));
					$('#next').attr('href', $(this).parent().next().children('a').attr('href'));
					 $(this).parent().addClass('activo');
					cargaImg('#foto', $(this).attr('href'));
					clearInterval(intervalo);
					return false;
				}
			);
			function imagenSiguiente() {
				var siguiente_li = $('ul.navegador li.activo').next('li');
				$('ul.navegador li.activo').removeClass('activo');
				if(siguiente_li.children('a').attr('id') == 'next') {
					setupInicial();
				}
				else {
					siguiente_li.addClass('activo');
					cargaImg('#foto', siguiente_li.children('a').attr('href'));
				}
			}
			$('ul.navegador li a#next').click(
				function() {
					imagenSiguiente();
					clearInterval(intervalo);
					return false;
				}
			);
			$('ul.navegador li a#prev').click(
				function() {
					var anterior_li = $('ul.navegador li.activo').prev('li');
					$('ul.navegador li.activo').removeClass('activo');
					if(anterior_li.children('a').attr('id') == 'prev') {
						$('#next').attr('href', $('ul.navegador li:last').prev().children('a').attr('href'));
						$('#prev').attr('href', $('ul.navegador li:first').next().next().children('a').attr('href'));
						$('ul.navegador li:last').prev().addClass('activo');
						cargaImg('#foto', $('ul.navegador li:last').prev().children('a').attr('href'));
					}
					else {
						anterior_li.addClass('activo');
						cargaImg('#foto', anterior_li.children('a').attr('href'));
					}
					clearInterval(intervalo);
					return false;
				}
			);
			var intervalo;
			function sigaElBaile() {
				intervalo = setInterval(imagenSiguiente, delay_ss);
			}
			sigaElBaile();
			/* paginador */
			var ancho_up = ($('.ultra-paginator').find('li').length - 2) * 23 + 24;
			$('.ultra-paginator').css('width', ancho_up + 'px');
			/* scrollbars */
			$('#textolandia').jScrollPane({showArrows:true});
			/*$('#mas_opciones').hide('fast');*/
			// acciones para mostrar  en el cuadro de busqueda más opciones 
			/*$('#fancy').fancybox({
				"titleShow"		: true,
				"titlePosition" : "over",
				"centerOnScroll " : true,
				"showCloseButton" : false,
				"overlayShow" 	: true,
				"overlayOpacity": 0,
				"transitionIn"	: "no",
				"transitionOut"	: "no",
				"orig"			: $("#fancy")
				
			});*/
			/*$('#masopt_ok').click(function(){
				parent.$.fancybox.close();
			});*/
			$('#btn_mas_opciones').click(
					function(){
						$(this).hide('normal');
						var opciones = 	$(this).parent().parent().find('#mas_opciones');
						if(opciones.attr('id')!="mas_opciones")
							var opciones = 	$(this).parent().parent().find('#mas_opciones1');
						opciones.show('normal');
						$(this).parent().parent().find('#btn_menos_opciones').show('normal');
						
						
					}
				);
			// para mostrar menos acciones (destilde los items si es q estan tildados)
			$('#btn_menos_opciones').click(
					function(){
						$(this).parent().parent().find('#btn_mas_opciones').show('normal');
						var opciones = 	$(this).parent().parent().find('#mas_opciones');
						if(opciones.attr('id')!="mas_opciones")
							var opciones = 	$(this).parent().parent().find('#mas_opciones1');
						// quito los check
						opciones.find('#item16').removeAttr("checked");
						opciones.find('#item5').removeAttr("checked");
						opciones.find('#item29').removeAttr("checked");
						opciones.find('#item44').removeAttr("checked");
						// oculto
						opciones.hide('normal');
						$(this).hide('normal');
					}
				);
			/*****/
			$('#reserva_codigo_promocion').keyup(
					function(){
						
						if(this.value!=""){
							
							$('#recalcular').show();
						}else{
							$('#recalcular').hide();
						}
						
					}
			);
            getNoches();
		}
	);

    function getNoches(){
        var dia1=parseDate($("#cal-1").parent().children('[name*=desde]').val());
		var dia2=parseDate($("#cal-2").parent().children('[name*=hasta]').val());
        if($("#cal-1").val()==$("#cal-2").val()){
            dia2=parseDate($("[name*=hasta]").val());
        }

		var noches=GetDaysBetweenDates(dia1, dia2);
		$("#cant_noches").text(noches);
		$("#cant_noches").parent().show();
    }
	/*Funciones para videos de youtube. Una parte esta en ver_apartamento.php y en ver_hotel.php ya que
	 * se necesita para poder enviar el ID del video en forma dinamica
	 * */
	
    
    // The "main method" of this sample. Called when someone clicks "Run".
    function loadPlayer() {
      // Lets Flash from another domain call JavaScript
      var params = { 
              allowScriptAccess: "always",
              wmode: "transparent"
                  };
      // The element id of the Flash embed
      var atts = { 
              id: "ytPlayer",
              wmode: "transparent"
           };
      // All of the magic handled by SWFObject (http://code.google.com/p/swfobject/)
      swfobject.embedSWF("http://www.youtube.com/apiplayer?" +
                         "&enablejsapi=1&playerapiid=player1", 
                         "videoDiv", "550", "350", "8", null, null, params, atts);
    }
    function _run() {
      loadPlayer();
    }
    /*
     * Chromeless player has no controls.
     */
    
    // This function is called when an error is thrown by the player
    function onPlayerError(errorCode) {
      alert("An error occured of type:" + errorCode);
    }
    
    function playVideo() {
      if (ytplayer) {
        ytplayer.playVideo();
      }
    }
    
    function pauseVideo() {
      if (ytplayer) {
        ytplayer.pauseVideo();
      }
    }
    
    function muteVideo() {
      if(ytplayer) {
          $('#sonido').attr('src', 'img/video-sound-mute.png');
          $("a[href^='javascript:muteVideo();']").attr('href', 'javascript:unMuteVideo();');
        ytplayer.mute();
      }
    }
    
    function unMuteVideo() {
      if(ytplayer) {
          $('#sonido').attr('src', 'img/video-sound.png');
          $("a[href^='javascript:unMuteVideo();']").attr('href', 'javascript:muteVideo();');
        ytplayer.unMute();
      }
    }
    
    /*FIN SCRIPTS PARA YOUTUBE*/
	
	
	
	/** INI :: Funciones para tachar el calendario **/
	function getDias(anio,mes, sCalendarId) {
		$.ajax({	
    		url: 'getDias.php?mes='+mes+'&anio='+anio+'&id_apartamento='+id_apartamento(),
    		type: 'GET',
    		success: function(dias){
	 			marcarCalendario(dias, sCalendarId);
    		}
		});
	}

	function marcarCalendario(sDiasMes, sCalendarId) {
		aDiasMes = sDiasMes.split(",");
		var ant=-2;
		if (sDiasMes!="") {
			$(sCalendarId + ' tbody tr td a').each(
				function(i){
					if (JS_inArray($(this).html(), aDiasMes)) {
						$(this).addClass('dia-tachado');
// si el calendario no es el num 4, al clickear en fecha ocupada no debo hacer nada
						if($(this).parent().parent().parent().parent().parent().parent().attr("id")!="cal-4"){
							$(this).click(function(){return false});
							$(this).dblclick(function(){return false});
						}else{
							// si el calendario es el numero 4 las fechas tachadas son consecutivas, debo retornar false					
							if((ant+1)==i){
								$(this).click(function(){return false});
								$(this).dblclick(function(){return false});
							}
						}
						ant=i;
					}
				}
			);
		}
	}
	
	function id_apartamento()
	{
		return idapartamento;
	}
	/** END :: Funciones para tachar el calendario **/

	/** INI :: Funciones útiles **/
		function JS_isset(v){return ((typeof(v)=='undefined' || v.length==0) ? false : true);}
		function JS_inArray(mValue, aDatos){ for(var iIndex in aDatos) if (aDatos[iIndex] == mValue) return true; return false;}
	/** END :: Funciones útiles **/

function popitup(url) {
		newwindow=window.open(url,'print','height=800,width=600');
		if (window.focus) {newwindow.focus()}
		return false;
	}

	function redondear(cantidad, decimales) {
		var cantidad = parseFloat(cantidad);
		var decimales = parseFloat(decimales);
		decimales = (!decimales ? 2 : decimales);
		decimales = Math.round(cantidad * Math.pow(10, decimales)) / Math.pow(10, decimales);
		return decimales;
	} 
	
	function mostrarmasopciones(obj)
	{
		var	estilo = obj.style;
		estilo.height='0px';
		estilo.overflow='hidden';
		estilo.visibility='hidden';
		estilo = document.getElementById('mas_opciones').style;
		estilo.height='auto';
		estilo.overflow='auto';
		estilo.visibility='visible';
	}
	
	function parseDate(str) {
	   if(str){
	    var date = str.split('-'); 
	    return new Date(date[2], date[1] - 1, date[0]);
        } 
	}

	function GetDaysBetweenDates(date1, date2) { 
        
	    return (date2 - date1) / (1000 * 60 * 60 * 24); 
	}

	
// ]]>
