/** Form Validation */
var allowSubmit = false;
var submitted = false;
var s1Tmr = 0;
var s2Tmr = 0;
var s3Tmr = 0;
/**Form */
var form=$('form');
/**Form Field Ids */
var ffname=form.find('input[id*="fname"]');
var flname=form.find('input[id*="lname"]');
var fshipCity=form.find('input[id*="city"]');
var fshipState=form.find('select[id*="state"]');
var fshipZip=form.find('input[id*="zip"]');
var fshipAddress=form.find('input[id*="address1"]');
var femail=form.find('input[id*="email"]');
var fphone=form.find('input[id*="phone"]');
var fbillFname=form.find('input[id="firstName"]');
var fbillLname=form.find('input[id="lastName"]');
var fbillCity=form.find('input[id="billingCity"]');
var fbillState=form.find('select[id="billingState"]');
var fbillZip=form.find('input[id="billingZip"]');
var fbillAddress=form.find('input[id="billingAddress1"]');
var fbillCard=form.find('input[id="cardNumber"]');
var fbillCardType=form.find('input[id="creditCardType"]');
var fbillCardCVV=form.find('input[id="cc_cvv"]');
var fbillCardExpMonth=(form.find('select[id*="Month"]').length)?form.find('select[id*="Month"]'):form.find('select[id*="month"]');
var fbillCardExpYear=(form.find('select[id*="Year"]').length)?form.find('select[id*="Year"]'):form.find('select[id*="year"]');


form.find('input:not(input[type=submit], input[type=image]), select, textarea').on('keyup', function () {
    $(this).removeClass('has-error');
    $(this).removeClass('no-error');
});

form.find('input:not(input[type=submit], input[type=image]), select, textarea').on('change blur', function () {
    if ($(this).val() == '') {
    $(this).addClass('has-error');
    $(this).removeClass('no-error');
    } else {
    $(this).removeClass('has-error');
    $(this).addClass('no-error');
    }
});

fshipAddress.on('change blur', function () {
    if (!(/^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[ ])([a-zA-Z0-9\/\-\.\, ]+)$/.test($(this).val()))) {
        $(this).addClass('has-error');
        $(this).removeClass('no-error');
    }
});

fbillAddress.on('change blur', function () {
    if (!(/^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[ ])([a-zA-Z0-9\/\-\.\, ]+)$/.test($(this).val()))) {
        $(this).addClass('has-error');
        $(this).removeClass('no-error');
    }
});

femail.on('change blur', function () {
    var emailReg2 = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    if (!emailReg2.test($(this).val())) {
        $(this).addClass('has-error');
        $(this).removeClass('no-error');
    }
});

fphone.on('change blur', function () {
    var phoneReg2 = /^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$/;
    if (!phoneReg2.test($(this).val())) {
        $(this).addClass('has-error');
        $(this).removeClass('no-error');
    }
});

fshipZip.on('change blur', function () {
    var zip = $(this).val();
    if ((zip.length) < 5) {
        $(this).addClass('has-error');
        $(this).removeClass('no-error');
    }
});

fbillZip.on('change blur', function () {
    var zip = $(this).val();
    if ((zip.length) < 5) {
        $(this).addClass('has-error');
        $(this).removeClass('no-error');
    }
});

fbillCard.keyup(function() {
    var cc_card = $(this).val().replace(/\s/g, '');
    if(cc_card.charAt(0)!=1){
      var result = $(this).validateCreditCard();
      var card = result.card_type.name;
      card = card.replace("mastercard", "master");
      fbillCardType.val(card);
    }				
});

fbillCard.on('change blur', function() {
    var cc_card = $(this).val().replace(/\s/g, '');
    if ((cc_card.length)< 16 ){
        //$(this).addClass('has-error');
        $(this).removeClass('no-error');
    }
});

