// DAH - JS
// Mansoor Malik
// unminified

//jquery & jquery tools
function BindEvents() {
    $(document).ready(function () {

        // Product Information Box
        $('img.prodInfo').overlay({
            mask: {
                color: '#eee',
                loadSpeed: 100,
                opacity: 0.6
            },
            fixed: false,
            closeOnClick: false,
            onBeforeLoad: function () {
                var id = "#" + this.getTrigger().attr('id');
                var href = $(id).attr("subject");
                var pk = "PickupDepot_" + getParameterByName("p", href);
                var p = $('select[name="' + pk + '"]').val();
                if (p == "0") {
                    alert("Please select Pick-up location first to view Information");
                    return false;
                }
                href += p;
                document.getElementById("iframeRB").src = href;
            },
            onClose: function () {
                document.getElementById("iframeRB").src = "loading.htm";
            }
        });

        // Select Car (loads terms and conditions)
        $('img.selectCar').overlay({
            mask: {
                color: '#eee',
                loadSpeed: 100,
                opacity: 0.6
            },
            fixed: false,
            closeOnClick: false,
            onBeforeLoad: function () {
                var id = "#" + this.getTrigger().attr('id');
                var href = $(id).attr("subject");
                var driverAge = document.getElementById('tbxdriverAge').value;
                var minage = getParameterByName("minAge", href);
                var maxage = getParameterByName("maxAge", href);
                if ((driverAge < minage) || (driverAge > maxage)) {
                    alert("The selected car has a minimum age of " + minage + " and a maximum age of " + maxage);
                    return false;
                }
                //alert("DriverAge: " + driverAge + "\nMinAge: " + minage + "\nMaxAge: " + maxage);
                var supp = getParameterByName("supp", href);
                var sipp = getParameterByName("s", href);
                var pid = getParameterByName("pid", href);
                var pk = "PickupDepot_" + pid;
                var dr = "DropoffDepot_" + pid;
                var p = $('select[name="' + pk + '"]').val();
                var d = $('select[name="' + dr + '"]').val();
                var err = "";
                if ((p == "0") || (d == "0"))
                    err = "Please select Pick-up and Drop-off location";
                if ((p.indexOf("-1:") != -1) || (d.indexOf("-1:") != -1))
                    err = "The selected Depot is closed";
                if (err != "") {
                    alert(err);
                    return false;
                }
                var suppMsg = supplierMsg(supp, sipp);
                if (!suppMsg) { return false; }
                href += "&p=" + p + "&d=" + d;
                document.getElementById("tbxsipp").value = sipp;
                document.getElementById("tbxpkdp").value = p;
                document.getElementById("tbxdrdp").value = d;
                document.getElementById("tbxproductid").value = pid;
                document.getElementById("iframeTC").src = href;
            },
            onClose: function () {
                document.getElementById("iframeTC").src = "loading.htm";
                document.getElementById("termsButtons").style.display = "none";
                document.getElementById("chkterms").checked = false;
            }
        });

        // show terms and conditions buttons
        $('iframe.termsFrame').load(function () {
            var iframesrc = this.src;
            if (iframesrc.indexOf("termsandconditions.aspx") != -1)
                document.getElementById("termsButtons").style.display = "block";
        });

        // Inclusions
        $('img.inclusions').overlay({
            mask: {
                color: '#eee',
                loadSpeed: 100,
                opacity: 0.6
            },
            fixed: false,
            closeOnClick: false,
            onBeforeLoad: function () {
                var id = "#" + this.getTrigger().attr('id');
                var href = $(id).attr("subject");
                var pk = "PickupDepot_" + getParameterByName("pid", href);
                var dr = "DropoffDepot_" + getParameterByName("pid", href);
                var p = $('select[name="' + pk + '"]').val();
                var d = $('select[name="' + dr + '"]').val();
                var err = "";
                if ((p == "0") || (d == "0"))
                    err = "Please select Pick-up and Drop-off location";
                if (err != "") {
                    alert(err);
                    return false;
                }
                href += "&p=" + p + "&d=" + d;
                document.getElementById("iframeRB").src = href;
            },
            onClose: function () {
                document.getElementById("iframeRB").src = "loading.htm";
            }
        });


        // Depot Information Box
        $('img.pkDepot').overlay({
            mask: {
                color: '#eee',
                loadSpeed: 100,
                opacity: 0.6
            },
            fixed: false,
            closeOnClick: true,
            onBeforeLoad: function () {
                var id = "#" + this.getTrigger().attr('id');
                var href = $(id).attr("subject");
                var pk = "PickupDepot_" + getParameterByName("p", href);
                var p = $('select[name="' + pk + '"]').val();
                if (p == "0") {
                    alert("Please select Pick-up location first to view Information");
                    return false;
                }
                href += p;
                document.getElementById("iframeCar").src = href;
            },
            onClose: function () {
                document.getElementById("iframeCar").src = "loading.htm";
            }
        });
        $('img.doDepot').overlay({
            mask: {
                color: '#eee',
                loadSpeed: 100,
                opacity: 0.6
            },
            fixed: false,
            closeOnClick: true,
            onBeforeLoad: function () {
                var id = "#" + this.getTrigger().attr('id');
                var href = $(id).attr("subject");
                var pk = "DropoffDepot_" + getParameterByName("p", href);
                var p = $('select[name="' + pk + '"]').val();
                if (p == "0") {
                    alert("Please select Drop-off location first to view Information");
                    return false;
                }
                href += p;
                document.getElementById("iframeCar").src = href;
                //                var wrap = this.getOverlay().find("div.contentWrap");
                //                wrap.load(href);
            },
            onClose: function () {
                document.getElementById("iframeCar").src = "loading.htm";
            }
        });

        // Car Information Box
        $("a[rel]").overlay({
            mask: {
                color: '#eee',
                loadSpeed: 100,
                opacity: 0.6
            },
            fixed: false,
            closeOnClick: true,
            onBeforeLoad: function () {
                document.getElementById("iframeCar").src = this.getTrigger().attr("href");
                //              var wrap = this.getOverlay().find("div.contentWrap");
                //              wrap.load(this.getTrigger().attr("href"));
            },
            onClose: function () {
                document.getElementById("iframeCar").src = "loading.htm";
            }
        });

        //busybox Overlay
        $('div.busybox').overlay({
            mask: {
                color: '#eee',
                loadSpeed: 100,
                opacity: 0.6
            },
            left: "center",
            top: "center",
            fixed: true,
            closeOnClick: false,
            target: "#busybox"
        });

    });

}

