﻿function formatMoney(x)
{
    if ((x == "") || (isNaN(x)))
    {
        x = 0;
    }
    x = new String(Math.round(x * 100) / 100);
    if (x.lastIndexOf(".") == -1)
    {
        x = x + ".";
    }
	
    var zerosRequired = 2 - (x.length - x.lastIndexOf(".") - 1);
	
    for (; zerosRequired > 0; zerosRequired--)
    {
        x = x + "0";
    }
	
    return x;
}

function UpdatePaymentWithFfo(referrerFieldId, MonthlyCost, UpdateDeposit, FfoDescription)
{
    var referrerField = eval("document.forms[0]." + referrerFieldId);
    var CurrentMonthlyPayment = document.forms[0].ctl00_Content_hdnMonthlyPayment.value;
    if (referrerField.checked)
    {
        document.getElementById("ctl00_Content_lblHeaderPayment").innerHTML = "£" + formatMoney(parseFloat(document.forms[0].ctl00_Content_hdnMonthlyPayment.value) + parseFloat(MonthlyCost));
        //if (UpdateDeposit)
        //    document.getElementById("ctl00_Content_lblDeposit").innerHTML = formatMoney(3 * (parseFloat(document.forms[0].ctl00_Content_hdnMonthlyPayment.value) + parseFloat(MonthlyCost)));
        document.forms[0].ctl00_Content_hdnMonthlyPayment.value = parseFloat(document.forms[0].ctl00_Content_hdnMonthlyPayment.value) + parseFloat(MonthlyCost);
        if (document.getElementById("ctl00_Content_litExtrasDescription").innerHTML == "")
            document.getElementById("ctl00_Content_litExtrasDescription").innerHTML = "with " + FfoDescription;
        else
            document.getElementById("ctl00_Content_litExtrasDescription").innerHTML += " | " + FfoDescription;
    }
    else
    {
        document.getElementById("ctl00_Content_lblHeaderPayment").innerHTML = "£" + formatMoney(parseFloat(document.forms[0].ctl00_Content_hdnMonthlyPayment.value) - parseFloat(MonthlyCost));
        //if (UpdateDeposit)
        //    document.getElementById("ctl00_Content_lblDeposit").innerHTML = formatMoney(3 * (parseFloat(document.forms[0].ctl00_Content_hdnMonthlyPayment.value) - parseFloat(MonthlyCost)));
        document.forms[0].ctl00_Content_hdnMonthlyPayment.value = parseFloat(document.forms[0].ctl00_Content_hdnMonthlyPayment.value) - parseFloat(MonthlyCost);
        document.getElementById("ctl00_Content_litExtrasDescription").innerHTML = document.getElementById("ctl00_Content_litExtrasDescription").innerHTML.replace(" | " + FfoDescription, "");
        document.getElementById("ctl00_Content_litExtrasDescription").innerHTML = document.getElementById("ctl00_Content_litExtrasDescription").innerHTML.replace(FfoDescription, "");
        while (document.getElementById("ctl00_Content_litExtrasDescription").innerHTML.indexOf("  ") > -1)
            document.getElementById("ctl00_Content_litExtrasDescription").innerHTML = document.getElementById("ctl00_Content_litExtrasDescription").innerHTML.replace("  ", " ");
        document.getElementById("ctl00_Content_litExtrasDescription").innerHTML = document.getElementById("ctl00_Content_litExtrasDescription").innerHTML.replace("with |", "with");
        if (document.getElementById("ctl00_Content_litExtrasDescription").innerHTML == "with" || document.getElementById("ctl00_Content_litExtrasDescription").innerHTML == "with " || document.getElementById("ctl00_Content_litExtrasDescription").innerHTML == "with | " || document.getElementById("ctl00_Content_litExtrasDescription").innerHTML == "with |")
            document.getElementById("ctl00_Content_litExtrasDescription").innerHTML = "";
    }
}

function NewWindow(mypage, myname, w, h, scroll)
{
	var winl = (screen.width - w) / 2;
	var wint = ((screen.height - h) / 2) - 50;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable'
	win = window.open(mypage, myname, winprops)
	if (parseInt(navigator.appVersion) >= 4)
	    win.window.focus();
}

function pafSearch(textBoxPrefix)
{
    
    var postcode = eval('document.forms[0].' + textBoxPrefix + 'Postcode.value');
    if (postcode != "")
        NewWindow("/lib/PafSearch.xlcr?Postcode=" + postcode + "&textBoxPrefix=" + textBoxPrefix, 'pafSearch', '800', '400', 'no');
    else
        alert("Please enter a postcode to search.");
}

function sicSearch(sicCodeField)
{
    NewWindow("/lib/SicCodeLookup.xlcr?sicCodeField=" + sicCodeField,"sicSearch", '600', '350', 'no');
}

