﻿if (window.location.href.indexOf("Default.aspx") > -1 || window.location.href.indexOf("default.aspx") > -1) {
    window.location = "/";
}

function pad(i) { return i < 10 ? "0" + i : i; }
function max(v1, v2) { return (v1 >= v2 ? v1 : v2); }
/*************************************************************************\
boolean isExpiryDate([int year, int month])
return true if the date is a valid expiry date,
else return false.
\*************************************************************************/
function isExpiryDate() {
    var argv = isExpiryDate.arguments;
    var argc = isExpiryDate.arguments.length;

    year = argc > 0 ? parseInt(argv[0], 10) : this.year;
    month = argc > 1 ? parseInt(argv[1], 10) : this.month;

    if (!isNum(year + "")) return false;
    if (!isNum(month + "")) return false;
    today = new Date();
    expiry = new Date(year, month - 1);

    if (today.getTime() > expiry.getTime()) return false;
    else return true;

}

/*************************************************************************\
boolean isNum(String argvalue)
return true if argvalue contains only numeric characters,
else return false.
\*************************************************************************/
function isNum(argvalue) {
    argvalue = argvalue.toString();

    if (argvalue.length == 0) return false;

    for (var n = 0; n < argvalue.length; n++)
        if (argvalue.substring(n, n + 1) < "0" || argvalue.substring(n, n + 1) > "9") return false;

    return true;
}

function submitEnter(func, e) {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;

    if (keycode == 13) func();

    return true;
}

var is_blocking = false;

function showWaitingPage(msg) {
    if (typeof msg != "undefined") {
        $("#waitingPage .waitingText").html(msg);
    }

    if (!is_blocking) {
        is_blocking = true;
        $.blockUI({ message: $("#waitingPage"), css: { width: '390px'} });
    }
}

function hideWaitingPage() {
    $.unblockUI();
    is_blocking = false;
}

function keepAlive() {
    $.get("/Ajax/KeepAlive.ashx?r=" + Math.random());
    window.setTimeout("keepAlive()", 60000);
}

// login
function login() {
    $.blockUI({ message: $("#loginform"), css: { border: 'none', background: 'none'} });
}

function logout() {
    showWaitingPage();
    $.ajax({
        url: "/ajax/Account.ashx",
        data: { action: "Logout" },
        cache: false,
        sync: true,
        success: function(xml) {
            window.location = "/";
        }, complete: function() {
            hideWaitingPage();
        }
    });
}

function loginconfirm() {
    var username = $("#loginform input[name=username]").val();
    var password = $("#loginform input[name=password]").val();
    if (username == "") {
        alert(INVALID_USERNAME);
        return false;
    }
    if (password == "") {
        alert(INVALID_PASSWORD);
        return false;
    }

    $("#loginform .input").hide();
    $("#loginform .waiting").show();
    $.ajax({
        url: "/ajax/Account.ashx",
        data: { action: "Login", username: username, password: password },
        cache: false,
        sync: true,
        success: function(xml) {
            window.location = "/Welcome.aspx";
        }, error: function() {
            alert(CANNOT_LOGIN);
        }, complete: function() {
            $("#loginform .input").show();
            $("#loginform .waiting").hide();
            $("#loginform .input input[name=username]").focus();
        }
    });

    return false;
}
// end of login

// autocomplete
function formatLocation(row) {
    if (row[1] == 0)
        return "<div class=\"ac_group\">" + row[0] + "</div>";
    else
        return "<div class=\"ac_subitem\">" + row[0] + "</div>";
}
function parseLocation(data) {
    var groupByTypes = [];
    var data = data.split('\n');
    $(data).each(function() {
        var data = this.split('|');
        if (data.length > 0) {
            var type = data[1];
            if (typeof groupByTypes[type] == "undefined")
                groupByTypes[type] = [];
            var group = groupByTypes[type];
            group[group.length] = data;
        }
    });

    var parsed = [];
    insertLocationGroup(parsed, groupByTypes, "airport", "Airports");
    insertLocationGroup(parsed, groupByTypes, "city", "Cities");
    insertLocationGroup(parsed, groupByTypes, "province", "Regions");
    insertLocationGroup(parsed, groupByTypes, "country", "Countries");

    return parsed;
}
function insertLocationGroup(parsed, group, groupName, groupText) {
    if (typeof group[groupName] == "undefined") return;

    parsed[parsed.length] = {
        data: [groupText, 0, groupName],
        value: 0,
        result: groupText
    };
    for (var i = 0; i < group[groupName].length; i++) {
        var row = group[groupName][i];
        parsed[parsed.length] = {
            data: [row[2], row[0], row[1]],
            value: row[0],
            result: row[2]
        };
    }
}
// end of autocomplete