function validate_optin_form() {
            
    ShowExitPopup = false;
    internal = 1;
    isExit = false;

    var errors = new Array();
    var phonefilter = /^([0-9\-\+\(\)]{8,22})+$/;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

    $("input").removeClass("has-error");

    if (ffname.val().replace(/^\s+|\s+$/g, "") == '') {
        errors.push('Please enter your first name');
        ffname.addClass("has-error");
    }
    if (flname.val().replace(/^\s+|\s+$/g, "") == '') {
        errors.push('Please enter your last name');
        flname.addClass("has-error");
    }
    var trigger_address_invalid_error=false;
    if (fshipAddress.length && fshipAddress.val().replace(/^\s+|\s+$/g, "") == '') {
        errors.push('Please select your address');
        fshipAddress.addClass("has-error");
    }else if(fshipAddress.length && !(/^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[ ])([a-zA-Z0-9\/\-\.\, ]+)$/.test(fshipAddress.val()))){
        errors.push("Ooops, looks like you may have left out part of the address line empty. Please fix and resubmit!");
        trigger_address_invalid_error=true;
        fshipAddress.addClass("has-error");
    }
    if (fshipZip.length && fshipZip.val().replace(/^\s+|\s+$/g, "") == '') {
        errors.push('Please enter your Zip Code');
        fshipZip.addClass("has-error");
    }else if(fshipZip.length && fshipZip.val().length < 5){
        if(trigger_address_invalid_error==true && errors.length == 1){
            errors.push("<br>Ooops, looks like you may have left out part of your zip code empty. Please fix and resubmit!");
        }else{
            errors.push("Ooops, looks like you may have left out part of your zip code empty. Please fix and resubmit!");
        }
        fshipZip.addClass("has-error");
    }
    if (fshipCity.length && fshipCity.val().replace(/^\s+|\s+$/g, "") == '') {
        errors.push('Please enter your city');
        fshipCity.addClass("has-error");
    }
    if (fshipState.length && fshipState.val().replace(/^\s+|\s+$/g, "") == '') {
        errors.push('Please enter your state');
        fshipState.addClass("has-error");
    }
    if (femail.val().replace(/^\s+|\s+$/g, "") == '') {
        errors.push('Please enter your email address');
        femail.addClass("has-error");
    } else if (!emailReg.test(femail.val())) {
        errors.push('Please enter valid email address');
        femail.addClass("has-error");
    }

    if (fphone.length && fphone.val().replace(/^\s+|\s+$/g, "") == '') {
        errors.push('Please enter your phone number');
        fphone.addClass("has-error");
    }else if(fphone.length && (!(/^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$/.test(fphone.val())))){
        errors.push('Phone number must be a minimum of 10 digits');
        fphone.addClass("has-error");
    }
    
    console.log(errors.length);

    if (errors.length == 0) {
        $('.popup-loading-wrapper').show();
        $('#loading-indicator').show();
        if(fphone.length)fphone.unmask();
        var data = form.serialize();
        if(fphone.length)fphone.mask('000-000-0000');
        var url =  form.attr('action');
        //$('#vmodal').html($('#vmodal-submitting').html());
		//softModal.open('#vmodal');
        $.ajax({
            type: "POST",
            dataType: "json",
            url: url,
            data: data,
            success: function(result) {
                if (result.status == "success") {
                    window.location.href = result.goTo;
                } else {
                    //softModal.close('#vmodal');
                    popErrorModal(result.message);
                }
            },
            error: function() {
                //softModal.close('#vmodal');
                $("#preloader").hide();
                $('.popup-loading-wrapper').hide();
                $('#loading-indicator').hide();
                $('#loading-screen').hide();
            }
        });
        //form.submit();
            
        return false;
    } else {
        
        var li = '';
        $.each(errors, function (key, value) {
            li += '<li>' + value + '</li>';
        });

        var html = '';
        html += '<div id="error_handler_overlay">';
        html += '<div class="error_handler_body"><a href="javascript:void(0);" id="error_handler_overlay_close">X</a><ul>' + li + '</ul></div>';
        html += '</div>';

        $('body').append(html);

        $('#error_handler_overlay').fadeIn(500);
        return false;
    }
}

