﻿
// Una volta scelto il numero di stanze da prenotare (sender è la select "rooms_number"), aggiunge un "li" per ogni stanza con la scelta
// del numero di adulti e bambini per ciascuna
function PopolateRooms(sender, num_nights, maximum_beds, accomodationID, rooms, numadditionalbeds, nummaxkids) {
    if (sender.selectedIndex > 0) {
        var room_number = sender.value;
        var div = $('rooms');
        var fldst = $$('.s02');
        var nr = 0;
        var ul = $('ul_rooms');
        var num_li = ul.getChildren('li').length - 1;
        if (num_li > room_number) {
            // elimina "li" in eccesso
            for (var i = num_li; i > room_number; i--) {
                var deleting = ul.getLast('li');
                deleting.dispose();
                if (fldst.length > room_number)
                    fldst.getLast().dispose();
               //var deleting =
            }
            UpdateTotalPrice();
        }
        else if (num_li < room_number) {
            // aggiungi "li" necessari
            var html = '';
            for (var i = 0; i<=maximum_beds; i++)
                html += '<option value="' + i + '">' + i + '</option>';
            
            for (var i = num_li+1; i <= room_number; i++) {
                var li = new Element('li', { 'class': 'dett_camera', 'html': '<span>' + lblCamera + ' ' + i + '</span><label>' + lblAdulti + '</label><select id="adulti' + i + '" title="Numero adulti" onChange="PopolateRoomComposition(this,' + num_nights + ',' + i + ',' + accomodationID + ',\'' + rooms + '\', ' + numadditionalbeds + ',' + nummaxkids + ',0)">' + html + '</select><label>' + lblBambini + '</label><select title="Numero bambini" id="bambini' + i + '" onChange="PopolateRoomComposition(this,' + num_nights + ',' + i + ',' + accomodationID + ',\'' + rooms + '\', ' + numadditionalbeds + ',' + nummaxkids + ',0)">' + html + '</select>' });
                li.inject(ul);
            }
        }
    }
}

// Visualizza o nascondi il div del rimessaggio in base al click sul checkbox dedicato
function ShowDivGaraging(sender) {
    var div = sender.getParent().getFirst('div');
    if (div) {
        if (div.getStyle('display') == 'none')
            div.setStyle('display', 'block');
        else
            div.setStyle('display', 'none');
    }
}