// convert from EUR to the selected currency
function applyCurrencyRate() {
    $("span.currency").each(function() {
        var currency = $(this).find("span.symbol").text();
        if (currency == CURRENCY_SYMBOL) return true;
        var priceText = $(this).text().replace(currency, "").replace(/[\r\n\s]/g, "");
        var price;
        if (currency == "€") price = parseFloat(priceText.replace(",", "."));
        else price = parseFloat(priceText);
        if (isNaN(price)) return true;

        var html = $(this).html().replace(currency, CURRENCY_SYMBOL).replace(priceText, (price * CURRENCY_RATE).toFixed(2));
        $(this).html(html);
    });
}

// datetimepicker
function getDate(type) {
    var day = parseInt($("#" + type + "Day").val(), 10);
    var month = $("#" + type + "MonthYear").val().split("-");
    var year = parseInt(month[1], 10);
    month = parseInt(month[0], 10);

    return new Date(year, month - 1, day);
}
function setDate(type, date) {
    $("#" + type + "Day").val(pad(date.getDate()));
    $("#" + type + "MonthYear").val(pad(date.getMonth() + 1) + "-" + date.getFullYear());
}
function setDropoffDate(date) {
    setDate("Dropoff", date);
}
// end of datetimepicker

// search cars
function searchCars() {
    if (!validateSearch()) return false;

    showWaitingPage(SEARCHING_PLEASE_WAIT);
    var a = $("#searchform input, #searchform select").serializeArray();
    var s = [];
    $.each(a, function() {
        s.push(encodeURIComponent(this.name) + "=" + encodeURIComponent(this.value));
    });
    s.push("currency=" + $("#currencies").val());

    $.ajax({
        url: "/select.aspx?ajax=1&" + s.join("&").replace(/%20/g, "+"),
        cache: false,
        success: function() {
            window.location = "/select.aspx";
        }, error: function() {
            window.location = "/select.aspx?" + s.join("&").replace(/%20/g, "+");
        }
    });

    return false;
}

function searchCarsIFrame() {
    if (!validateSearch()) return false;

    //showWaitingPage(SEARCHING_PLEASE_WAIT);
    var a = $("#searchform input, #searchform select").serializeArray();
    var s = [];
    $.each(a, function() {
        s.push(encodeURIComponent(this.name) + "=" + encodeURIComponent(this.value));
    });

    $.ajax({
        url: "/select.aspx?ajax=1&" + s.join("&").replace(/%20/g, "+"),
        cache: false,
        success: function() {
            //window.parent.location = "/select.aspx";
            //windowFeatures = "top=0,left=0,resizable=yes,width=" + (screen.width) + ",height=" + (screen.height); 
            window.open("/select.aspx");

        }, error: function() {
            //window.parent.location = "/select.aspx?" + s.join("&").replace(/%20/g, "+");
            window.open("/select.aspx?" + s.join("&").replace(/%20/g, "+"));
        }
    });

    return false;
}

function validateSearch() {
    var location_id = parseInt($("#location_id").val(), 10);
    if (location_id == 0 || $("#location").val() != $("#location_name").val()) {
        alert(Resources.PleaseEnterLocation);
        return false;
    }
    var pickupDate = getDateInSearch("Pickup");
    var dropoffDate = getDateInSearch("Dropoff");
    if (pickupDate < new Date()) {
        alert(Resources.InvalidPickupDate);
        return false;
    }
    if (dropoffDate < new Date()) {
        alert(Resources.InvalidDropoffDate);
        return false;
    }
    if (pickupDate >= dropoffDate) {
        alert(Resources.InvalidPickupDropoffDate);
        return false;
    }

    return true;
}

function getDateInSearch(prefix) {
    var hour = parseInt($("#" + prefix + "Hour").val(), 10);
    var minute = parseInt($("#" + prefix + "Minute").val(), 10);
    var day = parseInt($("#" + prefix + "Day").val(), 10);
    var month = $("#" + prefix + "MonthYear").val().split('-');
    var year = parseInt(month[1], 10);
    month = parseInt(month[0], 10);

    return new Date(year, month - 1, day, hour, minute);
}
// end of search cars

