﻿var calendarDateChanged = false;

// This function gets called when the end-user clicks on some date.
function selected(cal, date) {
    cal.sel.value = date; // just update the date in the input field.
    if (cal.dateClicked && (cal.sel.id == "sel1" || cal.sel.id == "sel3"))
    // if we add this call we close the calendar on single-click.
    // just to exemplify both cases, we are using this only for the 1st
    // and the 3rd field, while 2nd and 4th will still require double-click.
        cal.callCloseHandler();
    calendarDateChanged = true;
}

// And this gets called when the end-user clicks on the _selected_ date,
// or clicks on the "Close" button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
    cal.hide();                        // hide the calendar
    //  cal.destroy();
    _dynarch_popupCalendar = null;
}

// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(id, format, attachEl, showsTime, showsOtherMonths) {
    var el = document.getElementById(id);
    if (_dynarch_popupCalendar != null) {
        // we already have some calendar created
        _dynarch_popupCalendar.hide();                 // so we hide it first.
    } else {
        // first-time call, create the calendar.
        var cal = new Calendar(1, null, selected, closeHandler);
        // uncomment the following line to hide the week numbers
        // cal.weekNumbers = false;
        if (typeof showsTime == "string") {
            cal.showsTime = true;
            cal.time24 = (showsTime == "24");
        }
        if (showsOtherMonths) {
            cal.showsOtherMonths = true;
        }
        _dynarch_popupCalendar = cal;                  // remember it in the global var
        cal.setRange(1900, 2070);        // min/max year allowed.
        cal.create();
    }
    _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
    _dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
    _dynarch_popupCalendar.sel = el;                 // inform it what input field we use

    // the reference element that we pass to showAtElement is the button that
    // triggers the calendar.  In this example we align the calendar bottom-right
    // to the button.
    var ael = document.getElementById(attachEl);
    _dynarch_popupCalendar.showAtElement(ael, "");        // show the calendar

    return false;
}

function checkField(field, defVal) {
    var fieldVal = field.value;
    if (isNaN(fieldVal)) {
        field.value = defVal;
    }
}

function createFormEvent() {
    try {
        if (document.addEventListener) {
            document.addEventListener('onsubmit', checkForm, false);
        } else {
            document.attachEvent('onsubmit', checkForm);
        }
        if (document.removeEventListener)
            setTimeout("document.getElementById('" + frmPrefix + "Smb').removeEventListener('onclick', checkForm, false);", 250);
        else
            setTimeout("document.getElementById('" + frmPrefix + "Smb').detachEvent('onclick', checkForm);", 250);
    }
    catch (E) {
    }
}