function submit_form() {
				
    $("#preloader").show();
    
    var errors = new Array();
                    
    if (! $('#billingSameAsShipping').prop('checked')) {
        // Validate billing fields
        if (fbillFname.val().replace(/^\s+|\s+$/g, "") == '') {
            errors.push('Please enter your first name');
            fbillFname.addClass("has-error");
        }
        if (fbillLname.val().replace(/^\s+|\s+$/g, "") == '') {
            errors.push('Please enter your last name');
            fbillLname.addClass("has-error");
        }
        var trigger_address_invalid_error=false;
        if (fbillAddress.val().replace(/^\s+|\s+$/g, "") == '') {
            errors.push('Please select your address');
            fbillAddress.addClass("has-error");
        }else if(!(/^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[ ])([a-zA-Z0-9\/\-\.\, ]+)$/.test(fbillAddress.val()))){
            errors.push("Ooops, looks like you may have left out part of the address line empty. Please fix and resubmit!");
            fbillAddress.addClass("has-error");
            trigger_address_invalid_error=true;
        }
        if (fbillZip.val().replace(/^\s+|\s+$/g, "") == '') {
            errors.push('Please enter your zip code');
            fbillZip.addClass("has-error");
            }else if(fbillZip.val().length < 5){
            if(trigger_address_invalid_error==true && errors.length == 1){
                errors.push("<br>Ooops, looks like you may have left out part of your zip code empty. Please fix and resubmit!");
            }else{
                errors.push("Ooops, looks like you may have left out part of your zip code empty. Please fix and resubmit!");
            }
            fbillZip.addClass("has-error");
        }    
        if (fbillCity.val().replace(/^\s+|\s+$/g, "") == '') {
            errors.push('Please enter your city');
            fbillCity.addClass("has-error");
        }
        if (fbillState.val() === '') {
            errors.push('Please enter your state');
            fbillState.addClass("has-error");
        }
    }
    
    // Check CC #
    if (fbillCard.val() === "") {
        errors.push("Please enter a credit card number.");
        fbillCard.addClass("has-error");
    } else {
        var validCard = LuhnAlgorithm(fbillCard.unmask().val());
        fbillCard.mask('0000 0000 0000 0000');
        if (!validCard) {
            errors.push('Credit Card number is Invalid, please enter a valid credit card number.');
        }
    }
    
    if (fbillCardExpMonth.val() === "" || fbillCardExpMonth.val() === "Month") {
        errors.push("Please enter a valid expiration month.");
        fbillCardExpMonth.addClass("has-error");
    }
    
    if (fbillCardExpYear.val() === "" || fbillCardExpYear.val() === "Year") {
        errors.push("Please enter a valid expiration year.");
        fbillCardExpYear.addClass("has-error");
    }
    
    if (fbillCardCVV.val() === "") {
        errors.push("Please enter a CVV code.");
        fbillCardCVV.addClass("has-error");
    }
                    
    if (errors.length == 0) {
        $('.loading-screen').show();
		allowSubmit = true;
        submitted = true;
        clearTimer();
        $('.loading-screen .show-1').addClass("active");
        s2Tmr = setTimeout(function(){ $('.loading-screen .show-2').addClass("active"); }, 1000);
        s3Tmr = setTimeout(function(){ $('.loading-screen .show-3').addClass("active"); }, 1500);
        fbillCard.unmask();
        var data = form.serialize();	
        fbillCard.mask('0000 0000 0000 0000');
        var url =	form.attr('action');
        $('#vmodal').html($('#vmodal-submitting').html());
		softModal.open('#vmodal');
        $.ajax({
          type: "POST",
          dataType: "json",
          url: url,
          data: data,
          success: function(result) {
            if (result.status == "success") {
                window.location.href = result.goTo;
            } else {
                allowSubmit = false;
                submitted = false;
                clearTimer();
                softModal.close('#vmodal');
                popErrorModal(result.message);
                $('.loading-screen').hide();
            }
          },
          error: function() {
            softModal.close('#vmodal');
            $("#preloader").hide();
            $('.popup-loading-wrapper').hide();          
            allowSubmit = false;
            submitted = false;
            clearTimer();
            $('.loading-screen').hide();
          }
        });
        
        fbillCard.mask("0000 0000 0000 0000");
        
        return false;
        
    } else {
        
        fbillCard.mask("0000 0000 0000 0000");
        var li = '';
        $.each(errors, function (key, value) {
        li += '<li>' + value + '</li>';
        });
        var html = '';
        html += '<div id="error_handler_overlay">';
        html += '<div class="error_handler_body"><a href="javascript:void(0);" id="error_handler_overlay_close">X</a><ul>' + li + '</ul></div>';
        html += '</div>';
        $('body').append(html);
        $("#preloader").hide();
        softModal.close('#vmodal');
        $('.popup-loading-wrapper').hide();
        $('.loading-screen').hide();         
        $('#error_handler_overlay').fadeIn(500);
        return false;
    }
}