// book car
var is_quote = false;
function book(carid, quote) {
    showWaitingPage(BOOKING_PLEASE_WAIT);
    is_quote = quote;
    $.ajax({
        url: "/Ajax/AddToCart.ashx",
        data: { carid: carid, quote: is_quote ? 1 : 0 },
        cache: false,
        success: function() {
            window.location = (useSSL ? "https://" : "http://") + window.location.host + (is_quote ? "/quote.aspx" : "/book.aspx");
        }, error: function() {
            hideWaitingPage();
            searchCars();
        }
    });
}
// end of book car

// office
function showDropOffices(officeID) {
    //var showDropOff = document.getElementById("showDropOff");
    // if (showDropOff.checked && typeof showDropOff.init == "undefined") {
    //    showDropOff.init = true;
        showWaitingPage(BOOKING_PLEASE_WAIT);
        $.ajax({
            url: "/Ajax/GetOffices.ashx",
            data: { type: "dropoff" },
            cache: false,
            success: function(data) {
                var $offices = $(data).children("Offices").children("Office");
                if ($offices.length == 0) return;
                var $ddl = $("#dropoff_office div:first div:first");
                var $div = $("#dropoff_office .opening_hours div");

                if ($offices.length == 1) {
                    $ddl.html("<span>" + $($offices[0]).attr("Description") + "</span>");
                } else {
                    $ddl.html("<select id=\"dropoff_offices\" name=\"dropoff_offices\"></select>");
                    var $select = $ddl.children("select");
                    $offices.each(function() {
                        $select.append("<option value=\"" + $(this).attr("ID") + "\">" + $(this).attr("Description") + "</option>");
                    });
                    //assign default value
                    $("#dropoff_office_id").val($("#pickup_offices").val());
                    $("#dropoff_offices").val($("#pickup_offices").val());
                    bindOfficeEvents("dropoff");
                }
                $offices.each(function() {
                    $div.append("<ul class=\"opening_hours_" + $(this).attr("ID") + " hide\" officeType=\"" + $(this).attr("OfficeType") + "\"></ul>");
                    var $ul = $div.children("ul:last");
                    $(this).children("OpeningHours").children("OpeningHour").each(function() {
                        $ul.append("<li><span>" + $(this).text() + ":</span> <span>" + $(this).attr("StartTime") + " - " + $(this).attr("CloseTime") + "</span></li>");
                    });
                });

                var selected = $($offices[0]).attr("ID");
                if (typeof officeID != "undefined") {
                    if ($("#dropoff_offices option[value=" + officeID + "]").length > 0) {
                        selected = officeID;
                        $("#dropoff_offices").val(selected);
                    }
                }

                showOpeningHoursAndAcco("dropoff", selected);

                $("#dropoff_office").show("slow");
            }, complete: function() {
                hideWaitingPage();
            }
        });
 //   }
//    else {
//        $("#dropoff_office").toggle("slow");
//        if (!$("#dropoff_office")[0].checked) {
//            $("#dropoff_office_id").val($("#pickup_office_id").val());
//            $("#dropoff_offices").val($("#dropoff_office_id").val());
//            if (typeof $("#dropoff_office") != "undefined" && $("#dropoff_office").css("display") == "block")
//                showOpeningHoursAndAcco("dropoff", $("#dropoff_office_id").val());
//        }
//        setOffices();
//    }
}

function bindOfficeEvents(type) {
    $("#" + type + "_office select").change(function() {
        $("#" + type + "_office_id").val($(this).val());
        $("#" + type + "_office_acco input").val("");
        showOpeningHoursAndAcco(type, $(this).val());

        setOffices();
    });
}
function showOpeningHoursAndAcco(type, selected) {
    var $type = $("#" + type + "_office");
    $type.find(".opening_hours ul").hide();
    var $office = $type.find(".opening_hours_" + selected);
    $office.show();
    if ($office.attr("officeType") == "accommdel") {
        $type.find("#" + type + "_office_acco").show();
        $type.find("#" + type + "_office_acco input").bind("blur", validateAccomodation);
    } else {
        $type.find("#" + type + "_office_acco").hide();
        $type.find("#" + type + "_office_acco input").unbind("blur", validateAccomodation);
    }
}

function validateAccomodation() {
    $(this).parent().find("b").css("backgroundColor", this.value == "" ? "#ff0000" : "#00ff00");
}