// used on the page 'select'. gets the supplier msg
function supplierMsg(Supplier, SIPPCode) {
    var str;
    if (Supplier == "PGT") {
        str = "To qualify for a Peugeot Lease, the contracted driver must meet all the following criteria:\n\n"
        str += "They must;\n"
        str += "- Reside outside of the European Union.\n"
        str += "- Stay in the European Union for no more than 185 days in any consecutive 12 month period.\n"
        str += "- Not carry out any activity for gain during your stay (No working Visa's allowed).\n"
        str += "- Must be an Australian Resident.\n"
        str += "- Minimum age to be 18 years with a full Australian driver's license (provisional license not accepted).\n\n"
        str += "If the contracted driver qualifies to do a Peugeot Lease, select 'OK'.\n\n"
        str += "If the contracted driver does not qualify, please select 'Cancel' and choose a rental vehicle.\n"
        return confirm(str);
    }
    if (Supplier == "RTZWK") {
        str = "To qualify for the Weekend Special Rate, the booking must meet the following criteria:\n\n"
        str += "- Pick up: Must be between 12pm Thursday and 12pm Sunday.\n"
        str += "- Drop off: Must be before 12pm Monday.\n"
        str += "- Pick up & Drop off must be at the same location. No one way rentals permitted.\n\n"
        str += "Participating Locations:\n"
        str += "Sydney Airport, Melbourne Airport, Brisbane Airport, Adelaide Airport, Coolangatta Airport, Maroochydore Airport, Canberra Airport.\n\n"
        str += "If the booking qualifies for the Weekend Special Rate, select 'OK'.\n\n"
        str += "If the booking does not qualify, please select 'Cancel' and choose another vehicle.\n"
        return confirm(str);
    }
    if ((Supplier == "THT") && (document.getElementById("hdncountrycode").value == "AU")) {
        if (document.getElementById("hdnpucity").value == "ADELAIDE") {
            if (SIPPCode == "ECMRAPOW" || SIPPCode == "CCARAPOW" || SIPPCode == "ICARAPOW" || SIPPCode == "IWARAPOW" || SIPPCode == "FCARAPOW" || SIPPCode == "ECMRDTOW" || SIPPCode == "CCARDTOW" || SIPPCode == "ICARDTOW" || SIPPCode == "IWARDTOW" || SIPPCode == "FCARDTOW") {
                str = "To qualify for the Relocation Special Rate, the booking must meet the following criteria:\n\n"
                str += "- Pick Up: Adelaide Airport, City or Adelaide North ONLY\n"
                str += "- Drop Off: Cairns Airport or City ONLY\n"
                str += "- Maximum 10 days rental.\n\n"
                str += "Note: No one way fees applicable on this Special Rate, regardless of duration.\n"
                str += "If the booking qualifies for the Relocation Special Rate, select 'OK'.\n\n"
                str += "If the booking does not qualify, please select 'Cancel' and choose another vehicle.\n"
                return confirm(str);
            }
        }
    }
    if (Supplier == "THTWK") {
        str = "To qualify for the Weekend Special Rate, the booking must meet the following criteria:\n\n"
        str += "- Pick up: Must be between 12pm Thursday and 12pm Sunday.\n"
        str += "- Drop off: Must be before 12pm Monday.\n"
        str += "- One way rentals are permitted between participating locations.\n\n"
        str += "Participating Locations:\n"
        str += "Sydney Airport, Melbourne Airport, Adelaide Airport, Canberra Airport.\n\n"
        str += "If the booking qualifies for the Weekend Special Rate, select 'OK'.\n\n"
        str += "If the booking does not qualify, please select 'Cancel' and choose another vehicle.\n"
        return confirm(str);
    }
    return true;
}