$(function () {
    $(window).keydown(function (e) {
        if (e.which === 27 && $('#error_handler_overlay').length) {
            $('#error_handler_overlay').remove();
        }
    });

    $(document).off('click', '#error_handler_overlay');
    $(document).on('click', '#error_handler_overlay', function () {
        $(this).remove();
    });

    $(document).off('click', '#error_handler_overlay_close');
    $(document).on('click', '#error_handler_overlay_close', function () {
        $('#error_handler_overlay').remove();
    });

    $(document).on('click', '#app_common_modal_close', function () {
        $('#app_common_modal').remove();
    });
});

function onlyNumbers(e, type) {
    var keynum;
    var keychar;
    var numcheck;
    if (window.event) // IE
    {
        keynum = e.keyCode;
    } else if (e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    keychar = String.fromCharCode(keynum);
    numcheck = /\d/;

    switch (keynum) {
        case 8:    //backspace
        case 9:    //tab
        case 35:   //end
        case 36:   //home
        case 37:   //left arrow
        case 38:   //right arrow
        case 39:   //insert
        case 45:   //delete
        case 46:   //0
        case 48:   //1
        case 49:   //2
        case 50:   //3
        case 51:   //4
        case 52:   //5
        case 54:   //6
        case 55:   //7
        case 56:   //8
        case 57:   //9
        case 96:   //0
        case 97:   //1
        case 98:   //2
        case 99:   //3
        case 100:  //4
        case 101:  //5
        case 102:  //6
        case 103:  //7
        case 104:  //8
        case 105:  //9
            result2 = true;
            break;
        case 109: // dash -
            if (type == 'phone') {
                result2 = true;
            } else {
                result2 = false;
            }
            break;
        default:
            result2 = numcheck.test(keychar);
            break;
    }

    return result2;
}

function openNewWindow(page_url, type, window_name, width, height, top, left, features) {
    if (!type) {
        type = 'popup';
    }

    if (!width) {
        width = 480;
    }

    if (!height) {
        height = 480;
    }

    if (!top) {
        top = 50;
    }

    if (!left) {
        left = 50;
    }

    if (!features) {
        features = 'resizable,scrollbars';
    }

    if (type == 'popup') {
        var settings = 'height=' + height + ',';
        settings += 'width=' + width + ',';
        settings += 'top=' + top + ',';
        settings += 'left=' + left + ',';
        settings += features;

        win = window.open(page_url, window_name, settings);
        win.window.focus();
    } else if (type == 'modal') {
        var html = '';
        html += '<div id="app_common_modal">';
        html += '<div class="app_modal_body"><a href="javascript:void(0);" id="app_common_modal_close">X</a><iframe src="' + page_url + '" frameborder="0"></iframe></div>';
        html += '</div>';

        if (!$('#app_common_modal').length) {

            $('body').append(html);
        }
        $('#app_common_modal').fadeIn();
    }

}

function popErrorModal(errors) {
				
    var errors = [errors];
    var li = '';
    $.each(errors, function (key, value) {
    li += '<li>' + value + '</li>';
    });

    var html = '';
    html += '<div id="error_handler_overlay">';
    html += '<div class="error_handler_body"><a href="javascript:void(0);" id="error_handler_overlay_close">X</a><ul>' + li + '</ul></div>';
    html += '</div>';

    $('body').append(html);
    $("#preloader").hide();
    $('.popup-loading-wrapper').hide();
    $('#loading-indicator').hide();
    $('#loading-screen').hide();
        
    $('#error_handler_overlay').fadeIn(500);
    return false;
}

function GetCardType(number)
{
    // visa
    var re = new RegExp("^4");
    if (number.match(re) != null)
        return "visa";

    // Mastercard 
    // Updated for Mastercard 2017 BINs expansion
        if (/^(5[1-5][0-9]{14}|2(22[1-9][0-9]{12}|2[3-9][0-9]{13}|[3-6][0-9]{14}|7[0-1][0-9]{13}|720[0-9]{12}))$/.test(number)) 
        return "master";

    // AMEX
    re = new RegExp("^3[47]");
    if (number.match(re) != null)
        return "amex";

    // Discover
    re = new RegExp("^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)");
    if (number.match(re) != null)
        return "discover";

    // Diners
    re = new RegExp("^36");
    if (number.match(re) != null)
        return "diners";

    // Diners - Carte Blanche
    re = new RegExp("^30[0-5]");
    if (number.match(re) != null)
        return "diners";

    // JCB
    re = new RegExp("^35(2[89]|[3-8][0-9])");
    if (number.match(re) != null)
        return "jcb";

    // Visa Electron
    re = new RegExp("^(4026|417500|4508|4844|491(3|7))");
    if (number.match(re) != null)
        return "none";

    return "";
}

function LuhnAlgorithm(num){

    var inputNum = num.toString();
    var sum = 0;
    var doubleUp = false;

    /* from the right to left, double every other digit starting with the second to last digit.*/
    for (var i = inputNum.length - 1; i >= 0; i--)
    {
        var curDigit = parseInt(inputNum.charAt(i));

        /* double every other digit starting with the second to last digit */
        if(doubleUp)
        {
            /* doubled number is greater than 9 than subtracted 9 */
            if((curDigit*2) > 9)
            {
              sum +=( curDigit*2)-9;
            }
            else
            {
              sum += curDigit*2;
            }
        }
        else
        {
          sum += curDigit;
        }
        var doubleUp =!doubleUp
    }

  /* sum and divide it by 10. If the remainder equals zero, the original credit card number is valid.  */
  //return (sum % 10) == 0  ? true : false;
    return true;
};

function clearTimer(){
    $('.loading-screen .show-1, .loading-screen .show-2, .loading-screen .show-3, .loading-screen .show-4').removeClass("active");

    if((s1Tmr)) {
        clearTimeout(s1Tmr);
    }
    if((s2Tmr)) {
        clearTimeout(s2Tmr);
    }
    if((s3Tmr)) {
        clearTimeout(s3Tmr);
    }
}

$(document).ready(function () {
    fphone.mask('000-000-0000');
    fbillCard.mask("0000 0000 0000 0000");
    fshipZip.blur(function(e) { 
        let country='US';
        $.ajax({
            url: "https://api.zippopotam.us/"+country+"/" + $(this).val(),
            method: 'GET',
            dataType: 'json',
            success: function(data) {
                try {
                    if (data.places[0]["state abbreviation"]) {
                        fshipState.val(data.places[0]["state abbreviation"]);   
                        fshipState.trigger('blur');
                    }
                    if (data.places[0]["place name"]) {
                        fshipCity.val(data.places[0]["place name"]);   
                        
                        fshipCity.trigger('blur');
                    }
                } catch(e) {}
            },
            error: function(xhr) { console.log(xhr.status); }
        });
    });
    fbillZip.blur(function(e) { 
        let country='US';
        $.ajax({
            url: "https://api.zippopotam.us/"+country+"/" + $(this).val(),
            method: 'GET',
            dataType: 'json',
            success: function(data) {
                try {
                    if (data.places[0]["state abbreviation"]) {
                        fbillState.val(data.places[0]["state abbreviation"]);   
                        fbillState.trigger('blur');
                    }
                    if (data.places[0]["place name"]) {
                        fbillCity.val(data.places[0]["place name"]);   
                        
                        fbillCity.trigger('blur');
                    }
                } catch(e) {}
            },
            error: function(xhr) { console.log(xhr.status); }
        });
    });
});