function setOffices() {
    $("#cart #pickupOffice").html($("#pickup_offices option:selected").html());
    if ($("#pickup_office_id").val() == $("#dropoff_office_id").val()) {
        $("#cart #dropoffOffice").parent().parent().parent().hide();
    } else {
        $("#cart #dropoffOffice").parent().parent().parent().show();
        $("#cart #dropoffOffice").html($("#dropoff_offices option:selected").html());
    }

    /*var data = {
    pickup_office_id: $("#pickup_office_id").val(),
    dropoff_office_id: $("#dropoff_office_id").val(),
    Quote: (quote ? 1 : 0)
    };
    var s = [];
    if ($("#pickup_office .opening_hours_" + data.pickup_office_id).attr("officeType") == "accommdel") {
    data = $.extend(data, {
    pickup_acco_name: $("#pickup_acco_name").val(),
    pickup_acco_address: $("#pickup_acco_address").val(),
    pickup_acco_city: $("#pickup_acco_city").val(),
    pickup_acco_tel: $("#pickup_acco_tel").val()
    });
    if (data.pickup_acco_name == "") s[s.length] = INVALID_PICKUP_ACCO_NAME;
    if (data.pickup_acco_address == "") s[s.length] = INVALID_PICKUP_ACCO_ADDR;
    if (data.pickup_acco_city == "") s[s.length] = INVALID_PICKUP_ACCO_CITY;
    if (data.pickup_acco_tel == "") s[s.length] = INVALID_PICKUP_ACCO_TEL;
    }
    if ($("#dropoff_office .opening_hours_" + data.dropoff_office_id).attr("officeType") == "accommdel") {
    data = $.extend(data, {
    dropoff_acco_name: $("#dropoff_acco_name").val(),
    dropoff_acco_address: $("#dropoff_acco_address").val(),
    dropoff_acco_city: $("#dropoff_acco_city").val(),
    dropoff_acco_tel: $("#dropoff_acco_tel").val()
    });
    if (data.dropoff_acco_name == "") s[s.length] = INVALID_DROPOFF_ACCO_NAME;
    if (data.dropoff_acco_address == "") s[s.length] = INVALID_DROPOFF_ACCO_ADDR;
    if (data.dropoff_acco_city == "") s[s.length] = INVALID_DROPOFF_ACCO_CITY;
    if (data.dropoff_acco_tel == "") s[s.length] = INVALID_DROPOFF_ACCO_TEL;
    }
    if (s.length > 0) {
    //hideWaitingPage();
    alert(s.join("\n"));
    return false;
    }

    showWaitingPage();
    $.ajax({
    url: "/Ajax/SetOffice.ashx",
    data: data,
    cache: false,
    success: function() {
    }, error: function() {
    hideWaitingPage();
    alert("The system might be busy at the moment. Please try again!");
    }
    });*/
}
// end of office

// upgrade car
function upgradeCar(carID) {
    showWaitingPage(QUOTING_PLEASE_WAIT);
    $.ajax({
        url: "/Ajax/UpgradeCar.ashx",
        data: { carID: carID },
        cache: false,
        async: false,
        success: function() {
            window.location.reload(true);
        }, error: function() {
            hideWaitingPage();
        }
    });
}
// end of upgrade car

// cart
var originalPrice = 0.0;
function refreshCart() {
    var before = $("#cart #carprice").html();
    if (originalPrice == 0) originalPrice = before;
    else before = originalPrice;
    var decSep = before.indexOf(",") != -1 ? "," : ".";
    before = parseFloat(before.replace(decSep, "."));
    var after = 0.0;
    $('#cart .options p').remove();
    var $options = $("#options input:checked").not('#option_1000163');
    if ($options.length) {
        $options.each(function () {
            $('<p />', {
                html: $(this).parent().next().text()
            }).appendTo('#cart .options');
            var price = parseFloat($(this).attr("price"));
            if ($(this).attr("prepaid") == "Y")
                before += price;
            else
                after += price;
        });
    } else {
        $('<p />', {
            html: 'Nam augue orci'
        }).appendTo('#cart .options');
    }

    $("#cart #optionsprice").html(after.toFixed(2).replace(".", decSep));
    $("#cart #carprice").html(before.toFixed(2).replace(".", decSep));
    $("#cart #total").html((before + after).toFixed(2).replace(".", decSep));
}
// end of cart

