﻿function CheckForm() {

    if ($("#privacy:checked").size() == 0) {
        DoAlert(Localize('ConsensoPrivacy'));
        return;
    }

    var newsletter = $("#newsletter:checked").size() == 1;

    var arrival = $("#arrival-b").val();
    var departure = $("#departure-b").val();

    if (arrival == "" || departure == "") {
        DoAlert(Localize('InserireDate'), "#date");
        return;
    }

    var rooms = parseInt($("#rooms").val());

    if (isNaN(rooms) || rooms < 1) {
        DoAlert(Localize('ScegliereCamere'));
        return;
    }

    var request = new String();
    for (i = 0; i < rooms; i++) {
        var $room = $("#camere .camera").eq(i);
        var adulti = parseInt($room.find(".adulti select").val());
        var bambini = parseInt($room.find(".bambini select").val());

        if (adulti + bambini == 0) {
            DoAlert(Localize('SelezionareAdultiBambini') + " " + (i + 1), "#camera" + i);
            return;
        }
        //request = request.concat(Localize('TipoCamera') + " " + (i + 1) + "\n");
        request = request.concat(Localize('Adulti') + " : " + adulti + "\n");
        request = request.concat(Localize('Bambini') + " : " + bambini + "\n");
        if (bambini > 0) {
            for (b = 0; b < bambini; b++) {
                request = request.concat(Localize("EtaBambino") + " " + (b + 1) + " : " + $room.find(".eta-bambini select").eq(b).val() + "\n");
            }
        }

        request = request.concat(Localize('TipoCamera') + " : " + $room.find(".tipo-camera select").val() + "\n");
        request = request.concat(Localize('Trattamento') + " : " + $room.find(".trattamento select").val() + "\n");
        request = request.concat("---------------\n\n");
    }

    var name = $.trim($("#name").val());
    var surname = $.trim($("#surname").val());
    if (name == "" || surname == "") {
        DoAlert(Localize('InserireNomeCognome'));
        return;
    }

    var email = $.trim($(".dati .mail input").val());
    if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
        DoAlert(Localize('InserireEmail'), "#dati");
        return;
    }

    var activities = new Array();
    var $act_checkboxes = $(".scegli-attivita input[type=checkbox]:checked");
    for (i = 0; i < $act_checkboxes.size(); i++)
        activities.push($act_checkboxes.eq(i).val());

    var contact = new Array();
    contact.push(name + " " + surname);
    contact.push("Indirizzo: " + $.trim($("#address").val()));
    contact.push("CAP: " + $.trim($("#zip").val()));
    contact.push("Città: " + $.trim($("#town").val()));
    contact.push("Nazione: " + $.trim($(".cont.dati .nazione select").val()));
    contact.push("Telefono: " + $.trim($("#phone").val()));
    contact.push("E-mail: " + $.trim($("#email").val()));

    var userdata = {};

    userdata.arrival = arrival;
    userdata.departure = departure;
    userdata.rooms = rooms;
    userdata.request = request;
    userdata.info = $(".info textarea").val();
    userdata.contact = contact.join("\n");
    userdata.name = name;
    userdata.surname = surname;
    userdata.activities = activities;
    userdata.newsletter = newsletter;
    userdata.address = $.trim($("#address").val());
    userdata.town = $.trim($("#town").val());
    userdata.zip = $.trim($("#zip").val());
    userdata.country = $.trim($(".cont.dati .nazione select").val());
    userdata.phone = $.trim($("#phone").val());
    userdata.email = email;

    var loading = $("<div title='" + Localize("Wait") + "'>" + Localize("Sending") + "</div>").dialog({ modal: true });

    var DTO = { 'userdata': userdata };
    $.ajax({
        "url": "/ajax/Disponibilita.asmx/AddAvailability",
        "data": JSON.stringify(DTO),
        "type": "POST",
        "contentType": "application/json; charset=utf-8",
        "dataType": "json",
        "success": function(res) {
            loading.dialog('close');
            DoDialog("Conferma", Localize("RichiestaInviata"));
            setTimeout(function() { location.href = "/"; }, 3000);
        },
        "error": function() {
            loading.dialog('close');
            DoAlert(Localize("VerificatoErrore"));
        }
    });
}