// Restituisce il codice HTML di un elemento "li" di un cliente (adulto => type=1 o bambino => type=2)
// num2 serve solo per il colore di sfondo delle righe, accomodationRooms è l'elenco di stanze (#numeroletti|idstanza) della struttura
function WriteGuestLi(num, type, add_li, num2, room, accomodationRooms, numAdditionalBeds, num_nights, totalPeople) {
    var error = '';
    var html = '';
    var id_part = '';
    if (type == 1) {
        if (add_li == 1) {
            html += '<li class="adult"';
            if (num2 % 2 == 0)
                html += ' style="background-color:#F5F5F5"';
            html += '>';
        }
        html += '<span>' + lblAdulto + ' ' + num + '</span>';
        id_part = room + '_ad' + num;
    }
    else {
        if (add_li == 1) {
            html += '<li class="kid"';
            if (num2 % 2 == 0)
                html += ' style="background-color:#F5F5F5"';
            html += '>';

        }
        id_part = room + '_bb' + num;
        html += '<span>' + lblBambino + ' ' + num + '</span>';
        html += '<input id="culla' + id_part + '" name="culla' + id_part + '" title="' + lblCulla + '" type="checkbox" onclick="CalculateRoomCost(' + room + ',\'' + accomodationRooms + '\',' + numAdditionalBeds + ')" /><label>' + lblCulla + '</label>';
        html += '<label>' + lblEta + '</label><select id="eta' + id_part + '" name="eta' + id_part + '" class="eta" title="' + lblEta + '" onchange="CalculateRoomCost(' + room + ',\'' + accomodationRooms + '\',' + numAdditionalBeds + ')">';
        html += '<option>' + lblScegli + '</option>';
        for (var y = 1; y < 15; y++)
            html += '<option value="' + y + '">' + y + '</option>';
        html += '</select>';
    }
    html += '<input title="' + lblAffitto + '" id="affitto' + id_part + '" name="affitto' + id_part + '" value="1" type="checkbox" onclick="CheckAffittoCorso(this,\'corso' + id_part + '\'); CalculateRoomCost(' + room + ',\'' + accomodationRooms + '\',' + numAdditionalBeds + ')" /><label>' + lblAffitto + '</label>';
    html += '<input title="' + lblCorso + '" id="corso' + id_part + '" name="corso' + id_part + '" value="1" type="checkbox" onclick="CheckAffittoCorso(this,\'affitto' + id_part + '\'); CalculateRoomCost(' + room + ',\'' + accomodationRooms + '\',' + numAdditionalBeds + ')" /><label>' + lblCorso + '</label>';
    html += '<select id="giornicorso' + id_part + '" name="giornicorso' + id_part + '" title="' + lblGiorniCorso + '" onchange="CalculateRoomCost(' + room + ',\'' + accomodationRooms + '\',' + numAdditionalBeds + ')">';
    html += '<option>' + lblGiorniCorso + '</option>';
    for (var y = 1; y <= num_nights+1; y++)
        html += '<option value="' + y + '">' + y + '</option>';
    html += '</select>';
    html += '<input id="rimessaggio' + id_part + '" name="rimessaggio' + id_part + '" title="' + lblRimessaggio + '" type="checkbox" value="1" onclick="ShowDivGaraging(this);  CalculateRoomCost(' + room + ',\'' + accomodationRooms + '\',' + numAdditionalBeds + ')" /><label>' + lblRimessaggio + '</label>';

    MinBeds = 100;
    MaxBeds = 0;
    test = accomodationRooms.split('#');
    for (var x = 0; x < test.length; x++)
        if (test[x] != "") {
            test2 = test[x].split('|');
            if (test2[0] < MinBeds)
                MinBeds = test2[0];
            if (test2[0] > MaxBeds)
                MaxBeds = test2[0];
        }

    if (type == 1)
        if (num2 > MaxBeds)
            html += '<input id="addbed' + id_part + '" name="addbed' + id_part + '" title="' + lblLettoAggiunto + '" value="1" type="checkbox" checked="checked" onclick="this.checked=!this.checked;" /><label>' + lblLettoAggiunto + '</label>';
        else
            if (num2 > MinBeds)
                html += '<input id="addbed' + id_part + '" name="addbed' + id_part + '" title="' + lblLettoAggiunto + '" value="1" type="checkbox" onclick="CalculateRoomCost(' + room + ',\'' + accomodationRooms + '\',' + numAdditionalBeds + ')" /><label>' + lblLettoAggiunto + '</label>';

            if (type == 1)
                if (num < MinBeds)
                    if (totalPeople == 1)
                        html += '<input id="suppsingola' + id_part + '" type="checkbox" value="1" name="suppsingola' + id_part + '" title="' + lblSupplementoSingola + '" checked="checked" onclick="CalculateRoomCost(' + room + ',\'' + accomodationRooms + '\',' + numAdditionalBeds + ')"><label>' + lblSupplementoSingola + '</label>';

    html += '<div style="display:none">';
    html += '<select id="giornirimessa' + id_part + '" name="giornirimessa' + id_part + '" value="1" title="' + lblGiorniRimessaggio + '" onchange="CalculateRoomCost(' + room + ',\'' + accomodationRooms + '\',' + numAdditionalBeds + ')">';
    html += '<option>' + lblGiorniRimessaggio + '</option>';
    for (var y = 1; y <= num_nights+1; y++)
        html += '<option value="' + y + '">' + y + '</option>';
    html += '</select><select id="numtavole' + id_part + '" name="numtavole' + id_part + '" title="' + lblTavole + '" onchange="CalculateRoomCost(' + room + ',\'' + accomodationRooms + '\',' + numAdditionalBeds + ')">';
    html += '<option>' + lblTavole + '</option>';
    for (var y = 1; y < 32; y++)
        html += '<option value="' + y + '">' + y + '</option>';
    html += '</select><select id="numvele' + id_part + '" name="numvele' + id_part + '" title="' + lblVele + '" onchange="CalculateRoomCost(' + room + ',\'' + accomodationRooms + '\',' + numAdditionalBeds + ')">';
    html += '<option>' + lblVele + '</option>';
    for (var y = 1; y < 32; y++)
        html += '<option value="' + y + '">' + y + '</option>';
    html += '</select></div>';
    if (add_li == 1)
        html += '</li>';

    return html;
}

// Controlla che solo una tra le due caselle checkbox "affitto/corso" siano spuntate
function CheckAffittoCorso(sender, other) {
    if ($(sender).checked)
        $(other).checked = false;
}

// Aggiorna il colore di sfondo dei "li" dei bambini
function UpdateBackgroundColor(room_number, adults) {
    var fieldset = $('fieldset' + room_number);
    if (fieldset) {
        var ul = fieldset.getFirst('ul');
        var i = adults;
        ul.getElements('.kid').each(function(el) {
            i++;
            if (i % 2)
                el.setStyle('background-color', '#FFFFFF');
            else
                el.setStyle('background-color', '#F5F5F5');
        });
    }
}