function vatRegNoValidate(source, arguments)
{
    var VatRegNo = arguments.Value;
    VatRegNo = VatRegNo.replace("GB", "");
    VatRegNo = VatRegNo.replace("gb", "");
    VatRegNo = VatRegNo.replace(/ /g, "");
    if (isNaN(VatRegNo))
        arguments.IsValid = false;
    else if (VatRegNo.length != 9)
        arguments.IsValid = false;
    else
        arguments.IsValid = true;
}

function sicCodeValidate(source, arguments)
{
    var sicCode = arguments.Value;
    if (sicCode.length != 4)
    {
        arguments.IsValid = false;
    }
    else if (isNaN(sicCode))
    {
        arguments.IsValid = false;
    }
    else
    {
        arguments.IsValid = true;
    }
}

function directorTimeAtAddress(source, arguments)
{
    if (document.forms[0].ctl00_mainContent_DirectorMovedIn.value != "" && document.forms[0].ctl00_mainContent_DirectorAddressYears.value != "")
        arguments.IsValid = false;
    else if (document.forms[0].ctl00_mainContent_DirectorMovedIn.value == "" && document.forms[0].ctl00_mainContent_DirectorAddressYears.value == "")
        arguments.IsValid = false;
    else
        arguments.IsValid = true;
}

function showHelp(e, helpText)
{
    if (helpText == "helpText1")
    {
        document.getElementById('helpPanel').innerHTML = "<p>Our most popular agreement type – very flexible with easy early termination so if things change or if you want to upgrade during the contract, its easy with very little penalty. Also no mileage restrictions or charges for damage give you the ability to benefit from the equity in the vehicle too or keep it at the end of the contract. Highly recommended.</p>";
    }
    else if (helpText == "helpText2")
    {
        document.getElementById('helpPanel').innerHTML = "<p>The anticipated resale value of the vehicle at the end of the contract has an effect on the monthly rental, so a more expensive (but higher specification) vehicle may actually have a lower monthly rental.</p>";
    }
    else if (helpText == "helpText3")
    {
        document.getElementById('helpPanel').innerHTML = "<p>Please provide either the time at address or the date moved in (one or the other, not both). The date should be entered as dd/mm/yyyy; set the day to the 1st if you are not sure of the exact date.</p>";
    }
    else
    {
        document.getElementById('helpPanel').innerHTML = helpText;
    }
    
    document.body.style.cursor = "help";
    document.getElementById('helpPanel').style.display = "inline";
    
    document.getElementById('helpPanel').style.left = e.clientX + 'px';
    document.getElementById('helpPanel').style.top = e.clientY + 'px';
}

function hideHelp()
{
    document.getElementById('helpPanel').style.display = "none";
    document.body.style.cursor = "default";
}

function formatDateStringYM(startDate, endDate)
{
    return "1 year 1 month";
}