// common:
function numOnly(e){
var key;var tf;
if (window.event) // IE 
key = e.keyCode;
else if (e.which) // Netscape/Firefox/Opera
key = e.which;
if ((key > 47 && key < 58) || (key == 8) || (e.keyCode == 9)) return true;
else return false;}
function alphabetOnly(e){
var key;var tf;
if (window.event) key = e.keyCode;
else if (e.which) key = e.which;
if (((key > 64 && key < 91) || (key > 96 && key < 123)) || (key == 8) || (key == 32) || (e.keyCode == 9) || (e.keyCode > 34 && e.keyCode < 41) || (e.keyCode == 46)) return true; else return false;}
function namesCheck(e) {
var key; var tf;
if (window.event) key = e.keyCode;
else if (e.which) key = e.which;
if(((key > 64 && key < 91) || (key > 96 && key < 123)) || (key == 8) || (key == 32) || (key == 46) || (key == 45) || (key == 39) || (e.keyCode == 9) || (e.keyCode == 39) || (e.keyCode == 46)) return true; else return false;}


/** booking engine stuff::::: **/
function changeCityList() {
    var chkloc = document.getElementById('chkloc');
    var pcountry = document.getElementById('ddlPickupCountry');
    var dcountry = document.getElementById('ddlDropoffCountry');
    var dcity = document.getElementById('ddlDropoffCity');
    var pcity = document.getElementById('ddlPickupCity');
    if ((chkloc.checked) && (pcountry.value == dcountry.value))
        dcity.value = pcity.value;
    document.getElementById('hdnPcity').value = pcity.value;
    document.getElementById('hdnDcity').value = dcity.value;
}
function chkObject(){if ((document.getElementById("ddlPickupCountry")==null) || (document.getElementById("ddlDropoffCountry")==null) || (document.getElementById("ddlPickupCity")==null) || (document.getElementById("ddlDropoffCity")==null)) return false;else return true;}

function PKCityList(country) {
    var selectedCountry = country.options[country.selectedIndex].value;
    var chkloc = document.getElementById('chkloc');
    var pcountry = document.getElementById('ddlPickupCountry');
    var dcountry = document.getElementById('ddlDropoffCountry');
    var dcity = document.getElementById('ddlDropoffCity');
    var pcity = document.getElementById('ddlPickupCity');
    if (chkloc.checked)
        dcountry.value = selectedCountry;
    cbLocations.Callback(selectedCountry);
}