// Una volta scelti il numero di adulti o bambini (adulti => type=1, bambini => type=2), aggiunge o toglie fieldsets
// con i dettagli dei componenti della stanza. Sender è la select sulla quale è stato effettuata una scelta e "room" è il numero di stanza
function PopolateRoomComposition(sender, num_nights, room, accomodationID, rooms, numAdditionalBeds, nummaxkids, roomID) {
    var e = $(sender).getParent();
    var adulti = e.getChildren('select')[0].value;
    var bambini = e.getChildren('select')[1].value;
    var fieldset = $('fieldset' + room);
    var totalPeople = Number(adulti) + Number(bambini);

    if (roomID == 0) {
        // Controlla se ci sono più stanze/appartamenti con un numero compatibile di posti, nel qual caso deve mostrare la scelta della stanza
        var arrayRooms = rooms.split('#');
        var somma = Number(adulti) + Number(bambini);
        var found = 0;
        var foundRooms = '<option value="">' + lblScegli + '</option>';
        for (var x = 0; x < arrayRooms.length; x++)
            if (arrayRooms[x] != "") {
            var arrayRooms2 = arrayRooms[x].split('|');
            if (arrayRooms2[0] == somma) {
                found++;
                foundRooms += '<option value="' + arrayRooms2[1] + '">' + arrayRooms2[2] + '</option>';
            }
        }

        if (found > 1) {
            if (fieldset)
                fieldset.dispose();
            if (!$('chooseroomID_' + room)) {
                var selectScelta = new Element('select', {
                    'id': 'chooseroomID_' + room,
                    'html': foundRooms,
                    'title': lblScegliCamera,
                    'events': {
                        'change': function() {
                            PopolateRoomComposition(this, num_nights, room, accomodationID, rooms, numAdditionalBeds, nummaxkids, this.value);
                        }
                    }
                });
                var labelScelta = new Element('label', { 'html': lblScegliCamera, 'id': 'sceglicamera' + room });
                labelScelta.inject(e);
                selectScelta.inject(e);
            }
            else {
                $('chooseroomID_' + room).set('html', foundRooms);
            }
            return;
        }
        else {
            if ($('chooseroomID_' + room)) {
                $('sceglicamera' + room).dispose();
                $('chooseroomID_' + room).dispose();
            }
            var inputroomID = $('roomID_' + room);
            if (inputroomID)
                inputroomID.value = roomID;
        }

        var MinBeds = 100;
        var MaxBeds = 0;
        var test = rooms.split('#');
        for (var x = 0; x < test.length; x++)
            if (test[x] != "") {
            var test2 = test[x].split('|');
            if (test2[0] < MinBeds)
                MinBeds = test2[0];
            if (test2[0] > MaxBeds)
                MaxBeds = test2[0];
        }
    }
    else {
        // E' già stato dato l'ID della stanza
        var inputroomID = $('roomID_' + room);
        if (inputroomID)
            inputroomID.value = roomID;
    }

    if (Number(adulti) + Number(bambini) > Number(MaxBeds) + Number(numAdditionalBeds) + Number(nummaxkids)) {
        if ($('toohigh'+room)) {
        }
        else
            if (fieldset) {
                var ul = fieldset.getFirst('ul');
                var new_li = new Element('li', { 'id': 'toohigh' + room, 'html': lblNumeroTroppoElevato, 'class': 'adult' });
                new_li.inject(ul.getLast('li'), 'before');

                if ($('totale' + room)) {
                    $('totale' + room).value = ' - - ';
                    UpdateTotalPrice();
                }

                return;
            }
            else {
                var last_fieldset = $('form_booking').getLast('fieldset');
                var html = '<legend>' + lblDettagliCamera + ' ' + room + '</legend><ul>';
                html += '<li>' + lblNumeroTroppoElevato + '</li>';
                html += '<li class="totalecamera" style="text-align:right">';
                html += '<label>' + lblTotaleCamera + ' ' + room + '</label>';
                html += '<input id="totale' + room + '" name="totale' + room + '" title="' + lblTotaleCamera + ' ' + room + '" type="text" />';
                html += '<input id="ad_' + room + '" name="ad_' + room + '" type="hidden" value="0" />';
                html += '<input id="bb_' + room + '" name="bb_' + room + '" type="hidden" value="0" />';
                html += '<input id="roomID_' + room + '" name="roomID_' + room + '" type="hidden" value="' + roomID + '" />';
                html += '<div id="extraroom' + room + '" style="color:#DD0000;"></div>';
                html += '</li>';
                html += '</ul>';
                var new_fieldset = new Element('fieldset', { 'id': 'fieldset' + room, 'class': 's02', 'html': html });
                new_fieldset.inject(last_fieldset, 'before');
                return;
            }
    }
    
    if ($('toohigh'+room)) {
        $('toohigh'+room).dispose();
    }

    // In "rooms" ho la lista delle stanze con i rispettivi ID separate da # e | (es. #1|53#2|122#3|35#4|98 dove 
    // il primo numero è il numero letti e il secondo l'ID della stanza)
    // Controllare quanti adulti e quanti bambini ci sono, per sapere quanti letti aggiunti servono o come gestire il 
    // discorso scontistica bambini
    if (fieldset) {
        var i = 0;
        var ul = fieldset.getFirst('ul');
        var arraybambini = ul.getElements('.kid');
        var adulti_presenti = ul.getChildren('li').length - 1 - arraybambini.length;

        if (adulti_presenti > adulti) {
            // ELIMINA elementi "li" adulti
            for (var i = adulti_presenti; i > adulti; i--) {
                var li = ul.getLast('.adult');
                li.dispose();
            }
            UpdateBackgroundColor(room, adulti);
        }
        else if (adulti > adulti_presenti) {
            // AGGIUNGI elementi "li" adulti
            for (var i = adulti_presenti + 1; i <= adulti; i++) {
                var html = WriteGuestLi(i, 1, 0, i, room, rooms, numAdditionalBeds, num_nights, totalPeople);
                var new_li = new Element('li', { 'html': html, 'class':'adult' });
                if (i % 2 == 0)
                    new_li.setStyle('background-color','#F5F5F5');
                if (arraybambini.length > 0)
                    new_li.inject(arraybambini[0], 'before');
                else
                    new_li.inject(ul.getLast('li'), 'before');
            }
            UpdateBackgroundColor(room, adulti);
        }
        if (arraybambini.length > bambini) {
            // ELIMINA "bambini" :-)
            for (var i = arraybambini.length; i > bambini; i--) {
                var li = ul.getLast('.kid');
                li.dispose();
            }
        }
        else if (bambini > arraybambini.length)
        {
            // AGGIUNGI elementi "li" bambini
            for (var i = arraybambini.length + 1; i <= bambini; i++) {
                var html = WriteGuestLi(i, 2, 0, Number(i) + Number(adulti), room, rooms, numAdditionalBeds, num_nights, totalPeople);
                var new_li = new Element('li', { 'class': 'kid', 'html': html });
                if ((Number(i) + Number(adulti)) % 2 == 0)
                    new_li.setStyle('background-color', '#F5F5F5');
                new_li.inject(ul.getLast('li'), 'before');
            }
        }
        $('ad_' + room).value = adulti;
        $('bb_' + room).value = bambini;
    }
    else {
        var last_fieldset = $('form_booking').getLast('fieldset');
        var html = '<legend>' + lblDettagliCamera + ' ' + room + '</legend><ul>';
        for (var i = 1; i <= adulti; i++) {
            html += WriteGuestLi(i, 1, 1, i, room, rooms, numAdditionalBeds, num_nights, totalPeople);
        }
        for (var i = 1; i <= bambini; i++) {
            html += WriteGuestLi(i, 2, 1, Number(i) + Number(adulti), room, rooms, numAdditionalBeds, num_nights, totalPeople);
        }
        html += '<li class="totalecamera" style="text-align:right">';
        html += '<label>' + lblTotaleCamera + ' ' + room + '</label>';
        html += '<input id="totale' + room + '" name="totale' + room + '" title="' + lblTotaleCamera + ' ' + room + '" type="text" />';
        html += '<input id="ad_' + room + '" name="ad_' + room + '" type="hidden" value="' + adulti + '" />';
        html += '<input id="bb_' + room + '" name="bb_' + room + '" type="hidden" value="' + bambini + '" />';
        html += '<input id="roomID_' + room + '" name="roomID_' + room + '" type="hidden" value="' + roomID + '" />';
        html += '<div id="extraroom' + room + '" style="color:#DD0000;"></div>';
        html += '</li>';
        html += '</ul>';
        var new_fieldset = new Element('fieldset', { 'id': 'fieldset' + room, 'class': 's02', 'html': html });
        new_fieldset.inject(last_fieldset, 'before');
    }
    
    CalculateRoomCost(room, rooms, numAdditionalBeds, nummaxkids);
}