// make reservation
function setupPaymentValidation(msgs) {
    jQuery.validator.addMethod("creditcarddate", function(value, element, param) {
        var year = jQuery(param).val();
        if (value != "--" && year != "----") {
            return isExpiryDate(year, value);
        } else return false;
    }, "");
    jQuery.validator.addMethod("creditcarddateyear", function(value, element, param) {
        var month = jQuery(param).val();
        if (value != "----" && month != "--") {
            return isExpiryDate(value, month);
        } else return false;
    }, "");
    jQuery.validator.addMethod("date3", function(value, element, param) {
        var values = $.map($(element).parent().find("select"), function(n) { return $(n).val(); });
        return (values[0] != "--" && values[1] != "--" && values[2] != "----");
    }, "");
    jQuery.validator.addMethod("phonenumber", function(value, element) {
        var tmpValue = value.replace(/-/g, '');
        tmpValue = tmpValue.replace(/ /g, '');
        return this.optional(element) || (/^[+0-9][0-9][0-9\s\-\.\\\/]+$/.test(tmpValue) && tmpValue > 5);
    }, "");
    jQuery.validator.addMethod("number", function(value, element) { return this.optional(element) || ((value != null) && (value != "") && !isNaN(value) && (value.charAt(0) != " ")) }, "");
    jQuery.validator.addMethod("string", function(value, element) { return this.optional(element) || ((value != null) && (value != "") && isNaN(value) && (value.charAt(0) != " ")) }, "");
    jQuery.validator.addMethod("cvcnumber", function(value, element) {
        return this.optional(element) || ((value.length == 3) && !isNaN(value));
    }, "");
    jQuery.validator.addMethod("payment", function(value, element) {
        return value != "select";
    }, "");
    jQuery.validator.addMethod("validateIf", function(value, element, param) {
        if (!param.test()) return true;
        var validator = $(element.form).validate();
        var valid = true;
        for (var method in param.rules) {
            valid = $.validator.methods[method].call(validator, value, element, param.rules[method]);
            if (!valid) return false;
        }

        return true;
    }, "");

    var validator = $("form:first").validate({
        rules: {
            customer_name: { required: true, string: true },
            customer_initials: { required: true, string: true },
            customer_surname: { required: true, string: true },
            customer_email: { required: $("#travelagent").val() != "1", email: true },
            customer_address: { validateIf: { test: function () { return $("#businesstype_business")[0].checked; }, rules: { required: true, string: true}} },
            customer_city: { validateIf: { test: function () { return $("#businesstype_business")[0].checked; }, rules: { required: true, string: true}} },
            customer_phone: { required: $("#travelagent").val() != "1", phonenumber: true },
            customer_postal: { validateIf: { test: function () { return $("#businesstype_business")[0].checked; }, rules: { required: true, string: true}} },
            //customer_country: { required: true },
            customer_birthdate_day: { date3: true },
            customer_birthdate_month: { date3: true },
            customer_birthdate_year: { date3: true },
            driver_initials: { validateIf: { test: function () { return !$("#customer_is_driver")[0].checked; }, rules: { required: true, string: true}} },
            driver_surname: { validateIf: { test: function () { return !$("#customer_is_driver")[0].checked; }, rules: { required: true, string: true}} },
            driver_birthdate_day: { validateIf: { test: function () { return !$("#customer_is_driver")[0].checked; }, rules: { required: true, date3: true}} },
            driver_birthdate_month: { validateIf: { test: function () { return !$("#customer_is_driver")[0].checked; }, rules: { required: true, date3: true}} },
            driver_birthdate_year: { validateIf: { test: function () { return !$("#customer_is_driver")[0].checked; }, rules: { required: true, date3: true}} },
            payment_method: { payment: true },
            payment_cc_cardtype: { required: true },
            payment_cc_holder: { validateIf: { test: function () { return $("#payment_method").val() == "cc" || $("#payment_method").val() == "cc1"; }, rules: { required: true, string: true}} },
            payment_cc_number: { validateIf: { test: function () { return $("#payment_method").val() == "cc" || $("#payment_method").val() == "cc1"; }, rules: { required: true, creditcard2: "#payment_cc_cardtype"}} },
            payment_cc_expired_month: { validateIf: { test: function () { return $("#payment_method").val() == "cc" || $("#payment_method").val() == "cc1"; }, rules: { required: true, creditcarddate: "#payment_cc_expired_year"}} },
            payment_cc_expired_year: { validateIf: { test: function () { return $("#payment_method").val() == "cc" || $("#payment_method").val() == "cc1"; }, rules: { required: true, creditcarddateyear: "#payment_cc_expired_month"}} },
            payment_cc_cvc: { validateIf: { test: function () { return $("#payment_method").val() == "cc" || $("#payment_method").val() == "cc1"; }, rules: { required: true, cvcnumber: true}} },
            payment_cn_holder: { validateIf: { test: function () { return $("#payment_method").val() == "cn"; }, rules: { required: true, string: true}} },
            payment_cn_number: { validateIf: { test: function () { return $("#payment_method").val() == "cn"; }, rules: { required: true, number: true}} },
            payment_cn_city: { validateIf: { test: function () { return $("#payment_method").val() == "cn"; }, rules: { required: true, string: true}} },
            accept: { required: true }
        }, messages: msgs,
        showErrors: function (el, map) {
            $(this.errorList).each(function () {
                if ($(this.element).parent().find("span.validator").hasClass("valid"))
                    $(this.element).parent().find("span.validator").removeClass("valid");
                $(this.element).parent().find("span.validator").addClass("invalid");
                var section = $(this.element).attr("section");
                update_cart(section, false);
            });
            $(this.successList).each(function () {
                if ($(this).parent().parent().css('display') != 'none') {
                    if ($(this).parent().find("span.validator").hasClass("invalid"))
                        $(this).parent().find("span.validator").removeClass("invalid")
                    $(this).parent().find("span.validator").addClass("valid");
                }
                var section = $(this).attr("section");
                update_cart(section);
            });
        }
    });

    for (var el in validator.settings.rules) {
        $("#" + el).blur(function () {
            $(this).valid();
        });
    }
    $("#accept").click(function() {
        $(this).valid();
    });

    return true;
}

