$(document).ready(function () {

    $(document.body).on('click', '#testVin', function (event) {
        decodeVIN();
        return false;
    });

    $("#vin").change(function (event) {
        decodeVIN();
        return false;
    });

    $("#hotlineVin").change(function (event) {
        checkHotlineVin();
        return false;
    });
    
    $("#vin").keypress(function (event) {
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if (keycode === '13') {
            decodeVIN();
            return false;
        }
    });

    $('#vin').on('change keyup paste mouseup', function () {
        this.val = $(this).val($(this).val().replace(/[^\w\s]+/g, '').trim());
    });

    function checkHotlineVin(){
        var a = $.trim($('#hotlineVin').val().toUpperCase());
        var b = $.trim($('#h_byPass').val().toUpperCase());
        
        if(a === b) {
            $('#hotlineVinErrorDiv').show();
            $('#hotlineVin').val('');
        } else {
            $('#hotlineVinErrorDiv').hide();
        }
    };
    
    function parseNoDec(decodedData){ 
        //$('#decodedYn').val('N');
        $('#h_exactProdArtemisMatchYn').val('N');
        var valuesArr = decodedData.split("|");
        var mmy = valuesArr[1].trim();
        $("#h_prodname").val(mmy);
        $("#h_prodid").val(valuesArr[2].trim());
        $("#h_vPicReqSeqId").val(valuesArr[3].trim());
        $("#h_vPicErrorCode").val(valuesArr[4].trim());
        $("#h_vPicCodeAndMsg").val(valuesArr[5].trim());
        $("#h_incompleteVeh").val(valuesArr[6].trim());        
        
        if (valuesArr[6].trim() === 'Y') {
            $('#incompleteMsg').show();
        } else { 
            $('#incompleteMsg').hide();
        }
        
        $("#smartSearch").show();//A Div
        $('#decodedDiv').hide();
        $('#vehsearch').val(mmy);
        $('#searchText').val(mmy);
        $('#error-vin').show();
        $('#vin').rules("add", 'required');
        $("#oneNext").show();
        $('#the2ndTab').css('pointer-events', 'none');
        $('#vehsearch').keydown();
        $('#vehsearch').change();
        $('#vehsearch').focus();
    }
    
    function decodeVIN() {
        $("#down").hide();
        $('#smartSearch').hide();
        $('#decodedDiv').hide();
        $('#searchText').val('');
        $('#searchText').removeAttr('value');
        $('#ui-id-5').hide();
        $('#h_prodname').val('');
        $('#vehsearch').val('');
        $('#incompleteMsg').hide();
        $('#hotlineVinErrorDiv').hide();
        $('#hotlineVin').val('');
        $("#oneNext").hide();


        var isbyPass = document.getElementById('h_byPassYn').value;
        var bypassVin = document.getElementById('h_byPass').value;
        var currentVin = document.getElementById('vin').value;

        if (isbyPass === 'Y') {
            if(currentVin === "")
            {
              document.getElementById('h_prodid').value="";
              $('#vin').val(bypassVin);
            }
        }
        
        if ($("#vin").val()) {
            $(this).next("#error-vin").show();

            var vinValue = $.trim($('#vin').val().toUpperCase());
            $('#decoded').hide();
            $("#decoded").empty();
            $('#noDecoded').hide();
            $("#noDecoded").empty();
            $("#oneNext").hide();

            $('#hotlineVinDiv').hide();
            
            checkVin(vinValue);

        } else {
            $("#error-vin").hide();
            $('#decoded').hide();
            $("#decoded").empty();
            $('#noDecoded').hide();
            $("#noDecoded").empty();

            $('#hotlineVinDiv').hide();
        }
    };

    function checkVin(inVin) {
        $('#hotlineVinDiv').hide();
        $.ajax({
            url: "/VehicleComplaint/bypass/" + inVin
        }).then(function (data) {
            var valuesArr = data.split("|");
            var bypassYN = valuesArr[0].trim();
            var byPassReqSeqId = valuesArr[1].trim();
            if (bypassYN === 'Y') {
                $("#h_byPassYn").val("Y");
                $("#h_vByPassReqSeqId").val(byPassReqSeqId);
                $("#h_byPass").val(inVin);
                $('#smartSearch').show();
                $('#hotlineVinDiv').show();
                $('#vin').rules("remove", 'required');
                
                $('#vin').val('');
                $('#decoded').hide();
                $("#decoded").empty();
                $('#noDecoded').hide();
                $("#noDecoded").empty();
                $('#error-vin').hide();
                $("#error-vin").empty();

                $("#oneNext").show();
                $("#indicator2").hide();
            } else {
                $("#h_byPassYn").val("N");
                $("#h_byPass").val("");
                $('#smartSearch').hide();
                $('#hotlineVinDiv').hide();
                $('#veh').val("");
                $('#searchText').val("");
                $('#error-vin').show();
                $('#vin').rules("add", 'required');

                vinVal();
                $(this).next("#error-vin").show();
            }
        });
    };

    $(document.body).on('click', '.hide-vin', function () {
        $(this).parent("#error-vin").hide();
        return false;
    });

    function vinVal() {
        $("#error-vin").empty();
        var noDecodedMsg = "<p style='text-align: center; '>Your report is very important to NHTSA.<br />";
        noDecodedMsg += "However, your VIN could not be processed.<br />";
        noDecodedMsg += "Please verify that the entered VIN is correct.</p>";
        noDecodedMsg += "<p style='text-align: center; '>If you need assistance with filing your vehicle safety complaint,<br />please contact the Vehicle Safety Hotline<br />(Toll-Free: 1-888-327-4236 / Hearing Impaired (TTY): 1-800-424-9153).</p>";

        var hasErrors = false;
        var errors = {
        };
        var VIN_PATTERN = new RegExp("^[A-HJ-NPR-Z0-9][A-HJ-NPR-Z0-9][A-HJ-NPR-Z0-9][A-HJ-NPR-Z0-9][A-HJ-NPR-Z0-9][A-HJ-NPR-Z0-9][A-HJ-NPR-Z0-9][A-HJ-NPR-Z0-9][0-9X][A-HJ-NPR-TV-Y1-9][A-HJ-NPR-Z0-9][A-HJ-NPR-Z0-9][A-HJ-NPR-Z0-9][0-9][0-9][0-9][0-9]$", "i");
        var vinValue = $.trim($('#vin').val().toUpperCase());

        var VIN_PATTERN_ARRAY = [
            "[A-HJ-NPR-Z0-9]",
            "[A-HJ-NPR-Z0-9]",
            "[A-HJ-NPR-Z0-9]",
            "[A-HJ-NPR-Z0-9]",
            "[A-HJ-NPR-Z0-9]",
            "[A-HJ-NPR-Z0-9]",
            "[A-HJ-NPR-Z0-9]",
            "[A-HJ-NPR-Z0-9]",
            "[0-9X]",
            "[A-HJ-NPR-TV-Y1-9]",
            "[A-HJ-NPR-Z0-9]",
            "[A-HJ-NPR-Z0-9]",
            "[A-HJ-NPR-Z0-9]",
            "[0-9]",
            "[0-9]",
            "[0-9]",
            "[0-9]"];
        var errMsg = "<ul>";

        if (vinValue.length === 17) {
            //Check to make sure characters are not the same
            if (!checkForSameCharacters(vinValue)) {
                hasErrors = true;
                errMsg = errMsg + "The VIN characters cannot be the same.";
                $('#decodedDiv').hide();
                $('#the2ndTab').css('pointer-events', 'none');
                $('#smartSearch').hide();
            } else if (VIN_PATTERN.test(vinValue)) {
                if (!checkDigit(vinValue)) {
                    errMsg += "<li>Invalid VIN</li>";
                    $('#the2ndTab').css('pointer-events', 'none');
                    $('#smartSearch').hide();
                    hasErrors = true;
                } else {
                    $("#indicator2").show();
                    $.ajax({
                        url: "/VehicleComplaint/decode/" + vinValue
                    }).then(function (decodedData) {

                        $("#indicator2").hide();
                        if (decodedData.startsWith('NODEC')) {
                            parseNoDec(decodedData);
                            $("#down").hide();
                        } else if (decodedData.startsWith('DOWN')) {
                            parseNoDec(decodedData);
                            $("#down").show();
                        } else {
                            $("#down").hide();
                            $('#smartSearch').hide();
                            $('#decodedDiv').show();
                            //$('#decodedYn').val('Y');
                            $('#h_exactProdArtemisMatchYn').val('Y');
                            //I am happy
                            var values = decodedData.split("|");
                            var mmy = values[1].trim();
                            var prodIdValue = values[2].trim();
                            var vpicReqSeqIdVal = values[3].trim();
                            var vPicErrorCodeVal = values[4].trim();
                            var vPicErrorMsgVal = values[5].trim();
                            var incompleteVehVal = values[6].trim();
                      
                            $("#h_prodid").val(prodIdValue);
                            $("#h_prodname").val(mmy);
                            $("#h_vPicReqSeqId").val(vpicReqSeqIdVal);
                            $("#h_vPicErrorCode").val(vPicErrorCodeVal);
                            $("#h_vPicCodeAndMsg").val(vPicErrorMsgVal);
                            $("#h_incompleteVeh").val(incompleteVehVal);
                            $('#hotlineVin').val("");

                            $('#decoded').show();
                            $("#decoded").empty();
                            $("#decoded").append(mmy);
                            $("#oneNext").show();
                        }

                    });
                }
            } else {//end VIN_PATTERN.test(vinValue)) 
                for (var j = 0; j < vinValue.length; j++) {
                    var regExpChar = new RegExp(VIN_PATTERN_ARRAY[j], "i");
                    if (!regExpChar.test(vinValue.charAt(j))) {
                        errMsg += getErrorMsg(j);
                        hasErrors = true;
                    }
                }
            }

        } else {//end vinValue.length == 17
            errMsg = errMsg + "The VIN must be 17 characters long.";
            $('#the2ndTab').css('pointer-events', 'none');
            $("#indicator2").hide();
            $('#smartSearch').hide();
            hasErrors = true;
        }
        
        if(hasErrors) { 
            html = $.parseHTML(noDecodedMsg);
            $('#noDecoded').css('display', 'inline-block');
            $('#noDecoded').empty();
            $('#noDecoded').append(html);
            
            $('#oneNext').hide();
            $('#the2ndTab').css('pointer-events', 'none');
        }
        
        errMsg += "</ul>";
        html = $.parseHTML(errMsg);
        $('#error-vin').css('display', 'inline-block');//BJ
        $("#error-vin").append(html);        
    };


    function populateDecodeArray(deCodeCharArray) {
        deCodeCharArray["A"] = 1;
        deCodeCharArray["B"] = 2;
        deCodeCharArray["C"] = 3;
        deCodeCharArray["D"] = 4;
        deCodeCharArray["E"] = 5;
        deCodeCharArray["F"] = 6;
        deCodeCharArray["G"] = 7;
        deCodeCharArray["H"] = 8;
        deCodeCharArray["J"] = 1;
        deCodeCharArray["K"] = 2;
        deCodeCharArray["L"] = 3;
        deCodeCharArray["M"] = 4;
        deCodeCharArray["N"] = 5;
        deCodeCharArray["P"] = 7;
        deCodeCharArray["R"] = 9;
        deCodeCharArray["S"] = 2;
        deCodeCharArray["T"] = 3;
        deCodeCharArray["U"] = 4;
        deCodeCharArray["V"] = 5;
        deCodeCharArray["W"] = 6;
        deCodeCharArray["X"] = 7;
        deCodeCharArray["Y"] = 8;
        deCodeCharArray["Z"] = 9;
    }
    /**
     * Checks for the input string to calculate the digit by
     * considering all the decode and weightfactor.
     * @author  	Gopal Rajanala
     * @version 	1.0 02/10/01
     * @param {String} paramVIN 
     */
    function calculateDigit(paramVIN) {
        var VIN = new String(paramVIN);
        var deCodeCharArray = new Array();
        //    1, 2, 3, 4, 5, 6, 7, 8,  9, 10, 11, 12, 13, 14, 15, 16, 17
        var weightFactorArray = new Array(8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2);
        populateDecodeArray(deCodeCharArray);
        var sum = 0;
        for (i = 0; i < VIN.length; i++) {
            var deCodeChar = VIN.charAt(i);
            if (isNaN(VIN.charAt(i))) {
                deCodeChar = deCodeCharArray[VIN.charAt(i)];
            }
            var weightFacor = weightFactorArray[i];
            sum = sum + (deCodeChar * weightFacor);
        }
        var digit = sum % 11;
        if (digit === 10) {
            return 'X';
        }
        return digit;
    }

    function checkForSameCharacters(vinValue) {
        var reg = /^(.)\1+$/;
        if (reg.test(vinValue)) {
            return false;
        } else {
            return true;
        }
    }

    function checkDigit(paramVIN) {
        var digit = calculateDigit(paramVIN);
        var VIN = new String(paramVIN);
        var ninethChar = VIN.charAt(8);
        if (digit === ninethChar) {
            return true;
        }
        // return false; Always return true so it goes to VPIC
        return true;
    }
    function getErrorMsg(paramCharPosition) {
        switch (paramCharPosition) {
            case 0:
                return "<li>Position 1 of the VIN cannot contain the characters I, O, and Q.</li>";
            case 1:
                return "<li>Position 2 of the VIN cannot contain the characters I, O, and Q.</li>";
            case 2:
                return "<li>Position 3 of the VIN cannot contain the characters I, O, and Q.</li>";
            case 3:
                return "<li>Position 4 of the VIN cannot contain the characters I, O, and Q.</li>";
            case 4:
                return "<li>Position 5 of the VIN cannot contain the characters I, O, and Q.</li>";
            case 5:
                return "<li>Position 6 of the VIN cannot contain the characters I, O, and Q.</li>";
            case 6:
                return "<li>Position 7 of the VIN cannot contain the characters I, O, and Q.</li>";
            case 7:
                return "<li>Position 8 of the VIN cannot contain the characters I, O, and Q.</li>";
            case 8:
                return "The check character (position 9) of the VIN is invalid. Valid numbers are 0-9. The valid character is X.</li>";
            case 9:
                return "<li>Position 10 of the VIN cannot contain the characters I, O, Q, U, Z or the number 0.</li>";
            case 10:
                return "<li>Position 11 of the VIN cannot contain the characters  I, O, and Q.</li>";
            case 11:
                return "<li>Position 12 of the VIN cannot contain the characters I, O, and Q.</li>";
            case 12:
                return "<li>Position 13 of the VIN cannot contain the characters I, O, and Q.</li>";
            case 13:
                return "<li>Position 14 of the VIN must be numeric.</li>";
            case 14:
                return "<li>Position 15 of the VIN must be numeric.</li>";
            case 15:
                return "<li>Position 16 of the VIN must be numeric.</li>";
            case 16:
                return "<li>Position 17 of the VIN must be numeric.</li>";
        }
    }
});