function CalculateRoomCost(room, accomodationRooms, numMaxAdditionalBeds, numMaxkids) {
    var qryStr = 'key=' + $('accKey').value + '&ser=' + $('ser').value + '&room=' + room + '&lang=' + LinguaID + '&accTypeID=' + AccomodationTypeID;
    var fieldset = $('fieldset' + room);
    if (fieldset) {
        fieldset.getElements('input').each(function(el) {
            if (el.type == 'checkbox')
                if (el.checked)
                qryStr += '&' + el.get('id') + '=1';
            else
                qryStr += '&' + el.get('id') + '=0';
            else
                qryStr += '&' + el.get('id') + '=' + el.value;
        });
        fieldset.getElements('select').each(function(el) {
            qryStr += '&' + el.get('id') + '=' + el.value;
        });
    }
    qryStr += '&sd=' + $('sd').value;
    qryStr += '&ed=' + $('ed').value;
    if ($('ad_' + room))
        qryStr += '&ad=' + $('ad_' + room).value;
    if ($('bb_' + room))
        qryStr += '&bb=' + $('bb_' + room).value;

    var ul = fieldset.getFirst('ul');
    var arraybambini = ul.getElements('.kid');
    var arrayadulti = ul.getElements('.adult');

    // ESEGUI controlli sulla validità dei dati prima di calcolare il preventivo
    // controlla dati per "li" degli adulti
    var errori = '';
    var CountAdditionalBeds = 0;

    if ($('bb_' + room))
        if ($('bb_' + room).value > numMaxkids)
        if (numMaxkids == 0)
            errori += lblScontoBambiniNonPrevisto + '<br />';
        else
            errori += lblScontoBambiniPrevistoSolo + ' ' + numMaxkids + '<br />';
    
    for (var i = 1; i <= arrayadulti.length; i++) {
        if (!$('affitto' + room + '_ad' + i))
            errori += lblOltreMassimaCapienza + '<br />';
        else {
            if ($('addbed' + room + '_ad' + i))
                if ($('addbed' + room + '_ad' + i).checked)
                    CountAdditionalBeds++;
            if ($('affitto' + room + '_ad' + i).checked)
                $('corso' + room + '_ad' + i).checked = false;
            else
                if ($('corso' + room + '_ad' + i).checked)
                    $('affitto' + room + '_ad' + i).checked = false;
            // se "affitto" o "corso" sono checkati, controlla che sia impostato il numero di giorni
            if ($('affitto' + room + '_ad' + i).checked || $('corso' + room + '_ad' + i).checked)
                if (isNaN($('giornicorso' + room + '_ad' + i).value))
                    errori += lblAdulto + ' ' + i + ': ' + lblInserireGiorni + '<br />';
            else
                if ($('giornicorso' + room + '_ad' + i).value <= 0) {
                    errori += lblAdulto + ' ' + i + ': ' + lblInserireGiorni + '<br />';
            }
            // se "rimessaggio" è checkato, controllare che siano compilati anche gli altri campi
            if ($('rimessaggio' + room + '_ad' + i).checked) {
                if (isNaN($('giornirimessa' + room + '_ad' + i).value))
                    errori += lblAdulto + ' ' + i + ': ' + lblInserireGiorniRimessaggio + '<br />';
                else
                    if ($('giornirimessa' + room + '_ad' + i).value <= 0)
                        errori += lblAdulto + ' ' + i + ': ' + lblInserireGiorniRimessaggio + '<br />';
                if (isNaN($('numvele' + room + '_ad' + i).value) && isNaN($('numtavole' + room + '_ad' + i).value))
                    errori += lblAdulto + ' ' + i + ': ' + lblSpecificareOggetto + '<br />';
                else
                    if ($('numvele' + room + '_ad' + i).value <= 0 && $('numtavole' + room + '_ad' + i).value <= 0)
                        errori += lblAdulto + ' ' + i + ': ' + lblSpecificareOggetto + '<br />';
            }
        }
    }
    // Se il numero di letti aggiunti inseriti dal cliente è superiore dal numero massimo permesso, visualizza errore
    if (CountAdditionalBeds > numMaxAdditionalBeds)
        errori += lblTroppiLetti;
    
    // controlli per bambini come adulti + controllo età
    for (var i = 1; i <= arraybambini.length; i++) {
        if (!$('affitto' + room + '_bb' + i))
            errori += lblOltreMassimaCapienza;
        else {
            // controlla l'età
            if (isNaN($('eta' + room + '_bb' + i).value))
                errori += lblBambino + ' ' + i + ': ' + lblSpecifareEta + '<br />';
            else
                if ($('eta' + room + '_bb' + i).value <= 0)
                    errori += lblBambino + ' ' + i + ': ' + lblSpecificareEta + '<br />';
            // se "affitto" o "corso" sono checkati, controlla che sia impostato il numero di giorni
            if ($('affitto' + room + '_bb' + i).checked || $('corso' + room + '_bb' + i).checked)
                if (isNaN($('giornicorso' + room + '_bb' + i).value))
                    errori += lblBambino + ' ' + i + ': ' + lblInserireGiorni + '<br />';
            else
                if ($('giornicorso' + room + '_bb' + i).value <= 0)
                    errori += lblBambino + ' ' + i + ': ' + lblInserireGiorni + '<br />';
            // se "rimessaggio" è checkato, controllare che siano compilati anche gli altri campi
            if ($('rimessaggio' + room + '_bb' + i).checked) {
                if (isNaN($('giornirimessa' + room + '_bb' + i).value))
                    errori += lblBambino + ' ' + i + ': ' + lblInserireGiorniRimessaggio + '<br />';
                else
                    if ($('giornirimessa' + room + '_bb' + i).value <= 0)
                        errori += lblBambino + ' ' + i + ': ' + lblInserireGiorniRimessaggio + '<br />';
                if (isNaN($('numvele' + room + '_bb' + i).value) && isNaN($('numtavole' + room + '_bb' + i).value))
                    errori += lblBambino + ' ' + i + ': ' + lblSpecificareOggetto + '<br />';
                else
                    if ($('numvele' + room + '_bb' + i).value <= 0 && $('numtavole' + room + '_bb' + i).value <= 0)
                        errori += lblBambino + ' ' + i + ': ' + lblSpecificareOggetto + '<br />';
            }
        }
    }

    if (errori != '') {
        // Stampa errore
        $('totale' + room).value = ' - - ';
        $('totale').value = ' - - ';
        var li_errori = $('errori' + room);
        if (li_errori)
            li_errori.innerHTML = errori;
        else {
            var li_errori = new Element('div', { 'id': 'errori' + room, 'class':'div_errori', 'html': errori });
            var litotale = ul.getLast('li');
            li_errori.inject(litotale, 'top');
        }
        var button = $('sendform');
        button.disabled = 'disabled';
        button.set('disabled', 'disabled');
        return;
    }
    else {
        var li_errori = $('errori' + room)
        if (li_errori)
            li_errori.dispose();
    }
    
    qryStr += '&cache=' + Math.floor(Math.random() * 32767);

    var myRequest = new Request({
        onRequest: function() { },
        onCancel: function() { },
        onSuccess: function(a, b) {
            if (a != "") {
                if (a.indexOf('|') < 0) {
                    var errorMsg = '';
                    if (a.toLowerCase() == 'error: -1')
                        errorMsg = lblCombinazioneNonPrevista;
                    else
                        errorMsg = a;

                    $('totale' + room).value = ' - - ';
                    $('totale').value = ' - - ';
                    var roomExtra = $('extraroom' + room);
                    roomExtra.innerHTML = '';
                    var li_errori = $('errori' + room);
                    if (li_errori)
                        li_errori.innerHTML = errorMsg;
                    else {
                        var li_errori = new Element('div', { 'id': 'errori' + room, 'class': 'div_errori', 'html': errorMsg });
                        var litotale = ul.getLast('li');
                        li_errori.inject(litotale, 'top');
                    }
                    UpdateTotalPrice();
                }
                else {
                    var arr = a.split('|');
                    var totalestanza = $('totale' + room);
                    totalestanza.value = arr[0];
                    var roomID = $('roomID_' + room);
                    roomID.value = arr[1];
                    var roomExtra = $('extraroom' + room);
                    roomExtra.innerHTML = arr[2];
                    UpdateTotalPrice();
                    if (li_errori)
                        li_errori.dispose();
                }
            }
        },
        onFailure: function(a, b) { alert(a.responseText); },
        method: 'post',
        url: '/scripts/calcolapreventivo.asp'
    }).send(qryStr);

}

