﻿Date.prototype.goto = function(n) {
    this.setTime(this.getTime() + n * 86400000);
    return this;
};

Date.prototype.DateDiff = function(endDate) {
    var ONE_DAY = 1000 * 60 * 60 * 24;
    var date1_ms = this.getTime();
    var date2_ms = endDate.getTime();
    var difference_ms = Math.abs(date2_ms - date1_ms);
    return Math.round(difference_ms / ONE_DAY);
};

$(function() {

	var entrado=0;

	$("div.enterleave").mouseenter(function() {
		entrado = 1;
	}).mouseleave(function() {
		entrado = 0;
	});	
	
	$(".habitacionesdiferentestipos").click(function(evento){
		evento.preventDefault();
	});
	
	/* Si entra en el botón de habitaciones que aparezca */
	$(".habitacionesdiferentestipos").hover(
		function(){
			//El mousein
			$(".desplegabletiposhabitaciones").slideDown();
		},
		function(){
			//El mouseout
		}
	);
	
	/* Si sale del menú entero que se vaya */
	$(".menudeopcionesizquierda").hover(
		function(){
			//El mousein
		},
		function(){
			//El mouseout, pero solo si el ratón no está en el desplegable
			if(entrado==0){
				$(".desplegabletiposhabitaciones").slideUp();
			}
		}
	);	
	
	/* Si sale del desplegable que también se salga */
	$(".desplegabletiposhabitaciones").hover(
		function(){
			//El mousein
		},
		function(){
			//El mouseout
			$(".desplegabletiposhabitaciones").slideUp();
		}
	);
	
	$(".enviar").click(function(evento){
		evento.preventDefault();
		if($("input[name='nombre']").val().length==0 || $("input[name='telefono']").val().length == 0 || $("input[name='mail']").val().length == 0 || $(".observaciones").val().length == 0){
			devolverVacio(lang);
		}else{
			$("input[name='accion']").attr("value","n");
			$("#formularioacceso").submit();
		}
	});
	
	$(".resetear").click(function(evento){
		evento.preventDefault();
		document.forms["formularioacceso"].reset();
	});
	
	$("#etiSPA").tabs();
	$(".reservar").click(function(evento){
		evento.preventDefault();
		$("#formreserva").submit();
	});
	$('#galeria').cycle({
		fx: 'fade',
		timeout: 5000,
		speed: 1750
	});
	
	$.simpleWeather({
		zipcode: 'SPXX0165',
		unit: 'c',
		success: function(weather) {
			$("#weather").append("<p>"+weather.low+"&deg; "+weather.units.temp+" - "+weather.high+"&deg; "+weather.units.temp+"</p><br />");
			$("#weather").append('<p><img width="60" height="40" src="'+weather.image+'"></p>');
		},
		error: function(error) {
			$("#weather").html("<p>"+error+"</p>");
		}
	});
	SexyLightbox.initialize({color:'white', dir: '../estilos/sexyimages'});

	$('#fancyClock').tzineClock();
	
	$('.webs').change(function() { document.location = $(this).val(); });
    
	$('input.date').datepicker({
        dateFormat: 'dd/mm/yy',
        firstDay: 1,
        minDate: +1,
		showOn: "button",
		buttonImage: "../img/calendar.png",
		buttonImageOnly: true,
        numberOfMonths: [1, 2],
        onSelect: function(dateText) {
            var newDate = $.datepicker.parseDate('dd/mm/yy', dateText);
            if ($('.date').index(this) == 0) {
                $('.date:last').datepicker('option', 'minDate', newDate.goto(1));
                var checkOut = $('.date:last').datepicker('getDate');
                if (newDate > checkOut)
                    $('.date:last').datepicker('setDate', newDate.goto(1));
            }
            else {
                $('.date:first').datepicker('option', 'maxDate', newDate.goto(-1));
                var checkIn = $('.date:first').datepicker('getDate');
                if (newDate < checkIn)
                    $('.date:first').datepicker('setDate', newDate.goto(-1));
            }

            var newStage = $('.date:first').datepicker('getDate').DateDiff($('.date:last').datepicker('getDate'));
            $('#s').val(newStage);
        }
    });

    $('#datepicker').datepicker('option', $.extend({ showMonthAfterYear: false }, $.datepicker.regional[lang]));


    $('input.date:first').datepicker('setDate', +7);
    $('input.date:last').datepicker('setDate', +12);	
	
	var altura=0;
	$(document).resize(function(){
		var elem = $(this);
		altura= elem.height();
		$("#izquierda").css({'height':altura});
		$("#derecha").css({'height':altura});
	});
	// Actualizamos
	$(document).resize();
    ajaxSubscriptions.init();
	
    $('#panoramaModal').dialog({ autoOpen: false, width: 730, height: 640, modal: true, closeOnEscape: true, title: 'Gran Hotel Bali - Virtual Tour' });
    $('#tourvirtual').click(function(e) {
        e.preventDefault();
        $('#panoramaModal').dialog('open');
    });	
	
});