function DRCityList(drCountry) {
    var pkCountry = document.getElementById("ddlPickupCountry");
    var pk_selectedCountry = pkCountry.options[pkCountry.selectedIndex].value;
    var dr_selectedCountry = drCountry.options[drCountry.selectedIndex].value;
    var pk_selectedCity;
    if (document.getElementById("ddlPickupCity").options.length > 0) {
        var pkCity = document.getElementById("ddlPickupCity");
        pk_selectedCity = pkCity.options[pkCity.selectedIndex].value;
    }
    else
        pk_selectedCity = "";
    var dr_selectedCity;
    if (document.getElementById("ddlDropoffCity").options.length > 0) {
        var drCity = document.getElementById("ddlDropoffCity");
        dr_selectedCity = drCity.options[drCity.selectedIndex].value;
    }
    else
        dr_selectedCity = "";
    var str = pk_selectedCountry + ":" + dr_selectedCountry + ":" + pk_selectedCity + ":" + dr_selectedCity;
    cbLocations.Callback(str);
}


function showLocation(objSender, objBlockName) {
if (objSender.checked) {
    if (document.getElementById(objBlockName)!=null)
        document.getElementById(objBlockName).style.display = "none";
}
else {
    if (document.getElementById(objBlockName) != null)
        document.getElementById(objBlockName).style.display = "block";
}
document.getElementById("ddlDropoffCity").selectedIndex = document.getElementById("ddlPickupCity").selectedIndex;
}


function get24HrTime(time, ampm){
var timesplit = time.split(":", 2);
var newtime = new Array();
var hour;
if ((ampm == "PM")) {
    hour = parseInt(timesplit[0]) + 12;
    newtime[0] = hour;
}
else
    newtime[0] = timesplit[0];
newtime[1] = timesplit[1];
return newtime;
}

function checkPickUpTime() {
var currentDate = new Date();
var selectedDate = new Date();
selectedDate = PickerFrom.GetSelectedDate();
var ddlPUtm = document.getElementById("ddlPUtm");
var selectedTime = ddlPUtm.options[ddlPUtm.selectedIndex].value;
selectedTime = get24HrTime(selectedTime.substring(0, selectedTime.length - 3), selectedTime.substring(selectedTime.length - 2, selectedTime.length));
var currentTime = currentDate.getHours() + ":" + currentDate.getMinutes();

if (((currentDate.getDate() + 2) == selectedDate.getDate()) && (currentDate.getMonth() == selectedDate.getMonth()) && (currentDate.getFullYear() == selectedDate.getFullYear())) {
    if (selectedTime[0] >= currentDate.getHours()) {
        if (selectedTime[0] == currentDate.getHours()) {
            if (selectedTime[1] >= currentDate.getMinutes())
                return true;
            else
                return false;
        }
    }
    else
        return false;
}
else
    return true;
}

function checkGPSCC() {
var val = 0;
if (!document.getElementById("chkterms").checked) {
alert('You need to accept the Terms & Conditions before proceeding \n');
return false;}
for (i = 0; i < document.forms[0].Payment.length; i++) {
if (document.forms[0].Payment[i].checked == true)
val = document.forms[0].Payment[i].value;}
if ((val == "rbtnCreditCard") || (val == 0)) {
var ccstatus;
ccstatus = validateCard(document.getElementById("tbxCardNumber").value, document.getElementById("ddlCardType").value, document.getElementById("ddlCardMonth").value, document.getElementById("ddlCardYear").value, document.getElementById("tbxVerficationCode").value, document.getElementById("tbxCardName").value);
if (ccstatus) {return true;}else{return false;}}else {return true;}}

function printpage(){window.print();}


// creditcard stuff
function mod10(cardNumber) {
var ar = new Array(cardNumber.length);
var i = 0, sum = 0;
for (i = 0; i < cardNumber.length; ++i) {
ar[i] = parseInt(cardNumber.charAt(i));
}
for (i = ar.length - 2; i >= 0; i -= 2) {
ar[i] *= 2;
if (ar[i] > 9) ar[i] -= 9;
}
for (i = 0; i < ar.length; ++i) {
sum += ar[i];
}
return (((sum % 10) == 0) ? true : false);
}
function expired(month, year) {
year = eval("20" + year);
var now = new Date();
var expiresIn = new Date(year, month, 0, 0, 0);
if (now.getTime() < expiresIn.getTime()) return false;
return true;
}
function chkalpha(str) {
var re = /^[a-zA-Z]+$/;
if (re.test(str))
return true;
else
return false;
}

