﻿function changeCurrency() {
    showWaitingPage();
    $.ajax({
        url: "/Ajax/SetVar.ashx?currency=" + $("#currencies").val(),
        type: "GET",
        async: false,
        cache: false,
        success: function() {
            window.location.reload(true);
        }
    });
}

function searchCars() {
    if (!validateSearch()) return false;

    showWaitingPage(SEARCHING_PLEASE_WAIT);
    var a = $("#searchcar input, #searchcar 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");
            window.top.location = "/select.aspx";
        }, error: function() {
            //window.parent.location = "/select.aspx?" + s.join("&").replace(/%20/g, "+");
            //window.open("/select.aspx?" + s.join("&").replace(/%20/g, "+"));
            window.top.location = "/select.aspx?" + s.join("&").replace(/%20/g, "+");
        }
    });

    return false;
}

function book(carid) {
    showWaitingPage(BOOKING_PLEASE_WAIT);
    $.ajax({
        url: "/Ajax/AddToCart.ashx",
        data: { carid: carid },
        cache: false,
        success: function() {
            window.location = (useSSL ? "https://" : "http://") + window.location.host + "/book.aspx";
        }, error: function() {
            hideWaitingPage();
            //alert("Could not find the selected car");
            searchCars();
        }
    });
}

function payment(quote) {
    showWaitingPage(CREATING_PLEASE_WAIT);
    
    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;
    }
    
    $.ajax({
        url: "/Ajax/SetOffice.ashx",
        data: data,
        cache: false,
        success: function() {
            window.location = "/Payment.aspx";
        }, error: function() {
            hideWaitingPage();
            alert("The system might be busy at the moment. Please try again!");
        }
    });

    return false;
}

function checkquote() {
    if (!validatePayment(true)) return false;

    showWaitingPage(PROCESSING_PLEASE_WAIT);
    $("#confirm #Quote").val(1);
    var a = $("#confirm").find("input, select, textarea").serializeArray();
    var s = {};
	$.each(a, function(){
	    s[this.name] = this.value;
	});
	
    $.ajax({
        url: "/Ajax/SaveCart.ashx",
        cache: false,
        method: "POST",
        data: s,
        success: function() {
            $.ajax({
	            url: "/Ajax/Checkout.ashx",
	            cache: false,
	            success: function() {
	                window.location = "/thankyou.aspx";
	            }, error: function(e) {
	                hideWaitingPage();
	                alert(e.statusText);
	            }
	        });
        }, error: function(e) {
            hideWaitingPage();
            alert(e.statusText);
        }
    });
    
    return false;
}

function checkout(finalize) {
    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 },
            method: "GET"
        });
    }

    showWaitingPage(PROCESSING_PLEASE_WAIT);

    var a = $("#confirm").find("input, select, textarea").serializeArray();
    var s = {};
	$.each(a, function(){
	    s[this.name] = this.value;
	});
	var settings = {
	    url: "/Ajax/SaveCart.ashx",
	    cache: false,
        method: "POST",
        data: s
	};
	if (finalize) {
	    settings = $.extend(settings, { success: function() {
	        $.ajax({
	            url: "/Ajax/Checkout.ashx",
	            cache: false,
	            success: function() {
	                window.location = "/thankyou.aspx";
	            }, error: function(e) {
	                hideWaitingPage();
	                alert(e.statusText);
	            }
	        });
	    }});
	}
	
    $.ajax(settings);
    
    return false;
}

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 .office");
                var $div = $("#dropoff_office .opening_hours");

                if ($offices.length == 1) {
                    $ddl.html($($offices[0]).attr("Description"));
                } 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>");
                    });

                    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>" + $(this).attr("StartTime") + " - " + $(this).attr("CloseTime") + "</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");
    }
}

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();
        }
    });
}