function validateIf(valid, el, rules) {
    if (!valid) return false;

    var validator = $("form:first").validate();
    var value = $(el).val();
    for (var method in rules) {
        valid = $.validator.methods[method].call(validator, value, el, rules[method]);
        if (!valid) return false;
    }

    return true;
}

function validatePayment(quote) {
    if (quote) {
        var validator = $("form:first").validate();
        validator.invalid = {};
        validator.element("#driver_initials");
        validator.element("#driver_surname");
        validator.element("#customer_email");

        var r = true;
        var errors = [];
        for (var field in validator.invalid) {
            r = false;
            errors[errors.length] = validator.settings.messages[field];
        }
        if (!r) {
            alert(errors.join('\n'));
            return false;
        }

        return true;
    } else {
        var validator = $("form:first").validate();
        var r = validator.form();
        if (!r) {
            var errorMsg = $.map(validator.errorList, function(e) { return e.message; });
            errorMsg = $.grep(errorMsg, function(n) { return n != ''; });
            alert(errorMsg.join('\n'));
        }

        return r;
    }
}

// refresh validation status in the cart
function update_cart(section, valid) {
    if (typeof section == "undefined" || section == "") {
        return;
    }

//    if (typeof valid != "undefined" && !valid) {
//        $("#cart ." + section + " .status")
//            .addClass("incomplete")
//            .html(SECTION_IMCOMPLETE);
//        return;
//    }

    var valid = true;
    $("#bookingform input, #bookingform select, #bookingform textarea").filter("[section=" + section + "]").each(function() {
        if ($(this).attr("section") != section) return true;

        var validator = $(this).parent().find("span.validator");
        if (validator.length) {
            if (!validator.hasClass("valid")) {
                valid = false;
                return false;
            }
        }
    });

    // if driver is same as customer, use the validation result of customer block
    if (section == "customer") section = "driver";
    if (valid) {
        $("#cart ." + section + " .status").removeClass("incomplete").addClass("complete").html(SECTION_COMPLETE);
    } else {
        $("#cart ." + section + " .status").removeClass("complete").addClass("incomplete").html(SECTION_IMCOMPLETE);
    }

    update_payment_status();
}

function update_payment_status() {
     //check payment method
     /*if ($("#payment_method").val() == "cc") {
         $('#cart #payment_fee').show();
        //check for credit card
         var valid = true;
         var validator = $("#payment_method_cc").find("span.validator");
         if (validator.length) {
             for (var i = 1; i < validator.length; i++) {
                 if (!(validator[i].className.indexOf("validator valid") > -1)) {
                     valid = false;
                     break;
                 }
             }
         }
         if (valid) {
             $("#cart .payment .status").removeClass("incomplete").addClass("complete");
                //.html('<span class="type">creditcard fee&nbsp;</span>' + $('#option_1000163').parent().parent().find('span.alignright').html());
         } else {
             $("#cart .payment .status").removeClass("complete").addClass("incomplete").html(SECTION_IMCOMPLETE);
         }
     } else {
         $('#cart #payment_fee').hide();
         var valid = $("#payment_method").val() == "tr";
         if (valid) {
            $("#cart .payment .status").removeClass("incomplete").addClass("complete").html(SECTION_COMPLETE);
         } else {
             $("#cart .payment .status").removeClass("complete").addClass("incomplete").html(SECTION_IMCOMPLETE);
         }
     }*/
}