// Calcola il prezzo totale della prenotazione, sommando i prezzi parziali
function UpdateTotalPrice() {
    var totalepreventivo = $('totale');
    if (totalepreventivo) {
        var numTMP = $('rooms_number').value;
        var valueTMP = 0;
        //alert(numTMP);
        for (var i = 1; i <= numTMP; i++) {
            if ($('totale' + i))
                valueTMP += Number($('totale' + i).value);
        }
        if (isNaN(valueTMP)) {
            totalepreventivo.value = ' - - ';
            var button = $('sendform');
            button.disabled = 'disabled';
            button.set('disabled', 'disabled');
        }
        else {
            var button = $('sendform');
            button.set('disabled', '');
            totalepreventivo.value = valueTMP;
        }
    }
}


// Invio form prima e seconda pagina
function CheckForm(formID) {
    if (!isDate(window.document.getElementById('giorno-arrivo').value, window.document.getElementById('mese-arrivo').value, window.document.getElementById('anno-arrivo').value)) {
        alert(lblDataArrivoNonValida);
        return false;
    }
    if (!isDate(window.document.getElementById('giorno-partenza').value, window.document.getElementById('mese-partenza').value, window.document.getElementById('anno-partenza').value)) {
        alert(lblDataPartenzaNonValida);
        return false;
    }
    dateStart = new Date(window.document.getElementById('anno-arrivo').value, window.document.getElementById('mese-arrivo').value - 1, window.document.getElementById('giorno-arrivo').value, 23, 59, 00);
    dateEnd = new Date(window.document.getElementById('anno-partenza').value, window.document.getElementById('mese-partenza').value - 1, window.document.getElementById('giorno-partenza').value, 23, 59, 00);
    dateNow = new Date();
    differenza = dateEnd - dateStart;
    differenzaoggi = dateStart - dateNow;
    if (differenza <= 0) {
        alert(lblErroreData1);
        return false;
    }
    if (differenzaoggi < 0) {
        alert(lblErroreData2);
        return false;
    }
    if (differenza > 2678400000) {
        alert(lblErroreData3);
        return false;
    }
    window.document.getElementById(formID).action = "preventivo01.asp";
    window.document.getElementById(formID).submit();
}