function refreshCart() {
    // get product option selection in the step 3
    var before = parseFloat($("#cart #cart_car_price").find(".price").html());
    var after = 0.0;
    var $excl = $("#cart_excl");
    $excl.empty();
    var $incl = $("#cart_incl");
    $incl.empty();
    $("#excl input:checked").each(function() {
        var priceHtml = $(this).parent().find(".price").html();
        var price = parseFloat(priceHtml);
        if ($(this).attr("prepaid") == "Y") {
            before += price;
            $excl.append("<p class=\"pricebk\"><span class=\"span_left\">" + $(this).next().html() + "</span><span class=\"span_rig\">" + CURRENCY_SYMBOL + " " + priceHtml + "</span></p>");
        }
        else {
            after += price;
            $incl.append("<p class=\"pricebk\"><span class=\"span_left\">" + $(this).next().html() + "</span><span class=\"span_rig\">" + CURRENCY_SYMBOL + " " + priceHtml + "</span></p>");
        }
    });
    $("#cart #cart_price_before").find(".price").html(before.toFixed(2));
    $("#cart #cart_price_after").find(".price").html(after.toFixed(2));
    $("#cart #cart_price_total").find(".price").html((before + after).toFixed(2));
}

function updateCart() {
    // refresh the calculation
    var before = parseFloat($("#cart #cart_car_price").find(".price").html());
    var after = 0.0;
    var $excl = $("#cart_excl");
    var $incl = $("#cart_incl");
    $("#cart_excl p.pricebk").each(function() {
        if ($(this).css("display") == "none") return true;
        
        var priceHtml = $(this).find(".price").html();
        var price = parseFloat(priceHtml);
        before += price;
    });
    $("#cart_incl p.pricebk").each(function() {
        if ($(this).css("display") == "none") return true;
        
        var priceHtml = $(this).find(".price").html();
        var price = parseFloat(priceHtml);
        after += price;
    });
    $("#cart #cart_price_before").find(".price").html(before.toFixed(2));
    $("#cart #cart_price_after").find(".price").html(after.toFixed(2));
    $("#cart #cart_price_total").find(".price").html((before + after).toFixed(2));
}

function bindOfficeEvents(type) {
    $("#" + type + "_office .office select").change(function() {
        $("#" + type + "_office_id").val($(this).val());
        $("#" + type + "_office_acco input").val("");
        showOpeningHoursAndAcco(type, $(this).val());
    });
}
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");
}

// validate the step 1 and 2
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);
}

// validate the step 4
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;
    }
}

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("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("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: true, email: true },
            customer_address: { required: true, string: true },
            customer_city: { required: true, string: true },
            customer_phone: { required: true, phonenumber: true },
            customer_postal: { required: 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_type: { required: true },
            payment_cc_cardtype: { required: true },
            payment_cc_holder: { validateIf: { test: function() { return $("#payment_type_cc")[0].checked; }, rules: { required: true, string: true } } },
            payment_cc_number: { validateIf: { test: function() { return $("#payment_type_cc")[0].checked; }, rules: { required: true, creditcard2: "#payment_cc_cardtype" } } },
            payment_cc_expired_month: { validateIf: { test: function() { return $("#payment_type_cc")[0].checked; }, rules: { required: true, creditcarddate: "#payment_cc_expired_year" } } },
            payment_cc_cvc: { validateIf: { test: function() { return $("#payment_type_cc")[0].checked; }, rules: { required: true , cvcnumber: true } } },
            payment_cn_holder: { validateIf: { test: function() { return $("#payment_type_cn")[0].checked; }, rules: { required: true, string: true } } },
            payment_cn_number: { validateIf: { test: function() { return $("#payment_type_cn")[0].checked; }, rules: { required: true, number: true } } },
            payment_cn_city: { validateIf: { test: function() { return $("#payment_type_cn")[0].checked; }, rules: { required: true, string: true } } },
            accept: { required: true }
        }, messages: msgs,
           showErrors: function(el, map) {
            $(this.errorList).each(function() {
                if (this.element.id == "accept") {
                    $(this.element).parent().find("img").attr("src", "/images/check3.gif");
                } else {
                    $(this.element).parent().find("b.icon").css("backgroundColor", "#ff0000");
                }
            });
            $(this.successList).each(function() {
                if (this.id == "accept") {
                    $(this).parent().find("img").attr("src", "/images/check2.gif");
                } else {
                    $(this).parent().find("b.icon").css("backgroundColor", "#41ac17");
                }
            });
        }
    });
    
    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 login() {
    $.blockUI({ message: $("#loginform"), css: { width: '390px' } }, baseZ: 9000);
}

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;
}

