﻿
$(document).ready(function() {
    $("input:radio").addClass("radio");
    $("input:checkbox").addClass("checkbox");

    //prepare the "tick"
    $("img[src*=images/tick_bw.gif]").each(function() {
        $(this).attr("alt", "Required field");
        $(this).addClass("tick");
    })

    //allocate functions to buttons
    $("#btnClear").bind("click", function(event)
    { event.preventDefault(); clearForm(); return false; });
    $("#btnSubmit").bind("click", function(event)
    { event.preventDefault(); submitForm(); return false; });
    $("#btnContactAddressSearch").bind("click", function(event)
    { event.preventDefault(); showContactQuickAddress(this); return false; });
    $("#btnCollectionAddressSearch").bind("click", function(event)
    { event.preventDefault(); showCollectionQuickAddress(this); return false; });

    $("[name=rbMOT]").filter("[value=Yes]").bind("click", function() { doMOTMessage() });
    $("[name=rbService]").filter("[value=Yes]").bind("click", function() { doServiceNotice() });

    $("#chkCollectedDeliveredByDealer").bind("click", function() { checkMultiSelectedOptions(this); doCollectDealerNotice() });
    $("#chkDeliverCollect").bind("click", function() { checkMultiSelectedOptions(this); doCollectNotice() });
    $("#chkCourtesyCar").bind("click", function() { checkMultiSelectedOptions(this); doCourtesyNotice() });
});


function doMOTMessage() {
    alert("Prior to your vehicle being presented for an MOT test, please ensure that the front windscreen is not damaged and the tyres are within legal limits.");
}

function doServiceNotice() {
    alert("Please leave your service book and locking wheel nut key (if applicable) on the passenger seat.");
}

function doCollectDealerNotice() {
    if ($("#chkCollectedDeliveredByDealer").is(":checked"))
        alert("Please remember to allow a minimum of " + daysToAllow() + " working days.");
}

function doCollectNotice() {
    if ($("#chkDeliverCollect").is(":checked"))
        alert("Please remember to allow a minimum of " + daysToAllow() + " working days.");
}

function doCourtesyNotice() {
    if ($("#chkCourtesyCar").is(":checked")) {
        var msg = "The courtesy car will require collection from the allocated dealer." +
							"\nPlease remember to allow a minimum of " + daysToAllow() + " working days for a Courtesy Car.";
        alert(msg);
    }
}

function daysToAllow() {
//    var chkDeliverCollect = $get('chkDeliverCollect');
//    var chkCollectedDeliveredByDealer = $get('chkCollectedDeliveredByDealer');
//    var chkCourtesyCar = $get('chkCourtesyCar');
//    var rbWithinM25 = $get('rbWithinM25');
    var chkDeliverCollect = $("[id*=chkDeliverCollect]");
    var chkCollectedDeliveredByDealer = $("[id*=chkCollectedDeliveredByDealer]");
    var chkCourtesyCar = $("[id*=chkCourtesyCar]");
    var rbWithinM25 = $("[id*=rbWithinM25]");

    var dys = 0;

    if (chkDeliverCollect.is(":checked"))
    { dys = 5; }

    if (chkCollectedDeliveredByDealer.is(":checked"))
    { dys = (rbWithinM25.is(":checked")) ? 6 : 5; }

    if (chkCourtesyCar.checked)
    { dys = (rbWithinM25.is(":checked")) ? 8 : 7; }

    return dys;
}


function addDaysToDate(myDate, days) {
    var daysToAdd = days * 24 * 60 * 60 * 1000;

    return new Date(myDate.getTime() + daysToAdd);
}

function isDateOnWeekend(checkDate) {
    var dow = checkDate.getDay();

    return (dow == 6 || dow == 0);
}


function y2k(number) {
    return (number < 1000) ? number + 1900 : number;
}

function daysElapsed(date1, date2) {
    // return the number of days difference between two dates
    var d1 = Date.UTC(y2k(date1.getFullYear()), date1.getMonth(), date1.getDate(), 0, 0, 0);
    var d2 = Date.UTC(y2k(date2.getFullYear()), date2.getMonth(), date2.getDate(), 0, 0, 0);

    var difference = d1 - d2;

    return (difference / 1000 / 60 / 60 / 24);
}

function daysFromToday(checkDate) {
    // return the number of days difference between todays date and param date
    var todaysDate = new Date();
    //var todayStr = todaysDate.getDate() + "/" + (todaysDate.getMonth() + 1) + "/" + todaysDate.getFullYear();

    return daysElapsed(checkDate, todaysDate)
}