function directorAddressTimeValidation(source, arguments)
{
    var PreviousMovedInString = document.forms[0].ctl00_mainContent_hidPreviousMovedIn.value;
    var PreviousMovedIn = new Date(parseInt(PreviousMovedInString.substr(6, 4)), parseInt(PreviousMovedInString.substr(3, 2)) - 1, parseInt(PreviousMovedInString.substr(0, 2)));
    var PreviousMovedInLongString = PreviousMovedIn.toLocaleDateString();
    var DirectorMovedIn = document.forms[0].ctl00_mainContent_DirectorMovedIn.value;
    var DirectorAddressYears = document.forms[0].ctl00_mainContent_DirectorAddressYears.value;
    var DirectorAddressMonths = document.forms[0].ctl00_mainContent_DirectorAddressMonths.value;
    var ErrorMessageDate = "Please check the date moved in:\n    " + document.forms[0].ctl00_mainContent_hidDirectorName.value + " moved into the previous address on " + PreviousMovedInLongString + ".\n    Please therefore enter a valid date between that date and today.";
    var ErrorMessageTime = "Please check the time at address:\n    " + document.forms[0].ctl00_mainContent_hidDirectorName.value + " moved into the previous address on " + PreviousMovedInLongString + ".\n    Please therefore ensure that the time at address does not exceed " + formatDateStringYM(PreviousMovedIn, new Date()) ;
    //alert("Years -" + DirectorAddressYears + "-\nMonths -" + DirectorAddressMonths + "-\nDate -" + DirectorMovedIn + "-");
    if (DirectorMovedIn == "")
    {
        var ValidYears = !isNaN(DirectorAddressYears);
        var ValidMonths = !isNaN(DirectorAddressMonths);
        ValidMonths = ValidMonths && (DirectorAddressMonths < 12);
        
        if (DirectorAddressYears == "" && DirectorAddressMonths == "")
        {
            source.errormessage = "Please enter either the date moved in or the time at address.";
            arguments.IsValid = false;
        }
        else if (DirectorAddressYears == "" && DirectorAddressMonths != "")
        {
            document.forms[0].ctl00_mainContent_DirectorAddressYears.value = "0";
            if (!ValidMonths)
            {
                source.errormessage = "Please enter a number which is 11 or less for months at address.";
                arguments.IsValid = false;
            }
            else
            {
                source.errormessage = ErrorMessageTime;
                arguments.IsValid = validMovedInTime(PreviousMovedIn, DirectorAddressMonths);
            }
        }
        else if (DirectorAddressYears != "" && DirectorAddressMonths == "")
        {
            if (!ValidYears)
            {
                source.errormessage = "Please enter only numbers for the time at address.";
                arguments.IsValid = false;
            }
            else
            {
                source.errormessage = ErrorMessageTime;
                arguments.IsValid = validMovedInTime(PreviousMovedIn, (DirectorAddressYears * 12));
            }
        }
        else if (DirectorAddressYears != "" && DirectorAddressMonths != "")
        {
            if (ValidYears && ValidMonths)
            {
                source.errormessage = ErrorMessageTime;
                arguments.IsValid = validMovedInTime(PreviousMovedIn, ((DirectorAddressYears * 12) + DirectorAddressMonths));
            }
            else
            {
                source.errormessage = "Please enter only numbers for the time at address.\nFor the months, enter a number which is 11 or less.";
                arguments.IsValid = false;
            }
        }
    }
    else
    {
        if (DirectorAddressYears == "" && DirectorAddressMonths == "")
        {
            source.errormessage = ErrorMessageDate;
            arguments.IsValid = true;
        }
        else
        {
            source.errormessage = "Please enter either the time at address or moved in date (but not both).";
            arguments.IsValid = false;
        }
    }
}

function validMovedInTime(PreviousMovedInDate, MonthsAtAddress)
{
    return true;
}

function validateTelephoneNumber(source, arguments)
{
    var number = arguments.Value;
    number = number.replace(/ /g, "");
    if (isNaN(number))
        arguments.IsValid = false;
    else
        arguments.IsValid = true;    
}

function vatRegNoValidate(source, arguments)
{
    var VatRegNoString = arguments.Value;
    VatRegNoString = VatRegNoString.replace(/ /g, "");
    VatRegNoString = VatRegNoString.replace(/^GB/i, "");
    if (VatRegNoString.length == 9)
    {
        if (isNaN(VatRegNoString))
        {
            source.errormessage = "Please enter only numbers and spaces for the VAT number."
            arguments.IsValid = false;
        }
        else
        {
            var modulusTotal = 0;
            for (i = 1; i <= 7; i++)
            {
                var modulusValue = parseInt(VatRegNoString.substr(i - 1, 1));
                modulusValue *= (9 - i);
                modulusTotal += modulusValue;
            }
            
            while (modulusTotal > 0)
                modulusTotal -= 97;
                
            source.errormessage = "The VAT number appears to be invalid. Please check you have entered the digits correctly.";
            arguments.IsValid = ((-1 * modulusTotal) + '') == VatRegNoString.substr(7, 2);
        }
    }
    else
    {
        source.errormessage = "The VAT number should be 9 digits long without spaces, or 11 digits long with spaces. Please check the number and try again.";
        arguments.IsValid = false;
    }
}

function postBackHiddenField(hiddenFieldId)
{
    var hiddenField = $get(hiddenFieldId);
    if (hiddenField)
    {
        hiddenField.value = (new Date()).getTime();
        //__doPostBack(hiddenFieldId,'');
    }
}

function showBusinessCarPanel(businessCarId, hiddenFieldId)
{
    var behaviorE = $find("Expand_" + businessCarId);
    var behaviorC = $find("Collapse_" + businessCarId);
    if (behaviorE.get_Collapsed())
    {
        behaviorE._doOpen();
        behaviorC._doClose();
        postBackHiddenField(hiddenFieldId);
    }
    else
    {
        behaviorE._doClose();
        behaviorC._doOpen();
    }
}

function updateOpenPanels()
{
    var currentBehavior = null;
    var allBehaviors = Sys.Application.getComponents();
    for (var i = 0; i < allBehaviors.length; i++)
    {
        currentBehavior = allBehaviors[i];
        if (currentBehavior.get_name && currentBehavior.get_name() === "CollapsiblePanelBehavior" && !currentBehavior.get_Collapsed() && currentBehavior.get_id().substr(0, 6) === "Expand")
            postBackHiddenField(currentBehavior.get_element().id.replace("BusinessCarDetailsBox", "hdnUpdate"));
    }
}