// 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);
    });
}

function showWaitingPage(msg) {
    if (typeof msg != "undefined") {
        $("#waitingPage .waitingText").html(msg);
    }

    $.blockUI({message: $("#waitingPage"), css: { width: '390px' }, baseZ: 9000});
}

function hideWaitingPage() {
    $.unblockUI();
}

function lang(language) {
    showWaitingPage();
    var rewrite = /^\/(en|nl)\//i.test(window.location.pathname);
    if (rewrite)
    {
        var landing = window.location.pathname.indexOf("autoverhuur") != -1 || window.location.pathname.indexOf("car-rental") != -1;
        if (landing) {
            window.location = "/?language=" + language;
        } else {
            window.location = "/" + language + window.location.pathname.substring(3);
        }
    }
    else
    {
        var q = window.location.href.replace(/[\?&]language=\w{2}/, "");
        window.location = q + (q.indexOf('?') >= 0 ? '&' : '?') + "language=" + language;
    }
}

function customRange(input) {
    return {
           minDate: (input.id == "DropoffDate" ? max($("#PickupDate").datepicker("getDate"), new Date()) : new Date()),
           maxDate: (input.id == "PickupDate" ? null : null)
    };
}

function setDateTime(date, input) {
    if (input.id != "PickupDate") return false;
    
    // add 7 days
    var d = new Date(input.selectedYear, input.selectedMonth, input.selectedDay);
    d.setDate(d.getDate() + 7);
    var inst = $.datepicker._getInst(document.getElementById("DropoffDate"));
    $.datepicker._setDate(inst, d);
}

function getMaxDayInMonth(month, year) {
    switch(month) {
        case 2: return 28 + ((year % 4 == 0) && (year % 100 != 0) ? 1 : 0);
        case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31;
        default: return 30;
    }
}

function onMonthYearChange(element, value) {
    // refresh the day dropdown based on the month and year
    value = value.split('-');
    var month = parseInt(value[0], 10);
    var year = parseInt(value[1], 10);
    var max = getMaxDayInMonth(month, year);
    var id = element[0].id.substr(0, element[0].id.indexOf('MonthYear'));
    var $target = $("#" + id + "Day");
    // do not need to refresh the dropdown
    if ($target.children().length < max) {
        var selected = $target.val();
        var p;
        $target.empty();
        for(var i = 1; i <= max; i++) {
            p = pad(i);
            $target.append("<option value=\""+p+"\""+(selected==p?" selected=\"selected\"":"")+">" + p + "</option>");
        }
    }
    
    if (id == "Pickup") {
        var dropoffDate = new Date(year, month - 1, parseInt($("#PickupDay").val(), 10) + 7);
        setDropoffDate(dropoffDate);
    }
}

function onDayChange(element, value) {
    var id = element[0].id.substr(0, element[0].id.indexOf('Day'));
    if (id == "Pickup") {
        var dropoffDate = $("#PickupMonthYear").val().split('-');
        dropoffDate = new Date(parseInt(dropoffDate[1], 10), parseInt(dropoffDate[0], 10) - 1, parseInt(value, 10) + 7);
        setDropoffDate(dropoffDate);
    }
}

function setDropoffDate(dropoffDate) {
    $("#DropoffDay").val(pad(dropoffDate.getDate()));
    $("#DropoffMonthYear").val(pad(dropoffDate.getMonth() + 1) + "-" + dropoffDate.getFullYear());
}

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;
}

function keepAlive() {
    $.get("/Ajax/KeepAlive.ashx?r=" + Math.random());
    window.setTimeout("keepAlive()", 60000);
}

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 changePhonePrefix(input, prefix) {
    if (input.value.length == 0) {
        input.value = '+' + prefix;
    } else if (input.value.charAt(0) == '+' && input.value.length >= prefix.length) {
        input.value = '+' + prefix + input.value.substr(prefix.length + 1);
    }
}

// for 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, groupText],
        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],
            value: row[0],
            result: row[2]
        };
    }
}
// end of autocomplete