function workingDaysToDate(checkDate) {
    // return the number of working days from today until param dateStr "dd/mm/yyyy" - date is assumed in the future!!
    var todaysDate = new Date();

    var totalDays = daysFromToday(checkDate);
    var countDays = totalDays;

    while (countDays > 0) {
        var tempDate = addDaysToDate(todaysDate, countDays);

        if (tempDate.getDay() == 0 || tempDate.getDay() == 6)
        { totalDays = totalDays - 1; }

        countDays = countDays - 1;
    }
    return totalDays;
}




function validateBookings(d1, d2, d3) {
    //var chkCourtesyCar = $get('chkCourtesyCar');
    var chkCourtesyCar = $("[id*=chkCourtesyCar]");
    var dateOK = false;
    var errorString = "";


    if (d1 - d2 == 0 || d2 - d3 == 0 || d1 - d3 == 0) {
        errorString += "Please enter three different Preferred Booking Dates\n\r\n\r";
    }

    if (isDateOnWeekend(d1)) {
        errorString += "Booking Date 1 (" + d1.getDate() + "/" + (d1.getMonth() + 1) + "/" + d1.getFullYear() + ") - must be a working day (not a weekend)\n\r";
    }

    if (isDateOnWeekend(d2)) {
        errorString += "Booking Date 2 (" + d2.getDate() + "/" + (d2.getMonth() + 1) + "/" + d2.getFullYear() + ") - must be a working day (not a weekend)\n\r";
    }

    if (isDateOnWeekend(d3)) {
        errorString += "Booking Date 3 (" + d3.getDate() + "/" + (d3.getMonth() + 1) + "/" + d3.getFullYear() + ") - must be a working day (not a weekend)\n\r";
    }

    if ((daysFromToday(d1) < 0) || (daysFromToday(d2) < 0) || (daysFromToday(d3) < 0)) {
        var dy = daysToAllow();
        var msg = (dy > 0) ? "\n\rPlease remember to allow a minimum of " + dy + " working days." : "";
        //errorString += "\n\rAll booking dates must be in the future." + msg + "\n\r";
    }

    var dys = daysToAllow();
    var msg1 = " - please allow a minimum of " + dys + " working days";
    var msg2 = chkCourtesyCar.checked ? " for a Courtesy Car" : "";

    if (dys > 0) {
        if (workingDaysToDate(d1) < dys) {
            errorString += "\n\rBooking Date 1 (" + d1.getDate() + "/" + (d1.getMonth() + 1) + "/" + d1.getFullYear() + ")" + msg1 + msg2;
        }

        if (workingDaysToDate(d2) < dys) {
            errorString += "\n\rBooking Date 2 (" + d2.getDate() + "/" + (d2.getMonth() + 1) + "/" + d2.getFullYear() + ")" + msg1 + msg2;
        }

        if (workingDaysToDate(d3) < dys) {
            errorString += "\n\rBooking Date 3 (" + d3.getDate() + "/" + (d3.getMonth() + 1) + "/" + d3.getFullYear() + ")" + msg1 + msg2;
        }
    }

    return errorString;
}






function checkMultiSelectedOptions(obj) {
//    var chkDeliverCollect = $get('chkDeliverCollect');
//    var chkCollectedDeliveredByDealer = $get('chkCollectedDeliveredByDealer');
//    var chkCourtesyCar = $get('chkCourtesyCar');

    var chkDeliverCollect = $("[id*=chkDeliverCollect]");
    var chkCollectedDeliveredByDealer = $("[id*=chkCollectedDeliveredByDealer]");
    var chkCourtesyCar = $("[id*=chkCourtesyCar]");

    var nm = obj.id;

    if (obj) {
        if (nm == "chkCollectedDeliveredByDealer") {
            chkDeliverCollect.attr("checked", false);
            chkCourtesyCar.attr("checked", false);
        }

        if (nm == "chkDeliverCollect") {
            chkCollectedDeliveredByDealer.attr("checked", false);
        }

        if (nm == "chkCourtesyCar") {
            chkCollectedDeliveredByDealer.attr("checked", false);
            chkDeliverCollect.attr("checked", true);
        }
    }
    else {
        if (nm == "chkDeliverCollect") {
            chkCourtesyCar.attr("checked", false);
        }
    }
}