function display_payment_method() {
    var country = $("#customer_country").val();
    if (country != "NL") {
        // remove cn and tr
        $("#payment_method option[value=cn], #payment_method option[value=tr]").remove();
    } else {
        if (!$("#payment_method option[value=cn]").length) {
            $("#payment_method").append(document.payment_methods["cn"]);
        }
        if (!$("#payment_method option[value=tr]").length && typeof document.payment_methods["tr"] != "undefined") {
            $("#payment_method").append(document.payment_methods["tr"]);
        }
    }

    var type = $("#payment_method").val();
    $("#payment_info div[id^='payment_method_']").hide();
    $("#payment_info div[id='payment_method_" + (type == "cc1" ? "cc" : type) + "']").show();
    $("#payment_tooltip").html($("#payment_method option:selected").attr("tooltip"));

    if (type == "cc" || type == "cc1") {
        // add the credit card option
        $.get("/Ajax/UpdateOption.ashx?id=1000163&checked=1&r=" + Math.random());
        $("#option_1000163")[0].checked = true;
        //$("#option_1000163").parent().parent().show();
    } else {
        $.get("/Ajax/UpdateOption.ashx?id=1000163&checked=0&r=" + Math.random());
        $("#option_1000163")[0].checked = false;
        //$("#option_1000163").parent().parent().hide();
    }

    refreshCart();
}

function validationAccommodation() 
{
    var s = [];
    var data;
    if (typeof $("#pickup_office_acco") != "undefined" && $("#pickup_office_acco").css("display") == "block") {
        data = $.extend(data, {
            pickup_acco_name: $("#pickup_acco_name").val(),
            pickup_acco_address: $("#pickup_acco_address").val(),
            pickup_acco_city: $("#pickup_acco_city").val(),
            pickup_acco_tel: $("#pickup_acco_tel").val()
        });
        if (data.pickup_acco_name == "") s[s.length] = INVALID_PICKUP_ACCO_NAME;
        if (data.pickup_acco_address == "") s[s.length] = INVALID_PICKUP_ACCO_ADDR;
        if (data.pickup_acco_city == "") s[s.length] = INVALID_PICKUP_ACCO_CITY;
        if (data.pickup_acco_tel == "" || !/^[+0-9][0-9][0-9\s\-\.\\\/]+$/.test(data.pickup_acco_tel.replace(/-/g, '').replace(/ /g, ''))) s[s.length] = INVALID_PICKUP_ACCO_TEL;
    }
    if (typeof $("#dropoff_office_acco") != "undefined" && $("#dropoff_office_acco").css("display") == "block" &&
        typeof $("#dropoff_office") != "undefined" && $("#dropoff_office").css("display") == "block") {
        data = $.extend(data, {
            dropoff_acco_name: $("#dropoff_acco_name").val(),
            dropoff_acco_address: $("#dropoff_acco_address").val(),
            dropoff_acco_city: $("#dropoff_acco_city").val(),
            dropoff_acco_tel: $("#dropoff_acco_tel").val()
        });
        if (data.dropoff_acco_name == "") s[s.length] = INVALID_DROPOFF_ACCO_NAME;
        if (data.dropoff_acco_address == "") s[s.length] = INVALID_DROPOFF_ACCO_ADDR;
        if (data.dropoff_acco_city == "") s[s.length] = INVALID_DROPOFF_ACCO_CITY;
        if (data.dropoff_acco_tel == "" || !/^[+0-9][0-9][0-9\s\-\.\\\/]+$/.test(data.dropoff_acco_tel.replace(/-/g, '').replace(/ /g, ''))) s[s.length] = INVALID_DROPOFF_ACCO_TEL;
    }
    if (s.length > 0) {
        //hideWaitingPage();
        alert(s.join("\n"));
        return false;
    }
    return true;
}

function recalculate() {
    showWaitingPage(PROCESSING_PLEASE_WAIT);
    var a = $("#bookingform").find("input, select, textarea").serializeArray();
    var s = {};
    $.each(a, function () {
        s[this.name] = (this.value == "(Optional)" || this.value == "(Optioneel)") ? "" : this.value;
    });
    s['recalculate'] = 1;
    $.ajax({
        url: "/Ajax/SaveCart.ashx",
        cache: false,
        type: "POST",
        data: s,
        complete: function () {
            window.location.reload();
        }
    });
}

