﻿$(function() {
    if (viewIndex == 0) {
        if ($("#ctl00_ContentPlaceHolder1_chkNoCar").is(':checked')) {
            $('#ddYear').attr("disabled", true);
            $('#ddMake').attr("disabled", true);
            $('#ddModel').attr("disabled", true);
            $('#ddStyle').attr("disabled", true);

            $('#ctl00_ContentPlaceHolder1_lmApplyNow_txtYear').attr("value", "");
            $('#ctl00_ContentPlaceHolder1_lmApplyNow_txtMake').attr("value", "");
            $('#ctl00_ContentPlaceHolder1_lmApplyNow_txtModel').attr("value", "");
            $('#ctl00_ContentPlaceHolder1_lmApplyNow_txtStyle').attr("value", "");
        }
        else {
            $('#ddYear').attr("disabled", false);
            $('#ddMake').attr("disabled", false);
            $('#ddModel').attr("disabled", false);
            $('#ddStyle').attr("disabled", false);
        }

        $("#ctl00_ContentPlaceHolder1_chkNoCar").click(function() {
        if ($("#ctl00_ContentPlaceHolder1_lmApplyNow_txtIsLocked").attr("value") != "true") {
                if ($("#ctl00_ContentPlaceHolder1_chkNoCar").is(':checked')) {
                    $('#ddYear').attr("disabled", true);
                    $('#ddMake').attr("disabled", true);
                    $('#ddModel').attr("disabled", true);
                    $('#ddStyle').attr("disabled", true);


                    $('#ctl00_ContentPlaceHolder1_lmApplyNow_txtYear').attr("value", "");
                    $('#ctl00_ContentPlaceHolder1_lmApplyNow_txtMake').attr("value", "");
                    $('#ctl00_ContentPlaceHolder1_lmApplyNow_txtModel').attr("value", "");
                    $('#ctl00_ContentPlaceHolder1_lmApplyNow_txtStyle').attr("value", "");

                    $("#ddYear option:eq(0)").attr("selected", "selected");
                    $("#ddMake option:eq(0)").attr("selected", "selected");
                    $("#ddModel option:eq(0)").attr("selected", "selected");
                    $("#ddStyle option:eq(0)").attr("selected", "selected");
                }
                else {
                    $('#ddYear').attr("disabled", false);
                    $('#ddMake').attr("disabled", false);
                    $('#ddModel').attr("disabled", false);
                    $('#ddStyle').attr("disabled", false);
                }
            }
            else {
                alert("A Car has already been selected");
                $("#ctl00_ContentPlaceHolder1_chkNoCar").removeAttr("checked");
            }
        });

        $("#ddSource > option[0]").html('Loading...')
        $.getJSON('DDHandler.lmxd?a=getsources', function(sources) {
            $.each(sources, function() {
                var selText = '';
                if ($('#ctl00_ContentPlaceHolder1_txtSourceId').attr("value").length > 0 && $('#ctl00_ContentPlaceHolder1_txtSourceId').attr("value") == this['Value'])
                    selText = 'selected';
                $('#ddSource').append($("<option " + selText + "></option>").val(this['Value']).html(this['Name']));
            });
            $("#ddSource > option[0]").html('Select a Source');
            if ($('#ctl00_ContentPlaceHolder1_txtLocationId').attr("value").length > 0) {
                var selSource = $("#ddSource option:selected").attr("value");
                $("#ddLocation").html("");
                $.getJSON('DDHandler.lmxd?a=getlocations&sourceid=' + selSource, function(locations) {
                    $("#ddLocation").append($("<option></option>").val("0").html("Select a Location"));
                    $.each(locations, function() {
                        var selText = '';
                        if ($('#ctl00_ContentPlaceHolder1_txtLocationId').attr("value").length > 0 && $('#ctl00_ContentPlaceHolder1_txtLocationId').attr("value") == this['Value'])
                            selText = 'selected';
                        $("#ddLocation").append($("<option " + selText + "></option>").val(this['Value']).html(this['Name']));
                    });
                });
            }
        });


        $("#ddSource").change(function() {
            var selSource = $("#ddSource option:selected").attr("value");
            if (selSource != "0") {
                $("#ddLocation").html("");
                $.getJSON('DDHandler.lmxd?a=getlocations&sourceid=' + selSource, function(locations) {
                    $("#ddLocation").append($("<option selected></option>").val("0").html("Select a Location"));
                    $.each(locations, function() {
                        $("#ddLocation").append($("<option></option>").val(this['Value']).html(this['Name']));
                    });
                });
            }
            else {
                $("#ddLocation").html("");
                $("#ddLocation").append($("<option selected></option>").val("0").html("Select a Location"));
            }

            $("#ctl00_ContentPlaceHolder1_txtSourceId").attr("value", $("#ddSource option:selected").val());
        });

        $("#ddLocation").change(function() {
            $("#ctl00_ContentPlaceHolder1_txtLocationId").attr("value", $("#ddLocation option:selected").val());
        });
    }
    else if (viewIndex == 1) {
        $(function() {
            $("#ctl00_ContentPlaceHolder1_txtDOB").datepicker({
                showOn: 'both',
                buttonImage: 'App_Themes/800loanmart/images/calendar_icon.gif',
                buttonImageOnly: false,
                changeMonth: true,
                changeYear: true,
                minDate: '-80y',
                maxDate: '-16y',
                yearRange: '-80:1'
            });

            $("#ctl00_ContentPlaceHolder1_txtDLExpDate").datepicker({
                showOn: 'both',
                buttonImage: 'App_Themes/800loanmart/images/calendar_icon.gif',
                buttonImageOnly: false,
                changeMonth: true,
                changeYear: true,
                minDate: '+1d',
                maxDate: '+10y'
            });
        });
    }

    $("#ctl00_ContentPlaceHolder1_txtSSN").keyup(function() {
        var value = $("#ctl00_ContentPlaceHolder1_txtSSN").attr("value");

        switch (value.length) {
            case 0:
                return;
                break;
            case 1:
            case 2:
            case 3:
            case 4:
            case 6:
            case 7:
            case 8:
            case 9:
            case 10:
            case 10:
            case 11:
                if (isNaN(value.charAt(value.length - 1))) {
                    value = value.substr(0, value.length - 1);
                }
                else {
                    if (value.length == 3) {
                        value = value + "-";
                    }
                    else if (value.length == 6) {
                        value = value + "-";
                    }
                }
                break;
            default:
                if (value.length > 11)
                    value = value.substr(0, 11);
                break;
        }

        $("#ctl00_ContentPlaceHolder1_txtSSN").attr("value", value);
    });
});