var ajaxSubscriptions = {
    language: null,
    subscriber: null,
    subscribeMe: null,
    action: null,
    process: function() {
        var ajaxModal = $('#ajaxModal');
            ajaxModal.dialog('open').find('#onLoad').show().siblings('div').hide();
        $.post("/ajax/subscribe.ashx", { language: this.language, subscriber: this.subscriber, mode: this.subscribeMe, action: this.action },
            function(data) {
                ajaxModal.dialog('option', 'buttons', { "Salir": function() { $(this).dialog("close"); } });
                if (data == 'OK')
                    ajaxModal.find('#onSuccess').show().siblings('div').hide();
                else
                    ajaxModal.find('#onError').show().siblings('div').hide();
            });
    },
    processMobile: function() {
        this.subscriber = $('#tbSms').val();
        this.subscribeMe = $('#comprobadorsms #rbAltaIn:checked').length > 0 ? true : false;
        this.action = 'sms';
        this.language = $('#smsLang').val();

        this.process();
    },
    processEmail: function() {
        this.subscriber = $('#tbEmail').val();
        this.subscribeMe = $('#comprobadornewsletters #rbMailIn:checked').length > 0 ? true : false;
        this.action = 'mail';
        this.language = $('#emailLang').val();

        this.process();
    },
    defaultValues: function() {
        $('#suscriptions .subscription-form input.textbox').each(function(i, sender) {
            var ititle = $(this).attr('title');
            $(sender).val(ititle).blur(function() { if ($(this).val() == '') $(this).val(ititle); }).focus(function() { if ($(this).val() == ititle) $(this).val(''); });
        });
    },
    init: function() {
        this.defaultValues();
        $('#ajaxModal').dialog({ autoOpen: false, width: 450, height: 275, modal: true, closeOnEscape: false, title: 'Gran Hotel Bali', resizable: false });
        $('#ajaxModal').bind('dialogopen', function(event, ui) { $('.ui-dialog-titlebar-close').css('display', 'none'); })
                       .bind('dialogclose', function(event, ui) { $('.ui-dialog-titlebar-close').css('display', 'block'); });
        $('.button-submit').click(function(e) {
            if ($(e.target).hasClass('email-submit'))
                ajaxSubscriptions.processEmail();
            else
                ajaxSubscriptions.processMobile();
        });
    }
};

function devolverVacio(lang){
	switch(lang){
		case "es":
			alert("Todos los campos son obligatorios");
		break;		
		case "is":
			alert("Öll svið er skylt");
		break;		
		case "ru":
			alert("Все области обязательны");
		break;		
		case "de":
			alert("Alle Felder sind obligatorisch");
		break;			
		case "en":
			alert("All the fields are obligatory");
		break;		
		case "fr":
			alert("Tous les champs sont obligatoires");
		break;		
		case "it":
			alert("Tutti i campi sono obbligatori");
		break;		
		case "po":
			alert("Todos os campos são obrigatórios");
		break;		
		default:
			alert("Todos los campos son obligatorios");
		break;
	}
}

function MM_openBrWindow(theURL, winName, features) { window.open(theURL, winName, features); } // Inherited from v1.x