function validateCard(cardNumber, cardType, cardMonth, cardYear, cardVerficationCode, cardName) {
    var id = document.getElementById("hdnID").value;
    if (cardNumber.length == 0) {
        alert("Please enter a valid card number.");
        return false;
    }
    for (var i = 0; i < cardNumber.length; ++i) {
        var c = cardNumber.charAt(i);
        if (c < '0' || c > '9') {
            alert("Please enter a valid card number. Use only digits. do not use spaces or hyphens.");
            return false;
        }
    }
    var length = cardNumber.length;
    switch (cardType) {
        case 'a':
            if (length != 15) {
                alert("Please enter a valid American Express Card number.");
                return false;
            }
            var prefix = parseInt(cardNumber.substring(0, 2));
            if (prefix != 34 && prefix != 37) {
                alert("Please enter a valid American Express Card number.");
                return false;
            }
            break;
        case 'd':
            if (length != 14) {
                alert("Please enter a valid Diners Club card number.");
                return false;
            }
            break;
        case 'm':
            if (length != 16) {
                alert("Please enter a valid MasterCard number.");
                return false;
            }
            var prefix = parseInt(cardNumber.substring(0, 2));
            if (prefix < 51 || prefix > 55) {
                alert("Please enter a valid MasterCard Card number.");
                return false;
            }
            break;
        case 'v':
            if (length != 16 && length != 13) {
                alert("Please enter a valid Visa Card number.");
                return false;
            }
            var prefix = parseInt(cardNumber.substring(0, 1));
            if (prefix != 4) {
                alert("Please enter a valid Visa Card number.");
                return false;
            }
            break;
    }
    if (!mod10(cardNumber)) {
        alert("Sorry! this is not a valid credit card number.");
        return false;
    }
    if (expired(cardMonth, cardYear)) {
        alert("Sorry! The expiration date you have entered would make this card invalid.");
        return false;
    }
    if ((id != "56") && (id != "76455") && (id != "120201")) {
        if (cardVerficationCode.length != 0) {
            if ((cardVerficationCode.length < 3) || (cardVerficationCode.length > 4)) {
                alert("Sorry! The credit card verification code cannot be less than three characters");
                return false;
            }
            if (isNaN(cardVerficationCode)) {
                alert("Sorry! The credit card verification code must be numeric only");
                return false;
            }
        }
        else {
            alert("Sorry! The credit card verification code cannot be blank");
            return false;
        }
    }
    if (cardName.length == 0) {
        alert("Sorry! The credit card holder name cannot be blank");
        return false;
    }
    if (chkalpha(cardName)) {
        alert("Sorry! The credit card holder name contains some invalid characters");
        return false;
    }
    return true;
}


function blockNonNumbers(obj, e, allowDecimal, allowNegative) {
    var key;
    var isCtrl = false;
    var keychar;
    var reg;

    if (window.event) {
        key = e.keyCode;
        isCtrl = window.event.ctrlKey
    }
    else if (e.which) {
        key = e.which;
        isCtrl = e.ctrlKey;
    }

    if (isNaN(key)) return true;

    keychar = String.fromCharCode(key);

    // check for backspace or delete, or if Ctrl was pressed
    if (key == 8 || isCtrl) {
        return true;
    }

    reg = /\d/;
    var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
    var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;

    return isFirstN || isFirstD || reg.test(keychar);
}
function extractNumber(obj, decimalPlaces, allowNegative) {
    var temp = obj.value;

    // avoid changing things if already formatted correctly
    var reg0Str = '[0-9]*';
    if (decimalPlaces > 0) {
        reg0Str += '\\.?[0-9]{0,' + decimalPlaces + '}';
    } else if (decimalPlaces < 0) {
        reg0Str += '\\.?[0-9]*';
    }
    reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
    reg0Str = reg0Str + '$';
    var reg0 = new RegExp(reg0Str);
    if (reg0.test(temp)) return true;

    // first replace all non numbers
    var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (allowNegative ? '-' : '') + ']';
    var reg1 = new RegExp(reg1Str, 'g');
    temp = temp.replace(reg1, '');

    if (allowNegative) {
        // replace extra negative
        var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
        var reg2 = /-/g;
        temp = temp.replace(reg2, '');
        if (hasNegative) temp = '-' + temp;
    }

    if (decimalPlaces != 0) {
        var reg3 = /\./g;
        var reg3Array = reg3.exec(temp);
        if (reg3Array != null) {
            // keep only first occurrence of .
            //  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
            var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
            reg3Right = reg3Right.replace(reg3, '');
            reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
            temp = temp.substring(0, reg3Array.index) + '.' + reg3Right;
        }
    }

    obj.value = temp;
}