function checkout(finalize) {
    addEmail4TravelAgent();
    if (!validationAccommodation()) return false;
    if (!validatePayment()) return false;
    if (document.getElementById("subscribe") != null && document.getElementById("subscribe").checked) {
        // subscribe newsletters
        // 138 is the Dutch newsletters of BusinessCars
        // TODO: should be retrieved somewhere
        $.ajax({
            url: "/Ajax/SubscribeNewsletters.ashx",
            data: { newslettersID: document.getElementById("subscribe").value, email: document.getElementById("customer_email").value },
            type: "GET"
        });
    }
    showWaitingPage(PROCESSING_PLEASE_WAIT);
    var a = $("#bookingform").find("input, select, textarea").serializeArray();
    var s = {};
    $.each(a, function() {
        s[this.name] = (this.value == "(Optional)" || this.value == "(Optioneel)") ? "" : this.value;
    });
    var settings = {
        url: "/Ajax/SaveCart.ashx",
        cache: false,
        type: "POST",
        data: s
    };
    if (finalize) {
        settings = $.extend(settings, { success: function () {
            $.ajax({
                url: "/Ajax/Checkout.ashx",
                cache: false,
                success: function () {
                    if ($("#Quote").val() == "1")
                        window.location = "/Thankyou-quote.aspx";
                    else if ($('input:checked[name = "payment_method"]').val() == 'tr')
                        window.location = "/Thankyou.aspx";
                    else
                        window.location = "/ogone.aspx";
                }, error: function (e) {
                    hideWaitingPage();
                    alert(e.statusText);
                }
            });
        }
        });
    }

    $.ajax(settings);

    return false;
}
// end of make reservation
function lang(language) {
    showWaitingPage();
    
    var url = window.location.pathname;
    var rewrite = /^\/(en|nl)\//i.test(url);
    if (!rewrite) {
        if (url == '' || url == '/') return redirect('/' + language + '/');
        if (url.indexOf('.aspx') != -1) {
            var temp = url.replace(/[\?&]language=\w{2}/, "");
            return redirect(temp + (temp.indexOf('?') >= 0 ? '&' : '?') + 'language=' + language);
        }

        var q = url.replace(/[\?&]language=\w{2}/, '');
        return redirect(q.substring(0, q.lastIndexOf('/')) + '/' + language + q.substring(q.lastIndexOf('/')));
    }

    var car = url == '/nl/autoverhuur/' || url == '/en/car-rental/';
    if (car) {
        url = url.replace(language == 'en' ? '/nl/autoverhuur/' : '/en/car-rental/', language == 'en' ? '/en/car-rental/' : '/nl/autoverhuur/');
        return redirect(url);
    }

    var van = url == '/nl/busje-huren/' || url == '/en/van-hire/';
    if (van) {
        url = url.replace(language == 'en' ? '/nl/busje-huren/' : '/en/van-hire/', language == 'en' ? '/en/van-hire/' : '/nl/busje-huren/');
        return redirect(url);
    }

    var page = url.indexOf('/nl/pagina-') == 0 || url.indexOf('/en/page-') == 0;
    if (page) {
        url = url.replace(language == 'en' ? '/nl/pagina-' : '/en/page-', language == 'en' ? '/en/page-' : '/nl/pagina-');
        return redirect(url);
    }

    var supplier = url.indexOf('/nl/autoverhuurpartner-') == 0 || url.indexOf('/en/car-rental-supplier-') == 0;
    if (supplier) {
        url = url.replace(language == 'en' ? '/nl/autoverhuurpartner-' : '/en/car-rental-supplier-', language == 'en' ? '/en/car-rental-supplier-' : '/nl/autoverhuurpartner-');
        return redirect(url);
    }

    return redirect('/' + language + '/');
}
function redirect(url) {
    if ($.browser.msie && url.length <= 4) {
        window.location.href = url + '?_=' + Math.random();
    } else {
        window.location.href = url;
    }
    return false;
}
function changeLanguage(language) {
    lang(language);
}
function changeCurrency() {
    showWaitingPage();
    $.ajax({
        url: "/Ajax/SetVar.ashx?currency=" + $("#currencies").val(),
        type: "GET",
        async: false,
        cache: false,
        success: function() {
            window.location = window.location.href; //.reload(true);
        }
    });
}

function daysInMonth(month, year) {
    var m = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    if (month != 2) return m[month - 1];
    if (year % 4 != 0) return m[1];
    if (year % 100 == 0 && year % 400 != 0) return m[1];
    return m[1] + 1;
} 

function validateDaysInMonth(name)
{
    var monthYear = $("#" + name + "MonthYear").val().split('-');
    var maxDayOfMonth = daysInMonth(parseInt(monthYear[0], 10),parseInt(monthYear[1], 10));
    if (parseInt($("#" + name + "Day").val(), 10) > maxDayOfMonth)
            $("#"+name+"Day").val(maxDayOfMonth);
}