// Invio form prima e seconda pagina
function CheckFormHome(formID, language) {
    if (!isDate(window.document.getElementById('giorno-arrivo').value, window.document.getElementById('mese-arrivo').value, window.document.getElementById('anno-arrivo').value)) {
        alert(lblDataArrivoNonValida);
        return false;
    }
    if (!isDate(window.document.getElementById('giorno-partenza').value, window.document.getElementById('mese-partenza').value, window.document.getElementById('anno-partenza').value)) {
        alert(lblDataPartenzaNonValida);
        return false;
    }
    dateStart = new Date(window.document.getElementById('anno-arrivo').value, window.document.getElementById('mese-arrivo').value - 1, window.document.getElementById('giorno-arrivo').value, 23, 59, 00);
    dateEnd = new Date(window.document.getElementById('anno-partenza').value, window.document.getElementById('mese-partenza').value - 1, window.document.getElementById('giorno-partenza').value, 23, 59, 00);
    dateNow = new Date();
    differenza = dateEnd - dateStart;
    differenzaoggi = dateStart - dateNow;
    if (differenza <= 0) {
        alert(lblErroreData1);
        return false;
    }
    if (differenzaoggi < 0) {
        alert(lblErroreData2);
        return false;
    }
    if (differenza > 2678400000) {
        alert(lblErroreData3);
        return false;
    }
    window.document.getElementById(formID).action = "/" + language + "/booking/preventivo01.asp";
    window.document.getElementById(formID).submit();
}


// Accetta il calcolo del preventivo e vai alla pagina di raccolta dati per l'invio della richiesta
function SendPriceRequest(language) {
    window.document.getElementById('form_booking').action = "/" + language + "/booking/preventivo03.asp";
    window.document.getElementById('form_booking').submit();
}

// Scelta hotel per preventivo con invio form
function ChooseAccomodation(valore) {
    if (!isDate(window.document.getElementById('giorno-arrivo').value, window.document.getElementById('mese-arrivo').value, window.document.getElementById('anno-arrivo').value)) {
        alert(lblDataArrivoNonValida);
        return false;
    }
    if (!isDate(window.document.getElementById('giorno-partenza').value, window.document.getElementById('mese-partenza').value, window.document.getElementById('anno-partenza').value)) {
        alert(lblDataPartenzaNonValida);
        return false;
    }
    dateStart = new Date(window.document.getElementById('anno-arrivo').value, window.document.getElementById('mese-arrivo').value - 1, window.document.getElementById('giorno-arrivo').value, 23, 59, 00);
    dateEnd = new Date(window.document.getElementById('anno-partenza').value, window.document.getElementById('mese-partenza').value - 1, window.document.getElementById('giorno-partenza').value, 23, 59, 00);
    dateNow = new Date();
    differenza = dateEnd - dateStart;
    differenzaoggi = dateStart - dateNow;
    if (differenza <= 0) {
        alert(lblErroreData1);
        return false;
    }
    if (differenzaoggi < 0) {
        alert(lblErroreData2);
        return false;
    }
    if (differenza > 2678400000) {
        alert(lblErroreData3);
        return false;
    }
    window.document.getElementById('AccomodationID').value = valore;
    window.document.getElementById('formpreventivo').action = "preventivo02.asp";
    window.document.getElementById('formpreventivo').submit();
}