function submitForm() {
    var txtDriverName = $("[id*=txtDriverName]").val();
    var txtRegNo = $("[id*=txtRegNo]").val();
    var txtMake = $("[id*=txtMake]").val();
    var txtModel = $("[id*=txtModel]").val();
    var txtCurrentMileage = $("[id*=txtCurrentMileage]").val();
    var txtPhoneNo = $("[id*=txtPhoneNo]").val();
    var txtMobileNo = $("[id*=txtMobileNo]").val();
    var txtEmailAddress = $("[id*=txtEmailAddress]").val();

    //var rbWithinM25 = $get('rbWithinM25');
    var isWithinM25 = $("[id*=rbWithinM25]:checked").val() == "Yes" ? true : false;

    //var rbMOT = $get('rbMOT');
    var isMOTDue = $("[id*=rbMOT]:checked").val() == "Yes" ? true : false;

    //var rbService = $get('rbService');
    var isServiceDue = $("[id*=rbService]:checked").val() == "Yes" ? true : false;

//    var txtBookingDate1 = $get('txtBookingDate1').value;
//    var txtBookingDate2 = $get('txtBookingDate2').value;
//    var txtBookingDate3 = $get('txtBookingDate3').value;
    var txtBookingDate1 = $("[id*=txtBookingDate1]");
    var txtBookingDate2 = $("[id*=txtBookingDate2]");
    var txtBookingDate3 = $("[id*=txtBookingDate3]");

    //var txtComments = $get('txtComments').value;
    var txtComments = $("[id*=txtComments]").val();

    var txtContactAddress1 = $("[id*=txtContactAddress1]").val();
    var txtContactAddress2 = $("[id*=txtContactAddress2]").val();
    var txtContactAddress3 = $("[id*=txtContactAddress3]").val();
    var txtContactAddress4 = $("[id*=txtContactAddress4]").val();
    var txtContactTown = $("[id*=txtContactTown]").val();
    var txtContactCounty = $("[id*=txtContactCounty]").val();
    var txtContactPostcode = $("[id*=txtContactPostcode]").val();

//    var txtCollectionAddress1 = $get('txtCollectionAddress1').value;
//    var txtCollectionAddress2 = $get('txtCollectionAddress2').value;
//    var txtCollectionAddress3 = $get('txtCollectionAddress3').value;
//    var txtCollectionTown = $get('txtCollectionTown').value;
//    var txtCollectionCounty = $get('txtCollectionCounty').value;
//    var txtCollectionPostcode = $get('txtCollectionPostcode').value;
    var txtCollectionAddress1 = $("[id*=txtCollectionAddress1]").val();
    var txtCollectionAddress2 = $("[id*=txtCollectionAddress2]").val();
    var txtCollectionAddress3 = $("[id*=txtCollectionAddress3]").val();
    var txtCollectionTown = $("[id*=txtCollectionTown]").val();
    var txtCollectionCounty = $("[id*=txtCollectionCounty]").val();
    var txtCollectionPostcode = $("[id*=txtCollectionPostcode]").val();

    //var chkCollectedDeliveredByDealer = $get('chkCollectedDeliveredByDealer');
    var chkCollectedDeliveredByDealer = $("[id*=chkCollectedDeliveredByDealer]");
    var supplierDelivery = chkCollectedDeliveredByDealer.is(":checked") ? true : false;

    //var chkDeliverCollect = $get('chkDeliverCollect');
    var chkDeliverCollect = $("[id*=chkDeliverCollect]");
    var selfDelivery = chkDeliverCollect.is(":checked") ? true : false;

    //var chkCourtesyCar = $get('chkCourtesyCar');
    var chkCourtesyCar = $("[id*=chkCourtesyCar]");
    var courtesyCarReq = chkCourtesyCar.is(":checked") ? true : false;

    var bookingD1 = null;
    var bookingD2 = null;
    var bookingD3 = null;


    var buff = new StringBuffer();

    if (txtRegNo == "")
        buff.append("Missing Vehicle Registration\r\n");

    if (txtCurrentMileage == "")
        buff.append("Missing Current Mileage\r\n");

    if (txtDriverName == "")
        buff.append("Missing Driver Name\r\n");

    if (txtContactAddress1 == "")
        buff.append("Missing Driver Address\r\n");

    if (txtContactPostcode == "")
        buff.append("Missing Driver Address Postcode\r\n");

    if (txtPhoneNo == "")
        buff.append("Missing Phone Number\r\n");

    if (txtEmailAddress == "")
        buff.append("Missing Email Address\r\n");
    else if (!isValidEmail(txtEmailAddress))
        buff.append("Invalid Email Address Entered\r\n");

    var todaysDate = new Date();

    if (txtBookingDate1.val() != "") {
        if (txtBookingDate1.val() != "") {
            var book1DateElements = txtBookingDate1.val().split("/");
            var century = (book1DateElements[2].length == 2) ? ((book1DateElements[2] < '50') ? "20" : "19") : "";
            txtBookingDate1.val(book1DateElements[0] + '/' + book1DateElements[1] + '/' + century + book1DateElements[2]);
        }
        bookingD1 = convertToValidDate(txtBookingDate1.val());
        if (bookingD1 == null)
            buff.append("Invalid Date Entered for 1st Preferred Booking Date\r\n");
        else if (bookingD1 < todaysDate)
            buff.append("1st Booking Date must be in the future\r\n");
    }

    if (txtBookingDate2.val() != "") {
        if (txtBookingDate2.val() != "") {
            var book2DateElements = txtBookingDate2.val().split("/");
            var century = (book2DateElements[2].length == 2) ? ((book2DateElements[2] < '50') ? "20" : "19") : "";
            txtBookingDate2.val(book2DateElements[0] + '/' + book2DateElements[1] + '/' + century + book2DateElements[2]);
        }
        bookingD2 = convertToValidDate(txtBookingDate2.val());
        if (bookingD2 == null)
            buff.append("Invalid Date Entered for 2nd Preferred Booking Date\r\n");
        else if (bookingD2 < todaysDate)
            buff.append("2nd Booking Date must be in the future\r\n");
    }

    if (txtBookingDate3.val() != "") {
        if (txtBookingDate3.val() != "") {
            var book3DateElements = txtBookingDate3.val().split("/");
            var century = (book3DateElements[2].length == 2) ? ((book3DateElements[2] < '50') ? "20" : "19") : "";
            txtBookingDate3.val(book3DateElements[0] + '/' + book3DateElements[1] + '/' + century + book3DateElements[2]);
        }
        bookingD3 = convertToValidDate(txtBookingDate3.val());
        if (bookingD3 == null)
            buff.append("Invalid Date Entered for 3rd Preferred Booking Date\r\n");
        else if (bookingD3 < todaysDate)
            buff.append("3rd Booking Date must be in the future\r\n");
    }

    if (bookingD1 != null && bookingD2 != null && bookingD3 != null) {
        var bookingDateErrors = validateBookings(bookingD1, bookingD2, bookingD3);
        if (bookingDateErrors.length > 0)
            buff.append(bookingDateErrors);
    }

    if ((supplierDelivery == false) && (selfDelivery == false))
        buff.append("Please select the service you require\r\n");

    if (buff.length() > 0)
        alert(String.format('INVALID DETAILS!\nYour request contains the following error(s):\n\n{0}\n\rPlease correct your details and try again.\r\nThank You.', buff.toString()));
    else {
        bookingD1 = bookingD1 == null ? convertToValidDate("01/01/1900") : bookingD1;
        bookingD2 = bookingD2 == null ? convertToValidDate("01/01/1900") : bookingD2;
        bookingD3 = bookingD3 == null ? convertToValidDate("01/01/1900") : bookingD3;

        SalesAndMarketingSite.Services.UserService.BookServiceTrak(txtDriverName, txtRegNo, txtMake, txtModel, txtCurrentMileage, txtPhoneNo,
                                                txtMobileNo, txtEmailAddress, isWithinM25, isMOTDue, isServiceDue, bookingD1,
                                                bookingD2, bookingD3, txtComments, txtContactAddress1, txtContactAddress2,
                                                txtContactAddress3, txtContactTown, txtContactCounty, txtContactPostcode,
                                                txtCollectionAddress1, txtCollectionAddress2, txtCollectionAddress3,
                                                txtCollectionTown, txtCollectionCounty, txtCollectionPostcode,
                                                supplierDelivery, selfDelivery, courtesyCarReq, onCompletedBookServiceTrak, onFailed);
    }
}