function cleanSSN(domField) {
    var ssnNumOnlyRegEx = /([0-9]{3})-?([0-9]{2})-?([0-9]{4})/g;


    var tmpSSN = "";

    if (ssnNumOnlyRegEx.test(domField.attr("value"))) {
        domField.attr("value").replace(ssnNumOnlyRegEx, function(match, num1, num2, num3) {
            tmpSSN = num1 + "-" + num2 + "-" + num3;
            return ""
        });

        domField.attr("value", tmpSSN)
    }
}


function cleanPhone(domField) {
    var phoneNumOnlyRegEx = /([0-9]{3})-?([0-9]{3})-?([0-9]{4})/g;

    var tmpPhone = "";

    if (phoneNumOnlyRegEx.test(domField.attr("value"))) {
        domField.attr("value").replace(phoneNumOnlyRegEx, function(match, num1, num2, num3) {
            tmpPhone = "(" + num1 + ")" + num2 + "-" + num3;
            return ""
        });

        domField.attr("value", tmpPhone)
    }
}



function ValidateApp(step) {
    var errors = eval("ValidateStep" + step + "()");

    if (errors.length > 0) {
        var errMessage = errors.length + " Fields Are Invalid\n\n";
        $.each(errors, function() {
            errMessage += "* " + this + "\n";
        });

        alert(errMessage);
        return false;
    }
    else {
        return true;
    }
}