// Validate del form di invio dati del preventivo
function ValidateFormPreventivo()
{
	// Controlla che il campo 'nome' sia compilato
	if (document.getElementById('invioForm').nome.value=='Nome e Cognome')
	{
	    alert(lblErroreNome);
		document.getElementById('invioForm').nome.focus();
		return false;
	}
	if (!isEmail(document.getElementById('invioForm').email.value))
	{
		alert(lblErroreEmail);
		document.getElementById('invioForm').email.focus();						
		return false;
	}
	if (document.getElementById('invioForm').captchacode.value=='Codice di verifica')
	{
	    alert(lblErroreCaptcha);
		document.getElementById('invioForm').captchacode.focus();
		return false;
	}
	if (!window.document.getElementById('invioForm').privacy1[0].checked) {
		alert(lblErroreDatiPersonali);
		return false;
	}
	return true;
}


// Script generici validazione campi

// ritorna false se l'argomento ha lunghezza 0, true altrimenti
// Argomenti: str tipo stringa
function notNull(str) {
    if (str.length == 0)
        return false;
    else
        return true;
}

// ritorna true se il primo argomento rappresenta un numero
// compreso tra il secondo (valore minimo) e il terzo 
// (valore massimo) argomento
// Argomenti: str stringa,  num1,num2 numerici
function isInRange(str, num1, num2) {
    var i = parseInt(str, 10);

    return ((i >= num1) && (i <= num2));
}

// ritorna false se l'argomento è costituito da soli spazi o
// ha lunghezza 0, true altrimenti
// Argomenti: str tipo stringa
function notBlank(str) {
    for (i = 0; i < str.length; i++) {
        if (str.charAt(i) != " ")
            return true;
    }
    return false;
}

// ritorna true se l'argomento è una stringa costituita
// unicamente da caratteri numerici, false altrimenti
// Argomenti: str stringa
function isDigits(str) {
    var myExp = /^[0-9]*$/;
    return myExp.test(str);
}

// ritorna true se l'argomento è una stringa costituita
// unicamente da caratteri numerici, il segno + e lo spazio, false altrimenti
// Argomenti: str stringa
function isCellular(str) {
    var myExp = /^[0-9 +]*$/;

    return myExp.test(str);
}

// ritorna true se il primo argomento è una stringa
// di lunghezza superiore al valore del secondo argomento,
// false altrimenti
// Argomenti: str stringa, maxLength numerico
function isLonger(str, maxLength) {
    if (str.length > maxLength)
        return true;
    return false;
}

// ritorna true se il primo argomento è una stringa
// di lunghezza inferiore al valore del secondo argomento,
// false altrimenti
// Argomenti: str stringa, minLength numerico
function isShorter(str, minLength) {
    if (str.length < minLength)
        return true;
    return false;
}

// ritorna true se la lunghezza della stringa passata come 
// primo argomento è compresa tra i valori rappresentati
// dal secondo (minimo) e il terzo (massimo) argomento,
// false altrimenti
// Argomenti: str stringa, minLength,maxLength numerici
function isInside(str, minLength, maxLength) {
    if (!isShorter(str, minLength) && !isLonger(str, maxLength))
        return true;
    return false;
}

// ritorna true se l'argomento è una stringa composta unicamente
// da lettere
// Argomenti: str stringa
function isLetter(str) {
    var myExp = /^[a-z]*$/i;

    return myExp.test(str);
}

// ritorna true se l'argomento è una stringa composta unicamente
// da caratteri alfanumerici
// Argomenti: str stringa
function isAlfanumeric(str) {
    var myExp = /^[a-z0-9]*$/i;

    return myExp.test(str);
}