function checkForm(e) {
    if (proxyUrl == null) {
        alert('Set proxy url');
        return false;
    }

    if (chkObject(frmPrefix + "Date")) {
        var selDate = new String(document.getElementById(frmPrefix + "Date").value);
        selDate = selDate.replace(/\//g, '.');
    }
    
    if (calendarDateChanged == true) {
        if (window.ActiveXObject && !window.XMLHttpRequest) { window.XMLHttpRequest = function() { progIds = new Array("Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "Msxml2.XMLHTTP.3.0", "Msxml2.XMLHTTP", "Microsoft.XMLHTTP"); for (i in progIds) { try { return new ActiveXObject(progIds[i]); } catch (ex) { alert(progIds[i]); } } return null; }; }

        var urlRequest = proxyUrl + urlVar + "&jsRqstDate=" + selDate + "&rnd=" + Math.random();

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            // js to handle the HTTP request
            if (xhr.readyState == 4) {
                // HTTP Request complete
                try {
                    eval(xhr.responseText);
                    calendarDateChanged = false;
                }
                catch (E) {
                    alert('Connection error');
                    return false;
                }
            }
        };

        try {
            xhr.open("GET", urlRequest, false);
            xhr.send();
        }
        catch (E) {
            alert('Connection error');
            return false;
        }
    }

    //Giorno di arrivo
    if (chkObject(frmPrefix + "Date")) {
        var sSelDate = selDate.split('.');
        var selDDate = new Date();
        selDDate.setFullYear(parseInt(sSelDate[2]));
        selDDate.setMonth(parseInt(sSelDate[1]*1) - 1);
        selDDate.setDate(parseInt(sSelDate[0]*1));
        var dayIsValid = new Boolean;
        dayIsValid = true;

        if (vday.length > 0) {
            dayIsValid = false;
            for (var i = 0; i < vday.length; i++) {
                if (parseInt(vday[i]) == selDDate.getDay()) {
                    dayIsValid = true;
                }
            }
        }

        if (!dayIsValid) {
            var invalidDays = '';
            for (var i = 0; i < vday.length; i++) {
                invalidDays += Calendar._DN[parseInt(vday[i])] + "\n";
            }
            //setAlertMsg(invalidDayAlertMsg.replace('#1', escape(invalidDays)));
            setAlertMsg(invalidDayAlertMsg.replace('#1',invalidDays));
            return false;
        }
    }
    
    
    //Sistemazione
    var selSistemazione = 0;
    if (chkObject(frmPrefix + "Sys") && document.getElementById(frmPrefix + 'Sys').type == "select-one") {
        if (document.getElementById(frmPrefix + 'Sys').selectedIndex == 0) {
            setAlertMsg(accomodationAlertMsg);
            return false;
        } else {
            selSistemazione = document.getElementById(frmPrefix + 'Sys').options[document.getElementById(frmPrefix + 'Sys').selectedIndex].value;
        }
    } else {
        if (chkObject(frmPrefix + "SysH")) {
            selSistemazione = document.getElementById(frmPrefix + 'SysH').value;
        }
    }
    

    //Notti
    if (chkObject(frmPrefix + "Ngt")) {
        var selNotti = 0;
        try {
            selNotti = parseInt(document.getElementById(frmPrefix + 'Ngt').value);
        }
        catch (E) {
            alert('Form error [notti]');
            return false;
        }

        if (selNotti < parseInt(nottiParm[0])) {
            setAlertMsg(minNightAlertMsg.replace('#1', nottiParm[0]));
            return false;
        }

        if (selNotti > parseInt(nottiParm[1])) {
            setAlertMsg(maxNightAlertMsg.replace('#1', nottiParm[1]));
            return false;
        }

        if ((selNotti % parseInt(nottiParm[2])) != 0) {
            setAlertMsg(mulNightAlertMsg.replace('#1', nottiParm[2]));
            return false;
        }
    }
    
    //Persone
    var sistemazione = new Array(0, 0, 0);
    for (var i = 0; i < accomodations.length; i++) {
        if (accomodations[i][0] == selSistemazione) {
            sistemazione = accomodations[i];
        }
    }

    var selPerson = incPerson;
    try {
        for (var i = 0; i < persons.length; i++) {
            if (chkObject(persons[i])) {
                selPerson += parseInt(document.getElementById(persons[i]).value);
            }
        }
    } catch (E) {
        alert('Form error [persons]');
        return false;
    }

    if (selPerson == 0) {
        setAlertMsg(emptyPersAlertMsg);
        return false;
    }

    if (parseInt(sistemazione[1]) > selPerson) {
        setAlertMsg(minPersAlertMsg);
        return false;
    }

    if (parseInt(sistemazione[2]) < selPerson) {
        setAlertMsg(maxPersAlertMsg);
        return false;
    }

    //Avvisi
    var msg = '';
    for (var i = 0; i < alertzero.length; i++) {
        if (document.getElementById(alertzero[i][0]).value == "0") {
            msg += '\n' + alertzero[i][1] ;
        }
    }
    if (msg != '') {
        return confirm(zeroAlertMsg.replace('#1', msg));
    }
    return true;
}

function setAlertMsg(msg) {
    alert(msg);
    msg = msg.replace(/\n/g, '<br>');
    document.getElementById('rateErrorMessages').innerHTML = msg;
}

function chkObject(theVal) {
    if (document.getElementById(theVal) != null) {
        return true;
    }
    else {
        return false;
    }
}