function ValidateName(name){
    var regExp = /^[a-zA-Z]+[a-zA-Z\-\s\.']*$/;
    if(name != null && name != "")
    {
        return name.match(regExp);
    }
      return false;
}

function TrimName(name) {
    return name.replace(/^\s+|\s+$/g, "");
}

function ValidateStep1() {
    var errors = [];
    var phoneRegEx = new RegExp("^[0-9]{10}$");
    $("#ctl00_ContentPlaceHolder1_txtFname").attr("value", TrimName($("#ctl00_ContentPlaceHolder1_txtFname").attr("value")));
    $("#ctl00_ContentPlaceHolder1_txtLname").attr("value", TrimName($("#ctl00_ContentPlaceHolder1_txtLname").attr("value")));
    //cleanPhone($("#ctl00_ContentPlaceHolder1_txtPhone"));
    //cleanPhone($("#ctl00_ContentPlaceHolder1_txtMPhone"));

    if ($("#ctl00_ContentPlaceHolder1_txtMiles").attr("value").length == 0 || isNaN($("#ctl00_ContentPlaceHolder1_txtMiles").attr("value")) || $("#ctl00_ContentPlaceHolder1_txtMiles").attr("value") > maxInt)
        errors.push("Approximate Mileage has no value or is invalid");
    if ($("#ctl00_ContentPlaceHolder1_txtFname").attr("value") == "First Name")
        errors.push("First Name has no value");

    else if (!ValidateName($("#ctl00_ContentPlaceHolder1_txtFname").attr("value")))
        errors.push("First Name should start with a letter. This can be followed by letters, apostrophes, periods, spaces and hyphens");
    if ($("#ctl00_ContentPlaceHolder1_txtLname").attr("value") == "Last Name")
        errors.push("Last Name has no value");
    else if (!ValidateName($("#ctl00_ContentPlaceHolder1_txtLname").attr("value")))
        errors.push("Last Name should start with a letter. This can be followed by letters, apostrophes, periods, spaces and hyphens");    
    if (!$("#ctl00_ContentPlaceHolder1_chkNoCar").is(':checked')) {
        if ($("#ctl00_ContentPlaceHolder1_lmApplyNow_txtYear").attr("value").length == 0)
            errors.push("No Vehicle Year has been selected");
        if ($("#ctl00_ContentPlaceHolder1_lmApplyNow_txtMake").attr("value").length == 0)
            errors.push("No Vehicle Make has been selected");
        if ($("#ctl00_ContentPlaceHolder1_lmApplyNow_txtModel").attr("value").length == 0)
            errors.push("No Vehicle Model has been selected");
        if ($("#ctl00_ContentPlaceHolder1_lmApplyNow_txtStyle").attr("value").length == 0)
            errors.push("No Vehicle Style has been selected");
    }
    if ($("#ctl00_ContentPlaceHolder1_txtPhone").attr("value").length == 0 && $("#ctl00_ContentPlaceHolder1_txtMPhone").attr("value").length == 0)
        errors.push("Must enter a Home Phone OR and Mobile Phone");
    if ($("#ctl00_ContentPlaceHolder1_txtPhone").attr("value").length > 0 && !phoneRegEx.test($("#ctl00_ContentPlaceHolder1_txtPhone").attr("value")))
        errors.push("Invalid Phone Number. Must be 10 digits");
    if ($("#ctl00_ContentPlaceHolder1_txtMPhone").attr("value").length > 0 && !phoneRegEx.test($("#ctl00_ContentPlaceHolder1_txtMPhone").attr("value")))
        errors.push("Invalid Mobile Phone Number. Must be 10 digits");
    if ($("#ctl00_ContentPlaceHolder1_txtAmount").attr("value").length == 0 || isNaN($("#ctl00_ContentPlaceHolder1_txtAmount").attr("value")) || $("#ctl00_ContentPlaceHolder1_txtAmount").attr("value") > maxDec)
        errors.push("Loan Amount Requested has no value or is invalid");
    else if ($("#ctl00_ContentPlaceHolder1_txtAmount").attr("value") <= 0 || $("#ctl00_ContentPlaceHolder1_txtAmount").attr("value") > 50000.00)
        errors.push("Loan Amount must have an amount between 0.00 and 50000.00");
    if ($("#ctl00_ContentPlaceHolder1_txtSourceId").attr("value").length == 0 || $("#ctl00_ContentPlaceHolder1_txtSourceId").attr("value") == 0)
        errors.push("A Source was not selected");
    if ($("#ctl00_ContentPlaceHolder1_txtLocationId").attr("value").length == 0 || $("#ctl00_ContentPlaceHolder1_txtLocationId").attr("value") == 0)
        errors.push("A Source Location was not selected");
    if (!$('#ctl00_ContentPlaceHolder1_chkDisc').is(':checked') && $('#ctl00_ContentPlaceHolder1_chkDisc').attr("value") != "checked")
        errors.push("Terms and Conditions are not checked");            

    return errors;
}

function ValidateStep2() {
    var ssnRegEx = new RegExp("[0-9]{3}-[0-9]{2}-[0-9]{4}");

    cleanSSN($("#ctl00_ContentPlaceHolder1_txtSSN"))

    var errors = [];
    if ($("#ctl00_ContentPlaceHolder1_txtDOB").attr("value").length == 0)
        errors.push("Missing Date of Birth");
    if ($("#ctl00_ContentPlaceHolder1_txtDLNo").attr("value").length == 0)
        errors.push("Missing Drivers License No.");
    if ($("#ctl00_ContentPlaceHolder1_selDLState  option:selected").attr("value") == 0)
        errors.push("No Drivers License State selected");
    if ($("#ctl00_ContentPlaceHolder1_txtDLExpDate").attr("value").length == 0)
        errors.push("Missing Drivers License Expiration Date");
    if ($("#ctl00_ContentPlaceHolder1_txtSSN").attr("value").length == 0 || $("#ctl00_ContentPlaceHolder1_txtSSN").attr("value") == 'XXX-XX-XXXX')
        errors.push("Missing Social Security Number");
    else if ($("#ctl00_ContentPlaceHolder1_txtSSN").attr("value").length > 0 && !ssnRegEx.test($("#ctl00_ContentPlaceHolder1_txtSSN").attr("value")))
        errors.push("Invalid Social Security Number. Must be XXX-XX-XXXX");
    if ($("#ctl00_ContentPlaceHolder1_txtEmail").attr("value").length == 0 || !ValidEmail($("#ctl00_ContentPlaceHolder1_txtEmail").attr("value")))
        errors.push("Missing or invalid Email");
    //else if ($("#ctl00_ContentPlaceHolder1_txtEmail").attr("value") != $("#ctl00_ContentPlaceHolder1_txtEmailConf").attr("value"))
    //    errors.push("Confirm Email does not match Email");

    if ($("#ctl00_ContentPlaceHolder1_txtAddressStreet").attr("value").length == 0)
        errors.push("Missing Street Number");
    if ($("#ctl00_ContentPlaceHolder1_txtAddressStreet").attr("value").length > 0 && isNaN($("#ctl00_ContentPlaceHolder1_txtAddressStreet").attr("value")))
        errors.push("Invalid Street Number");
    if ($("#ctl00_ContentPlaceHolder1_txtAddressStreetName").attr("value").length == 0)
        errors.push("Missing Street Name");
    if ($("#ctl00_ContentPlaceHolder1_txtAddressCity").attr("value").length == 0)
        errors.push("Missing City");
    if ($("#ctl00_ContentPlaceHolder1_selAddressState  option:selected").attr("value") == 0)
        errors.push("Missing State");
    if ($("#ctl00_ContentPlaceHolder1_txtAddressZip").attr("value").length == 0 || $("#ctl00_ContentPlaceHolder1_txtAddressZip").attr("value").length > 10)
        errors.push("Missing or Invalid Zip Code");
    if ($("#ctl00_ContentPlaceHolder1_selAddressYears  option:selected").attr("value") == 0 && $("#ctl00_ContentPlaceHolder1_selAddressMonths  option:selected").attr("value") == 0)
        errors.push("No Time At Address selected");
    if ($("#ctl00_ContentPlaceHolder1_txtMort").attr("value").length == 0 || isNaN($("#ctl00_ContentPlaceHolder1_txtMort").attr("value")) || $("#ctl00_ContentPlaceHolder1_txtMort").attr("value") > 999999)
        errors.push("Rent/Mortgage has no value or is invalid");
    if ($("#ctl00_ContentPlaceHolder1_txtAddressZip").attr("value").length > 0 && isNaN($("#ctl00_ContentPlaceHolder1_txtAddressZip").attr("value")))
        errors.push("Invalid Zip code");
    return errors;
}

function ValidateStep3() {
    var errors = [];
    var phoneRegEx = new RegExp("^[0-9]{10}$");
    
    if ($("#ctl00_ContentPlaceHolder1_txtEmpName").attr("value").length == 0)
        errors.push("Missing Employer Name");
    if ($("#ctl00_ContentPlaceHolder1_txtEmpTitle").attr("value").length == 0)
        errors.push("Missing Job Title");
    if ($("#ctl00_ContentPlaceHolder1_txtEmpAddressStreet").attr("value").length == 0)
        errors.push("Missing Street Number");
    if ($("#ctl00_ContentPlaceHolder1_txtEmpAddressStreet").attr("value").length > 0 && isNaN($("#ctl00_ContentPlaceHolder1_txtEmpAddressStreet").attr("value")))
        errors.push("Invalid Street Number");
    if ($("#ctl00_ContentPlaceHolder1_txtEmpAddressStreetName").attr("value").length == 0)
        errors.push("Missing Street Name");
    if ($("#ctl00_ContentPlaceHolder1_txtEmpAddressCity").attr("value").length == 0)
        errors.push("Missing City");
    if ($("#ctl00_ContentPlaceHolder1_selEmpAddressState  option:selected").attr("value") == 0)
        errors.push("Missing State");
    if ($("#ctl00_ContentPlaceHolder1_txtEmpAddressZip").attr("value").length == 0 || $("#ctl00_ContentPlaceHolder1_txtEmpAddressZip").attr("value").length > 10)
        errors.push("Missing or Invalid Zip Code");
    if ($("#ctl00_ContentPlaceHolder1_txtEmpIncomeTotal").attr("value").length > 0 && isNaN($("#ctl00_ContentPlaceHolder1_txtEmpIncomeTotal").attr("value")) || $("#ctl00_ContentPlaceHolder1_txtEmpIncomeTotal").attr("value") > maxInt)
        errors.push("Invalid Total Income");
    if ($("#ctl00_ContentPlaceHolder1_txtEmpOtherIncome").attr("value").length > 0 && isNaN($("#ctl00_ContentPlaceHolder1_txtEmpOtherIncome").attr("value")) || $("#ctl00_ContentPlaceHolder1_txtEmpOtherIncome").attr("value") > maxInt)
        errors.push("Invalid Other Income");
    if ($("#ctl00_ContentPlaceHolder1_txtEmpIncome").attr("value").length > 0 && isNaN($("#ctl00_ContentPlaceHolder1_txtEmpIncome").attr("value")) || $("#ctl00_ContentPlaceHolder1_txtEmpIncome").attr("value") > maxInt)
        errors.push("Invalid Income");
    if ($("#ctl00_ContentPlaceHolder1_selEmpYears  option:selected").attr("value") == 0 && $("#ctl00_ContentPlaceHolder1_selEmpMonths  option:selected").attr("value") == 0)
        errors.push("No Time At present employer selected");
    if ($("#ctl00_ContentPlaceHolder1_txtEmpIncome").attr("value").length == 0)
        errors.push("Missing Gross monthly income");
    if (!$("#divIsDD input[type='radio']").is(':checked'))
        errors.push("Select if you get direct deposit");
    if (!$("#divisContactWork input[type='radio']").is(':checked'))
        errors.push("Select if we can contact you at work");
    if (!$('#terms').is(':checked'))
        errors.push("Terms and Conditions are not checked");
    if ($("#ctl00_ContentPlaceHolder1_txtEmpAddressZip").attr("value").length > 0 && isNaN($("#ctl00_ContentPlaceHolder1_txtEmpAddressZip").attr("value")))
        errors.push("Invalid Zip code");
    if ($("#ctl00_ContentPlaceHolder1_txtEmpPhone").attr("value").length > 0 && !phoneRegEx.test($("#ctl00_ContentPlaceHolder1_txtEmpPhone").attr("value")))
        errors.push("Invalid Phone Number. Must be 10 digits");

    return errors;
}

function ValidEmail(str) {

    var at = "@"
    var dot = "."
    var lat = str.indexOf(at)
    var lstr = str.length
    var ldot = str.indexOf(dot)
    if (str.indexOf(at) == -1) {
        return false
    }

    if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
        return false
    }

    if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
        return false
    }

    if (str.indexOf(at, (lat + 1)) != -1) {
        return false
    }

    if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {
        return false
    }

    if (str.indexOf(dot, (lat + 2)) == -1) {
        return false
    }

    if (str.indexOf(" ") != -1) {
        return false
    }

    return true;
}