// ritorna true se l'argomento è una stringa composta 
// da caratteri alfanumerici, spazi e apici
// Argomenti: str stringa
function isAlfanumeric2(str) {
    var myExp = /^[a-z0-9 .,\/\-'éàùòì]*$/i;

    return myExp.test(str);
}

// ritorna true se l'argomento è una stringa composta 
// solo da lettere, spazi e apici
// Argomenti: str stringa
function isAlfanumeric3(str) {
    var myExp = /^[a-z 'éàùòì]*$/i;

    return myExp.test(str);
}

// ritorna true se l'argomento è una stringa composta 
// da caratteri alfanumerici, il punto, - e _
// Argomenti: str stringa
function isAlfanumeric4(str) {
    var myExp = /^[a-z0-9\-\_\éàùòì]*$/i;

    return myExp.test(str);
}

// Ritorna true se l'argomento è un indirizzo di email valido.
// E' valida la sintassi usuale user@domain,
// ma sono consentiti anche i formati user@[ip]
// e "User with Spaces"@domain o [ip],
// (tutte sintassi legali secondo il W3C.)
// Sono controllati anche errori quali multipli @ o . limitrofi
// nell'indirizzo (Es: user@a@b.com ed user@a..b.co.uk).
// Argomenti: emailStr stringa.
function isEmail(emailStr) {
    // Formato user@domain e separazione di username e dominio
    var emailPat = /^(.+)@(.+)$/;
    // Pattern per ritrovare i caratteri speciali (non consentiti)
    var specialChars = "\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
    // Caratteri consentiti in username o domainname
    var validChars = "\[^\\s" + specialChars + "\]";
    // Username contenente spazi
    var quotedUser = "(\"[^\"]*\")";
    // domainName costituito da un indirizzo IP
    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    // Unità 'atomo' ovvero una serie di caratteri non speciali
    var atom = validChars + '+';
    // Una 'word' dell'username. L'username può essere costituito da più 'word'
    // separate da .
    var word = "(" + atom + "|" + quotedUser + ")";
    // Struttura dell'username
    var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
    // Dominio sombolico
    var domainPat = new RegExp("^" + atom + "(\\." + atom + ")*$");

    // Controllo della sintassi username@domain e separazione dell'username dal
    // domain
    var matchArray = emailStr.match(emailPat);
    if (matchArray == null) {
        //alert("Email address seems incorrect (check @ and .'s)")
        return false;
    }
    var user = matchArray[1];
    var domain = matchArray[2];
    // User valido.
    if (user.match(userPat) == null) {
        //alert("The username doesn't seem to be valid.")
        return false;
    }
    // Indirizzo IP valido (nel caso in cui il domain sia un IP.
    var IPArray = domain.match(ipDomainPat);
    if (IPArray != null) {
        for (var i = 1; i <= 4; i++) {
            if (IPArray[i] > 255) {
                //alert("Destination IP address is invalid!")
                return false;
            }
        }
        return true;
    }
    // Domain è un nome simbolico
    var domainArray = domain.match(domainPat);
    if (domainArray == null) {
        //alert("The domain name doesn't seem to be valid.")
        return false;
    }
     // controllo sulla parte terminale del domain.
    // Spezzo il domain in 'atomi'
    var atomPat = new RegExp(atom, "g");
    var domArr = domain.match(atomPat);
    var len = domArr.length;
    if ((domArr[domArr.length - 1].length < 2) ||
	    (domArr[domArr.length - 1].length > 4)) {
        // alert("The address must end in a three-letter domain, or two letter country.")
        return false;
    }
    // Parte terminale del dominio preceduta da un host name.
    if (len < 2) {
        //var errStr="This address is missing a hostname!"
        //alert(errStr)
        return false;
    }
    return true;
}

// ritorna true se la data rappresentata dal giorno pari al
// primo argomento, dal mese pari al secondo e dall'anno pari 
// al terzo è valida, false altrimenti
// Argomenti gg,mm,aaaa stringhe rappresentanti interi
// (aaaa anno in formato esteso a 4 cifre)
function isDate(gg, mm, aaaa) {
    // gg, mm, aaaa sono stringhe tutte di caratteri numerici
    if (!isDigits(gg)) return false;
    if (!isDigits(mm)) return false;
    if (!isDigits(aaaa)) return false;
    giorno = parseInt(gg, 10);
    mese = parseInt(mm, 10);
    anno = parseInt(aaaa, 10);
    if (!isInRange(giorno, 1, 31)) return false;
    if (!isInRange(mese, 1, 12)) return false;
    if (!isInRange(anno, 1890, 2050)) return false;
    testDate = new Date(anno, mese - 1, giorno);
    return (testDate.getMonth() == (mese - 1) &&
			 testDate.getDate() == (giorno))
}

// ritorna true se l'argomento è una stringa non 
// vuota e non costituita da soli spazi
// Argomenti: str stringa
function isValidString(str) {
    if (notNull(str) && notBlank(str))
        return true;
    return false;
}

// ritorna true se il primo argomento è una stringa di 
// lunghezza pari al valore del secondo argomento
// Argomenti: str tipo stringa, size intero
function isSize(str, size) {
    if (str.length == size)
        return true;
    else
        return false;
}

// ritorna true se nella stringa passata per argomento
// sono contenuti 5 caratteri numerici (es.CAP)
// Argomenti: str stringa
function isCAP(str) {
    if (isDigits(str) && isSize(str, 5)) {
        return true;
    }
    return false;
}

// ritorna true se nella stringa passata per argomento
// sono contenute 2 lettere (es. Provincia)
// Argomenti: str stringa
function isProv(str) {
    if (notNull(str) && isLetter(str)) {

        if (isSize(str, 2))
            return true;
    }
    return false;
}

// ritorna true se nella stringa passata per argomento
// sono contenuti 11 caratteri numerici (es. P.IVA)
// Argomenti: str stringa
function isPIVA(str) {
    if (isDigits(str) && isSize(str, 11)) {
        return true;
    }
    return false;
}

// ritorna true se nella stringa passata per argomento
// sono contenuti 16 caratteri alfanumerici (es. Cod.Fiscale)
// Argomenti: str stringa
function isCodFisc(str) {
    if (isAlfanumeric(str) && isSize(str, 16)) {
        return true;
    }
    return false;
}
