
function dateRangeIsValid () {
    var valid =
        !$("#checkout").val() || !$("#checkin").val()
        || ($("#checkin").datepicker("getDate") < $("#checkout").datepicker("getDate"));
    return valid;
}

var Validator = {
    "name": {
        "empty": "Please enter your name",
        "wrong": "Please enter your name",
        "isValid": function () {
            return (/^[a-zA-Z]+$/.test(this.input.val()));
        }
    },
    "phone": {
        "empty": "You must enter your phone number",
        "wrong": "Please enter your phone number",
        "isValid": function () {
            return (/^[0-9()#\/*+\-. ]+$/.test(this.input.val()));
        }
    },
    "email": {
        "empty": "You must enter an e-mail address",
        "wrong": "Please enter a Valid email ",
        "isValid": function () {
            return (/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(this.input.val()));
        }
    }/*,
    "emailconfirm": {
        "empty": "You must confirm your e-mail address by writing it again on the proper field",
        "wrong": "Your emails don't match",
        "isValid": function () {
            return (this.input.val() == $("#email").val());
        }
    }*/,
    "checkin": {
        "empty": "You must enter a valid arrival date, for example: 16 Jun 2011",
        "wrong": "The departure date must be later than the arrival one!",
        "isValid": dateRangeIsValid
    },
    "checkout": {
        "empty": "You must enter a valid departure date, for example: 21 Dec 2012",
        "wrong": "",
        "isValid": dateRangeIsValid
    }
};

// This is set to true after a change in dates. As soon as everything
// in the form is valid, the ajax check is called and this goes back to false.
// This way, if a date is changed (again) but something else in the form is invalid,
// the ajax will take place when that field is corrected. Yes this is heavy nitpicking.
var mustCheckAvailability = false;

$(function () {
    $("#bookFormSubmit").attr("disabled", true);
    $.maskElement($("#roomSelection"));
    var currentTime = new Date()

    var month=new Array(12);
    month[0]="Jan";
    month[1]="Feb";
    month[2]="Mar";
    month[3]="Apr";
    month[4]="May";
    month[5]="Jun";
    month[6]="Jul";
    month[7]="Aug";
    month[8]="Sep";
    month[9]="Oct";
    month[10]="Nov";
    month[11]="Dec";
    var today  = currentTime.getDate()+' '+month[currentTime.getMonth()]+' '+currentTime.getFullYear();

    $("#checkin, #checkout").datepicker({dateFormat: "dd M yy", minDate: today});
    
    $.each(Validator, function (id) {
        this.input = $("#"+id);
        this.error = false; //can be "empty", "wrong" or false
        this.errorListItem = false;
        
        this.validate = validate;
        this.displayError = displayError;
    });
    
    $("#checkout").one("change", function (){
        $.each(Validator, function (field) {
            if (field != "checkin" && field != "checkout")
                this.validate();
        });
    });
    
    $("#checkin, #checkout").change(function () { mustCheckAvailability = true; });
    
    $.each(Validator, function (field) {
        var that = this;
        var dependantField = Validator[{
            "checkin": "checkout",
            "checkout": "checkin",
            "email": "emailconfirm"
        }[field]];
        this.input.change(function () {
            that.validate();
            if (dependantField && dependantField.input.val())
                dependantField.validate();
            if (!$("#errorList li").length && mustCheckAvailability)
                showAvailability();
        });
    });
});

function validate () {
    var err = false;
    /*
    if (!this.input.val().replace(/ /g, "").length)
        err = "empty";
    else */
    if (!this.isValid())
        err = "wrong";
    if (this.error != err) {
        this.error = err;
        this.displayError();
    }
}

function displayError () {
    if (this.errorListItem)
        this.errorListItem.remove();
    if (!this.error) {
        this.input.removeClass("errorField");
        this.errorListItem = false;
        if (!$("#errorList li").length && $("#checkout").val()) {
        document.getElementById('bookingReqText').style.display = 'none';
            $.unmaskElement($("#roomSelection"));
            $("#bookFormSubmit").attr("disabled", false);
        }
    } else {
        $.maskElement($("#roomSelection"));
        $("#bookFormSubmit").attr("disabled", true);
        this.input.addClass("errorField");
        if (this[this.error])
            this.errorListItem = $("<li>"+this[this.error]+"</li>").appendTo("#errorList");
    }
}

function showAvailability () {
    var dates = [$("#checkin").val(), $("#checkout").val()];
    if (dates[0] && dates[1]) {
        $("#bookFormSubmit").attr("disabled", false);
        $("#roomSelection").mask("Please wait...", 50);
        mustCheckAvailability = false;
    var xmlhttp = $.getJSON( ajaxAvailabLocal, { "checkin": dates[0], "checkout": dates[1] },changeAvailability );
       xmlhttp.onreadystatechange=function() {
          if (xmlhttp.readyState==4) {
               if (xmlhttp.status==200){
                    changeAvailability(xmlhttp.responseText);
                }
            }
        } 
    }
}
function changeAvailability (data) {
    var theData = JSON.parse(data);
    $.each(theData, function (id, minMax) {
        if (minMax[0] <= minMax[1]) {
            var options = "";
            var bedds = 'person';
            for (var i = minMax[0]; i <= minMax[1]; i++){
                if(i>1) var bedds = 'persons';
                options += '<option value="'+i+'">'+i+' '+bedds+'</option>';
            }
            $("#room_"+id).html('<option value="" selected="selected">Available</option>'+options);
        } else
            $("#room_"+id).html('<option value="" selected="selected">Full</option>');
    });
        //document.getElementById('bookingReqText').style.display = 'none';
    $('#bookingReqText').slideUp('slow', function() { });
    $("#roomSelection").unmask();
    $("#roomSelection").effect("highlight", {color: "#D8773B", duration: 2000});
    $('#bookingPromotion').slideDown('slow', function() { });
}

function validateBeds () {
    var valid = false;
    $("#bookForm select").each(function () {
        if (this.value) {
            valid = true;
            return false;
        }
    });
    if (!valid)
        alert("You must book at least one bed in one room");
    return valid;
}