function onCompletedBookServiceTrak() {
    document.location.href = '/pages/thankyou.aspx';
}



function showContactQuickAddress(obj) {
    QuickAddress.show(obj,
        $('[id*=txtContactPostcode]').val(),
        $('[id*=txtContactAddress1]').val(),
        $('[id*=txtContactAddress3]').val(),
        $('[id*=txtContactTown]').val(),
        getContactQuickAddress);
}

function showCollectionQuickAddress(obj) {
    QuickAddress.show(obj,
        $('[id*=txtCollectionPostcode]').val(),
        $('[id*=txtCollectionAddress1]').val(),
        $('[id*=txtCollectionAddress3]').val(),
        $('[id*=txtCollectionTown]').val(),
        getCollectionQuickAddress);
}

function getContactQuickAddress(formattedAddress) {
    $('[id*=txtContactAddress1]').val(formattedAddress.line1);
    $('[id*=txtContactAddress2]').val(formattedAddress.line2);
    $('[id*=txtContactAddress3]').val(formattedAddress.line3);
    $('[id*=txtContactTown]').val(formattedAddress.town);
    $('[id*=txtContactCounty]').val(formattedAddress.county);
    $('[id*=txtContactPostcode]').val(formattedAddress.postcode);
}

function getCollectionQuickAddress(formattedAddress) {
    $('[id*=txtCollectionAddress1]').val(formattedAddress.line1);
    $('[id*=txtCollectionAddress2]').val(formattedAddress.line2);
    $('[id*=txtCollectionAddress3]').val(formattedAddress.line3);
    $('[id*=txtCollectionTown]').val(formattedAddress.town);
    $('[id*=txtCollectionCounty]').val(formattedAddress.county);
    $('[id*=txtCollectionPostcode]').val(formattedAddress.postcode);
}