function goBooking() {
    if($("#arrival, #departure").size() > 0) {
            var arrival = $("#arrival").val().replace(/\//g, "-");
            var departure = $("#departure").val().replace(/\//g, "-");
            location.href = "/Booking.aspx?a=" + arrival + "&d=" + departure + "#booking";
        }
        else
            location.href = "/Booking.aspx#booking";
    
}

function DoDialog(title, message, link) {
    var $div = $(document.createElement("div"));
    $div.attr("title", title);
    $div.html(message);
    $div.dialog({
        modal: true,
        buttons: {
            Ok: function() {
                $(this).dialog('close');
                if (link != "" && link != undefined)
                    location.href = link;
            }
        }
    });
}

function DoAlert(message, link) {
    DoDialog(Localize("Attenzione"), message, link);
}
var gup = function(name) {
    var results = (new RegExp("[\\?&]" + name + "=([^&#]*)")).exec(window.location.href);
    if (results == null) { return "" }
    else { return results[1] }
};

function SubscribeNewsletter() {
    var email = $.trim($("#subscribe-email").val());
    if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
        DoAlert(Localize('InserireEmail'), "#dati");
        return;
    }

    $.ajax({
        "url": "/ajax/Disponibilita.asmx/SubscribeNewsletter",
        "data": "{'email':'" + email + "'}",
        "type": "POST",
        "contentType": "application/json; charset=utf-8",
        "dataType": "json",
        "success": function(res) {
            if (res.d == "-2")
                DoDialog("Conferma", "Localize('InserireEmail')");
            else
                DoDialog("Conferma", Localize('ConfermaNewsletter'));
        },
        "error": function() {
            DoAlert(Localize('VerificatoErrore'));
        }
    });
}

function GetBigOne(img) {
    var path = img.split("/");
    var _src = new Array();
    for (i = 0; i < path.length; i++) {
        if (path[i] != "" && path[i] != "Media" && path[i] != "GalleryThumb") {
            _src.push(path[i]);
        }
    }
    return _src.join("/");
}

var currentBigOne = 0;
function BigSlide() {
    var $big = $("#gallery .big-photo");

    if ($big.children().size() > 0) {
        $big.children(".old").fadeOut(function() { $(this).remove(); });
        $big.children(".new").fadeIn().addClass("old");
    }
    else {
        var first = GetBigOne($("#gallery .mask ul li").eq(currentBigOne).find("img").attr("src"));
        var $img1 = $(document.createElement("img")).addClass("old");
        $img1.attr("src", "/Media/Gallery/" + first).addClass("entering");
        $big.append($img1);
        $img1.fadeIn();
    }
    $("#gallery .main .caption").html($("#gallery .mask ul li span").eq(currentBigOne).html());

    /* preload next img */
    currentBigOne++;
    if (currentBigOne == $("#gallery .mask ul li").size())
        currentBigOne = 0;
    var second = GetBigOne($("#gallery .mask ul li").eq(currentBigOne).find("img").attr("src"));
    var $img2 = $(document.createElement("img"));
    $img2.attr("src", "/Media/Gallery/" + second).addClass("new");
    $big.append($img2);
    setTimeout(BigSlide, 5000);
}
function HandleGallery() {
    if ($("#gallery").data("status") == "opened" || $("#gallery").data("status") == undefined) {
        $("div.flash").addClass("closed");
        $(".gallery-handle a").removeClass("chiudi");
        $(".gallery-handle a").addClass("apri");
        $("#gallery .main").hide();
        $("#gallery").addClass("closed");
        $("#gallery").data("status", "closed");
        $("#thumb-control").hide().siblings().show();
        $("#thumb-control").find("img").attr("src", "/img/it_IT/inverno/common/chiudi.png");
        $.cookie("gallery", "closed");
    } else {
        $(".gallery-handle a").removeClass("apri");
        $(".gallery-handle a").addClass("chiudi");
        $("div.flash").removeClass("closed");
        $("#gallery").removeClass("closed");
        $("#gallery .main").show();
        $("#gallery").data("status", "opened");
        $("#thumb-control").show();
        $.cookie("gallery", "opened");
    }
}
function changeImage(e) {
    var src = $(e).find("img").attr("src").split("/");
    var _src = new Array();
    for (i = 0; i < src.length; i++)
        if (src[i] != "" && src[i] != "Media" && src[i] != "Mini")
        _src.push(src[i]);
    var imgUrl = _src.join("/");
    $(".immagine-principale img").attr("src", "/Media/ContenutoDettaglio/" + imgUrl);
    $(".immagine-principale a").attr("href", "/Media/Full/" + imgUrl);
}

var galleryScroll;

var Url = {

    // public method for url encoding
    encode: function(string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode: function(string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode: function(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function(utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

$(document).ready(function() {
    BigSlide();
    galleryScroll = $("#gallery .mask").scrollable({
        clickable: false,
        size: 4
    }).autoscroll({ interval: 5000 });

    setTimeout(function() {
        $("#gallery .main .text").fadeOut();
    }, 5000);

    $("#gallery .mask ul li a").live("click", function() {

        if ($("#gallery").data("status") == "closed") {
            HandleGallery();
        }

        var $big = $("#gallery .big-photo");
        var path = GetBigOne($(this).children("img").attr("src"));

        if ("/Media/Gallery/" + path == $big.children("img").attr("src"))
            return;

        var $img = $(document.createElement("img"));
        $img.attr("src", "/Media/Gallery/" + path).addClass("new");
        $big.children("img").fadeOut("slow", function() { $(this).remove(); });
        $big.append($img);
        $img.fadeIn("slow");
    });

    $("#thumb-control").live("click", function() {

        if ($(this).data("status") == "opened" || $(this).data("status") == undefined) {
            $("#gallery .mask, #gallery .next, #gallery .prev").hide();
            $(this).siblings().hide();
            $(this).removeClass("chiudi");
            $(this).addClass("apri");
            $(this).trigger("blur");
            $(this).data("status", "closed");
            $("#gallery-controller").addClass("closed");
        }
        else {
            $("#gallery-controller").removeClass("closed");
            $(this).trigger("blur");
            $(this).siblings().show();
            $(this).removeClass("apri");
            $(this).addClass("chiudi");
            $(this).data("status", "opened");
            $("#gallery .mask, #gallery .next, #gallery .prev").fadeIn(1000);
        }
    });

    if ($.cookie("gallery") == "closed")
        HandleGallery();

    $("ul.flags li a").click(function() {
        location.href = '/switchLocale.ashx?l=' + $(this).attr("rel") + '&p=' + Url.encode(location.href);
    });
    $(".seasons li a").click(function() {
        var season = $(this).hasClass("winter") ? "winter" : "summer";
        if (season != $.cookie("season"))
            location.href = '/switchSeason.ashx?l=' + season + '&p=' + Url.encode(location.href);
    });
});

function ShowCommentPanel() {
    var dialog = $("#comment-panel").clone();
    dialog.dialog({
        modal: true,
        buttons: {
            "Invia": function() {
                var name = $.trim($("input.guestbook-name", this).val());
                if (name.length == 0) {
                    DoAlert(Localize('InserireNome'));
                    return;
                }
                var email = $.trim($("input.guestbook-email", this).val());
                if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
                    DoAlert(Localize('InserireEmail'));
                    return;
                }
                var comment = $.trim($("textarea.guestbook-comment", this).val());
                if (comment.length == 0) {
                    DoAlert(Localize('InserireMessaggio'));
                    return;
                }
                var DTO = { "data": {
                    "email": email,
                    "name": name,
                    "comment": comment,
                    "newsletter": $(".guestbook-nl:checked").size() > 0
                }
                };
                var loading = $("<div title='" + Localize("Wait") + "'>" + Localize("Sending") + "</div>").dialog({ modal: true });
                $.ajax({
                    "url": "/ajax/Disponibilita.asmx/LeaveComment",
                    "data": JSON.stringify(DTO),
                    "type": "POST",
                    "contentType": "application/json; charset=utf-8",
                    "dataType": "json",
                    "success": function(res) {
                        loading.dialog('close');
                        dialog.dialog('close');
                        DoDialog("Conferma", Localize('ConfermaMessaggio'));
                    },
                    "error": function() {
                        loading.dialog('close');
                        dialog.dialog('close');
                        DoAlert(Localize('VerificatoErrore'));
                    }
                });
            },
            "Annulla": function() { $(this).dialog('close'); }
        },
        width: 400,
        height: 300
    });
}

function GalleryLogin() {
    var pwd = $(".gallery-password").val();
    $.post("/ajax/gallery-login.ashx", { p: pwd }, function(r) {
        if (r == "1") {
            location.href = "/PhotoGallery.aspx";
        }
        else {
            $("<div title='Error'>Password non corretta</div>").dialog({ modal: true });
        }
    });
}