var modalAlert;

/*---------- ADD COMMAS TO NUMBERS -------------*/

function numberWithCommas(x) {

    var parts = x.toString().split(".");

    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");

    return parts.join(".");

}

/* ----- SWAP MODALS -----*/

function swap_modal(hideModalID, showModalID) {

    $(hideModalID).modal('hide');

    $(showModalID).modal('show');

}

/*------ CHCK IF WE NEED TO RELOAD THE PAGE ON LOGIN OR REGISTRATION ------*/

function reload_customer_page_check() {

    var pathname = window.location.pathname;

    if (pathname.indexOf("/customers/cart") !== -1) {

        location.reload();

    }

}

/* ------ CUSTOMER REGISTRATION AJAX SCRIPT ---------- */

function customer_registration(productID) {

    productID = productID || null; //Fix for ie errors - doesn't like default parameters


    var responseError = "";

    var responseMessage = "";

    $.ajax({

        'async': false,

        type: "POST",

        url: "/customers/register_json/",

        data: {

            first_name: document.getElementById("customer_registration_first_name").value,

            last_name: document.getElementById("customer_registration_last_name").value,

            company: document.getElementById("customer_registration_company").value,

            email: document.getElementById("customer_registration_email").value,

            phone: document.getElementById("customer_registration_phone").value,

            username: document.getElementById("customer_registration_username").value,

            password: document.getElementById("customer_registration_password").value

        },

        dataType: 'JSON',

        success: function(response) {

            responseError = response.error;

            responseMessage = response.message;

        }

    });

    if (responseError === true) {

        document.getElementById("customer_registration_alert").innerHTML = responseMessage;

        document.getElementById("customer_registration_alert").className = "alert alert-danger modal-alert modal-error-alert";

        document.getElementById("customer_registration_alert").style.display = "block";

    } else {

        toggleLoginClasses();

        update_shopping_cart_total_items();

        reload_customer_page_check();

        if (productID !== null) {

            document.getElementById("customer_registration_alert").innerHTML = responseMessage;

            document.getElementById("customer_registration_alert").className = "modal-alert modal-success-alert";

            document.getElementById("customer_registration_alert").style.display = "block";

        } else {

            document.getElementById("customer_registration_alert").innerHTML = responseMessage;

            document.getElementById("customer_registration_alert").className = "modal-alert modal-success-alert";

            document.getElementById("customer_registration_alert").style.display = "block";

        }

        setTimeout(function() {

            $("#modalCustomerRegister").modal('hide');

            document.getElementById("customer_registration_alert").style.display = "none";

        }, 2000);

    }

    return false;

}

/* ------ CUSTOMER LOGIN AJAX SCRIPT ---------- */

function customer_login(productID) {
    productID = productID || null;
    var responseError = "";
    var responseMessage = "";
    $.ajax({
        'async': false,
        type: "POST",
        url: "/customers/login_json/",
        data: {
            username: document.getElementById("customer_login_username").value,
            password: document.getElementById("customer_login_password").value
        },
        dataType: 'JSON',
        success: function(response) {
            responseError = response.error;
            responseMessage = response.message;
            $(".loggedIn").css('display', 'flex');
            $(".loggedOut").css('display', 'none');
        }

    });

    if (responseError === true) {

        document.getElementById("customer_login_alert").innerHTML = responseMessage;

        document.getElementById("customer_login_alert").className = "alert alert-danger modal-alert modal-error-alert";

        document.getElementById("customer_login_alert").style.display = "block";

    } else {
        toggleLoginClasses();
        update_shopping_cart_total_items();
        reload_customer_page_check();

        if (productID !== null) {

            document.getElementById("customer_login_alert").innerHTML = responseMessage;

            document.getElementById("customer_login_alert").className = "alert alert-success modal-alert modal-success-alert";

            document.getElementById("customer_login_alert").style.display = "block";

        } else {

            document.getElementById("customer_login_alert").innerHTML = responseMessage;

            document.getElementById("customer_login_alert").className = "alert alert-success modal-alert modal-success-alert";

            document.getElementById("customer_login_alert").style.display = "block";

        }

        setTimeout(function() {

            $("#modalCustomerLogin").modal('hide');

            document.getElementById("customer_login_alert").style.display = "none";

        }, 2000);

    }

    return false;

}

function toggleLoginClasses() {
    var preLoginNav = $(".pre-customer-login");

    for (var i = 0; i < preLoginNav.length; i++) {

        preLoginNav[i].style.display = "none";
        $(preLoginNav[i]).toggleClass("d-none");

    }

    var postLoginNav = $(".post-customer-login");

    for (i = 0; i < postLoginNav.length; i++) {
        postLoginNav[i].style.display = "inline";
        $(postLoginNav[i]).toggleClass("d-none");
    }
}

/** ------ PRODUCT UPSELL FUNCTIONS ------- */

function product_upsell(upsell) {
    var upsellModal = $("#upsellContent");
    upsellModal.html('');
    $.each(upsell.products, function(index, data) {
        $.ajax({
            type: "POST",
            url: "/products/upsell",
            data: { productid: data.productid },
            dataType: "json"
        }).done(function(response) {
            var productData = response.product;
            var relatedProducts = $("<div class='row m-top-10 m-bottom-10' style='border-top: dotted 1px #ccc;padding:15px 0px'></div>").html(function(i, content) {
                var productHTML = "";
                //Thumbnail
                if (data.image) {
                    productHTML += '<div class="col-md-3"><img style="height:auto;width:100%;" src="' + data.image + '"/></div>';
                } else {
                    productHTML += '<div class="col-md-3"><img style="height:auto;width:100%;" src="' + productData.image + '"/></div>';
                }
                //Product Description
                if (data.name) {
                    productHTML += '<div class="col-md-9"><h4>' + data.name + '</h4>';
                } else {
                    productHTML += '<div class="col-md-9"><h4>' + productData.name + '</h4>';
                }
                if (data.summary) {
                    productHTML += '<p>' + data.summary + '</p>';
                } else {
                    productHTML += productData.summary;
                }
                //Buttons
                productHTML += '<p>';
                if (productData.productid) {
                    if (productData.upsell) {
                        productHTML += '<button style="margin-right:10px class="add_to_cart btn btn-primary btn-sm" data-upsell="' + productData.upsell + '"';
                    } else {
                        productHTML += '<button style="margin-right:10px" class="add_to_cart btn btn-primary btn-sm" data-upsell=""';
                    }
                    productHTML += 'data-product="' + productData.productid + '"';
                    if (productData.productOptions) {
                        productHTML += 'data-product-options="1:1,' + productData.productOptions + '>';
                    }
                    productHTML += '<em class="fa fa-shopping-cart"></em> Add To Cart</button>';
                }
                if (data.url) {
                    productHTML += '<a href="' + data.url + '" class="btn btn-default">Learn More</a>';
                } else {
                    productHTML += '<a href="/product/' + productData.productid + '" class="btn btn-default">Learn More</a>';
                }
                productHTML += '</p></div>';
                return productHTML;
            });
            upsellModal.append(relatedProducts);
        });
    });
}

$("#productUpsell").on('hidden.bs.modal', function() {
    $('#upsellContent').html('');
});

/** ------ ADD PRODUCT TO CART BUTTON FUNCTION ------- */

function add_product_to_cart(productID, variantID, productOptionValues, cloneName) {
    productOptionValues = productOptionValues || null;
    cloneName = cloneName || null;
    $.ajax({
        type: "GET",
        url: "/customers/check_login_json/",
        dataType: 'JSON',
    }).done(function(response) {
        if (response.error) {
            $("#modalCustomerRegister").modal('show');
        } else {
            display_add_2_cart_modal(productID, variantID, productOptionValues, cloneName);
        }
    });
}

$(document).on('click', '.add_to_cart', function() {
    if (modalAlert) {
        clearTimeout(modalAlert);
        $("#notification").fadeOut("fast");
    }
    var ProductOptions = "";
    var cloneName = "";
    var variantID = 0;
    if ($(this).data("product-options")) {
        ProductOptions = $(this).data("product-options");
    }
    if ($(this).data("variant")) {
        variantID = $(this).data("variant");
    }
    if ($(this).data("clone")) {
        cloneName = $(this).data("clone");
    }
    var button = $(this);
    button.prop("disabled", true);

    add_product_to_cart($(this).data("product"), variantID, ProductOptions, cloneName);

    //Upsell Modal
    var upsell = $(this).data("upsell");
    if (upsell) {
        product_upsell(upsell);
    }
    $(document).ajaxComplete(function() {
        button.prop("disabled", false);
    });

});

/* ------ FORGOT PASSWORD ------ */

$('#forgotPasswordLink').on('click', function() {

    $('#forgot_password_alert').hide();

    $('#customer_login').val('');

    $('#forgot_password .md-form').show();


});

$('#forgot_password').on('submit', function(event) {

    var user = $('#customer_login').val();

    var message = 'If there is an account associated with ' + user + ', a password reset email will be sent.';

    $('#forgot_password_alert').addClass('alert alert-info');

    $('#forgot_password_alert').text(message);

    $('#forgot_password_alert').show();

    $('#forgot_password .md-form').hide();

    $.ajax({
        type: "POST",
        url: '/Customers/forgot_password',
        data: 'user=' + user,
        dataType: 'JSON'
    })
    $('#forgot_password .modal-footer button').attr('disabled', true);

    event.preventDefault();

});

/* ------ RESET PASSWORD ------ */

$('#resetPassword').on('submit', function(e) {

    var password = $('[name="password"]').val();

    var confirmPassword = $('[name="confirmPassword"]').val();

    if (password != confirmPassword) {

        $('#resetPassword .alert').show("fast");

        $('#resetPassword .alert').text("Error: Passwords must match");

        e.preventDefault();

    }

});

/* ------ UPDATE CART ITEM ------- */

$(document).on('click', '.update_cart_item', function() {

    var ProductOptions = "";

    if ($(this).data("product-options") !== "") {

        ProductOptions = $(this).data("product-options");

    }

    var productQuantity = "1";

    if ($(this).data("product-quantity") !== "") {

        productQuantity = $(this).data("product-quantity");

    }

    update_cart_items($(this).data("item-id"), $(this).data("product"), ProductOptions, productQuantity, $(this).data("order"));

});

function update_cart_items(itemID, productID, productOptionValues, productQuantity, orderID) {

    productOptionValues = productOptionValues || null;

    orderID = orderID || null;

    var responseError = "";

    var responseContent = "";

    if (productOptionValues !== null) {

        productOptionValues = productOptionValues.replace(/:/gi, '":"');

        productOptionValues = productOptionValues.replace(/,/gi, '","');

        productOptionValues = '{"values":{"' + productOptionValues + '"}}';

    }

    $.ajax({

        'async': false,

        type: "POST",

        url: "/products/get_modal_product_options/",

        data: {

            itemID: itemID,

            productID: productID,

            productQuantity: productQuantity,

            productOptionValues: productOptionValues

        },

        dataType: 'JSON',

        success: function(response) {

            responseError = response.error;

            responseContent = response.content;

        }

    });

    document.getElementById("updateCartItemID").value = itemID;

    document.getElementById("updateCartItemProductOptionList").innerHTML = responseContent;

    document.getElementById("updateCartItemModalPrice").innerHTML = "";

    update_edit_item_price(productID);

    $("#modalUpdateCartItem").modal('show');

}

function update_edit_item_price(productID, orderID) {

    orderID = orderID || null;

    var optionString = "";

    var productQuantity = document.getElementById('add2CartModalQuantity').value;

    if ($(".add-2-cart-modal-product-options")[0]) {

        var productOptions = $('.add-2-cart-modal-product-options');

        optionString = '{"options":{';

        for (var i = 0; i < productOptions.length; i++) {

            if (optionString !== '{"options":{') {

                optionString = optionString + ', ';

            }

            var optionID = productOptions[i].getAttribute('data-productOptionID');

            var optionValue = productOptions[i].value;

            optionString = optionString + '"' + optionID + '":"' + optionValue + '"';

        }

        optionString = optionString + "}}";

    }

    var responsePrice = "";

    $.ajax({

        'async': false,

        type: "POST",

        url: "/products/get-pricing/",

        data: {

            orderID: orderID,

            productID: productID,

            productOptions: optionString

        },

        dataType: 'JSON',

        success: function(response) {

            responsePrice = response.price;

        }

    });

    //alert(responsePrice);   //////// DELETE THIS!!!!!!!

    if (productQuantity === "") {

        $('#add2CartModalQuantity').val('1').change();

        productQuantity = 1;

    }

    if (responsePrice !== '') {

        responsePrice = responsePrice * productQuantity;

        responsePrice = responsePrice.toFixed(2);

        responsePrice = numberWithCommas(responsePrice);

        document.getElementById("updateCartItemModalPrice").innerHTML = "Total Price: $" + responsePrice;

    } else {

        document.getElementById("updateCartItemModalPrice").innerHTML = "";

    }

}


/*------- ADD ITEM TO ORDER --------*/

$(document).on('click', '.add_order_item', function() {

    add_order_item($(this).data('order-id'));

});

function add_order_item(orderID) {

    $("#modalAddToOrder").modal('show');

}

/* ------ PULL PRODUCT OPTIONS FOR MODAL ---------- */

function display_add_2_cart_modal(productID, variantID, productOptionValues, cloneName) {
    productOptionValues = productOptionValues || null;
    cloneName = cloneName || null;
    if (productOptionValues !== null) {
        productOptionValues = productOptionValues.replace(/:/gi, '":"');
        productOptionValues = productOptionValues.replace(/,/gi, '","');
        productOptionValues = '{"values":{"' + productOptionValues + '"}}';
    }
    $("#add2CartModalPrice").html("");
    var data = {
        productID: productID,
        variantID: variantID,
        productOptionValues: productOptionValues,

    };
    $.ajax({
        type: "POST",
        url: "/products/get_modal_product_options/",
        data: data,
        dataType: 'JSON'
    }).done(function(response) {
        var responseContent = response.content;
        //Modernizr Function
        // update_placeholder();
        $("#add2CartProductOptionList").html(responseContent);
        update_modal_product_price(productID, variantID, true, cloneName); // Show modal
    });


}

function display_add_2_order_modal(productID, orderID, productOptionValues) {
    productOptionValues = productOptionValues || null;
    var responseError = "";
    var responseContent = "";
    if (productOptionValues !== null) {
        productOptionValues = productOptionValues.replace(/:/gi, '":"');
        productOptionValues = productOptionValues.replace(',', '","');
        productOptionValues = '{"values":{"' + productOptionValues + '"}}';
    }
    $.ajax({
        type: "POST",
        url: "/products/get_modal_product_options/",
        data: {
            orderID: orderID,
            productID: productID,
            productOptionValues: productOptionValues
        },
        dataType: 'JSON',
    }).done(function(response) {
        responseError = response.error;
        responseContent = response.content;
        $("#add2OrderProductOptionList").html(responseContent);
        //Modernizr Function
        // update_placeholder();
        update_order_modal_product_price(productID, orderID);
        $('#modalAdd2Order').data('product', productID);
        $('#modalAdd2Order').data('order', orderID);
        $("#add2OrderModalPrice").html("");
    });
    swap_modal('#modalAddToOrder', '#modalAdd2Order');

}

/*------ UPDATE PRODUCT PRICE BASED ON OPTIONS SELECTED --------*/

function update_modal_product_price(productID, variantID, showModal, cloneName) {
    cloneName = cloneName || null;
    showModal = showModal || null;
    var optionString = "";
    var productQuantity = $('#add2CartModalQuantity').val();
    if ($(".add-2-cart-modal-product-options")[0]) {
        var productOptions = $('.add-2-cart-modal-product-options');
        optionString = '{"options":{';
        for (var i = 0; i < productOptions.length; i++) {
            if (optionString !== '{"options":{') {
                optionString = optionString + ', ';
            }
            var optionID = productOptions[i].getAttribute('data-productOptionID');
            var optionValue = productOptions[i].value;
            optionString = optionString + '"' + optionID + '":"' + optionValue + '"';
        }
        optionString = optionString + "}}";
    }
    if (productQuantity === "") {
        $('#add2CartModalQuantity').val('1').change();
        productQuantity = 1;
    }
    var build = $("#genomicBuild :selected").text().substr(6);
    $.ajax({
        type: "POST",
        url: "/products/get-alert/",
        data: {
            productID: productID,
            productOptions: optionString,
            clone: cloneName,
            build: build
        },
        dataType: 'JSON',
    }).done(function(response) {
        if (response.message) {
            $("#notification").hide();
            var alertMessage = "<p style='padding: 5px' class='text-center alert-warning'><b class='text-warning'>" + response.message + "</b></p>";
            $("#notification").html(alertMessage);
            $("#notification").fadeToggle("fast");
            var timeout = response.timeout || 12000;
            modalAlert = setTimeout(function() {
                $("#notification").fadeOut("fast");
            }, timeout);
        }
    });
    var data = {
        productID: productID,
        productOptions: optionString
    };
    if (variantID !== 0) {
        data['variantID'] = variantID
    }
    $.ajax({
        type: "POST",
        url: "/products/get-pricing/",
        data: data,
        dataType: 'JSON',
    }).done(function(response) {
        var responsePrice = response.price;

        if (responsePrice != '') {
            responsePrice = responsePrice * productQuantity;
            responsePrice = responsePrice.toFixed(2);
            responsePrice = numberWithCommas(responsePrice);
            if ($("#add2CartModalPrice"))
                $("#add2CartModalPrice").text("Total Price: $" + responsePrice);
            if ($("#updateCartItemModalPrice"))
                $("#updateCartItemModalPrice").text("Total Price: $" + responsePrice);
        } else {
            $("#add2CartModalPrice").text("");
        }
        if (showModal) {
            $("#productUpsell").modal('hide');
            $("#modalAdd2Cart").modal('show');
        }
    });

}


/*---------- UPDATE THE SHOPPING CART -------------*/

function update_shopping_cart_total_items() {
    var totalItems = "";
    $.ajax({
        type: "POST",
        url: "/customers/get_cart_total_items/JSON",
        dataType: 'JSON',
    }).done(function(response) {
        totalItems = response.total;
        $('#cartTotalItems').text(totalItems);
    });
}

/*------------ DELETE ITEM FROM CART --------------*/

function delete_item_from_cart(itemID) {

    document.getElementById('deleteCartItemID').value = itemID;

    $("#modalDeleteCartItemConfirmation").modal('show');

}

/*------------ DISPLAY SELECT ADDRESS MODAL ---------------*/

function select_address_modal(addressType) {

    var addressOptions = "";

    $.ajax({

        'async': false,

        type: "POST",

        url: "/customers/pull_customer_addresses_for_modal",

        data: {},

        dataType: 'JSON',

        success: function(response) {

            addressOptions = response.addresses;

        }

    });

    document.getElementById("selectAddressOptions").innerHTML = addressOptions;

    document.getElementById("selectAddressType").value = addressType;

    $("#modalSelectCustomerAddress").modal('show');

}

/*----------- UPDATE ADDRESS FROM MODAL --------------*/

function update_checkout_address(addressID) {

    var addressType = document.getElementById("selectAddressType").value;

    var addressContent = "";

    $.ajax({

        'async': false,

        type: "POST",

        url: "/customers/pull_address_by_id_json",

        data: {

            addressID: addressID

        },

        dataType: 'JSON',

        success: function(response) {

            addressContent = response.address;

        }

    });

    if (addressType == "Billing") {

        document.getElementById("billingAddressContainer").innerHTML = addressContent;

        document.getElementById("orderBillingAddressID").value = addressID;

    }

    if (addressType == "Shipping") {

        document.getElementById("shippingAddressContainer").innerHTML = addressContent;

        document.getElementById("orderShippingAddressID").value = addressID;

        if (addressContent.includes("United States") || addressContent.includes("Canada")) {

            document.getElementById("checkoutShippingPrice").innerHTML = "50.00";

        } else {

            document.getElementById("checkoutShippingPrice").innerHTML = "150.00";

        }

        update_checkout_pricing();

    }

    $('.modal').modal('hide');

}

/*----------- CHECK IF TO DISPLAY STATE ---------------*/

function country_state_check(inputName) {

    var countryCode = document.getElementById(inputName + "Country").value;

    if (countryCode == "US") {

        document.getElementById(inputName + "State").required = true;

        document.getElementById(inputName + "State").disabled = false;

    } else {

        document.getElementById(inputName + "State").disabled = true;

        document.getElementById(inputName + "State").selectedIndex = 0;

        document.getElementById(inputName + "State").required = false; //newCustomerAddress

    }

}

function admin_country_state_check(inputName) {

    var countryCode = $('#' + inputName + 'Country option:selected').val();

    if (countryCode == "US") {

        document.getElementById(inputName + "State").required = true;

        document.getElementById(inputName + "State").disabled = false;

    } else {

        document.getElementById(inputName + "State").disabled = true;

        document.getElementById(inputName + "State").selectedIndex = 0;

        document.getElementById(inputName + "State").required = false; //newCustomerAddress

    }

}

/*----------- CREATE NEW ADDRESS ------------*/

function checkout_create_new_address() {

    var addressType = document.getElementById("selectAddressType").value;

    var defaultShipping = "N";

    var defaultBilling = "N";

    // DETERMINE IF SET tO BE DEFAULT SHIPPING

    if (document.getElementById("newCustomerAddressDefaultShipping").checked === true) {

        defaultShipping = "Y";

    } else {

        defaultShipping = "N";

    }

    // DETERMINE IF SET tO BE DEFAULT BILLING

    if (document.getElementById("newCustomerAddressDefaultBilling").checked === true) {

        defaultBilling = "Y";

    } else {

        defaultBilling = "N";

    }

    // POST TO CREATE NEW ADDRESS

    var addressID = "";

    $.ajax({

        'async': false,

        type: "POST",

        url: "/customers/create_new_address_json",

        data: {

            newCustomerAddressFirstName: document.getElementById("newCustomerAddressFirstName").value,

            newCustomerAddressLastName: document.getElementById("newCustomerAddressLastName").value,

            newCustomerAddressAddress1: document.getElementById("newCustomerAddressAddress1").value,

            newCustomerAddressAddress2: document.getElementById("newCustomerAddressAddress2").value,

            newCustomerAddressCity: document.getElementById("newCustomerAddressCity").value,

            newCustomerAddressState: document.getElementById("newCustomerAddressState").value,

            newCustomerAddressCountry: document.getElementById("newCustomerAddressCountry").value,

            newCustomerAddressZipcode: document.getElementById("newCustomerAddressZipcode").value,

            newCustomerAddressPhone: document.getElementById("newCustomerAddressPhone").value,

            newCustomerAddressFax: document.getElementById("newCustomerAddressFax").value,

            newCustomerAddressDefaultShipping: defaultShipping,

            newCustomerAddressDefaultBilling: defaultBilling

        },

        dataType: 'JSON',

        success: function(response) {

            addressID = response.addressID;

        }

    });

    // NOW LETS DISPLAY THE NEW ADDRESS

    update_checkout_address(addressID);

    // RETURN FALSE TO PREVENT FORM FROM SUBMITTING

    return false;

}

/*---------- UPDATE CUSTOMER ADDRESS ------------*/

function display_update_customer_address_modal(addressID) {

    var addressData = "";

    $.ajax({

        'async': false,

        type: "POST",

        url: "/customers/get_address_info_json",

        data: {

            addressID: addressID

        },

        dataType: 'JSON',

        success: function(response) {

            addressData = response;

        }

    });

    document.getElementById("updateCustomerAddress").value = addressData.id;

    document.getElementById("editCustomerAddressFirstName").value = addressData.firstname;

    document.getElementById("editCustomerAddressLastName").value = addressData.lastname;

    document.getElementById("editCustomerAddressAddress1").value = addressData.address1;

    document.getElementById("editCustomerAddressAddress2").value = addressData.address2;

    document.getElementById("editCustomerAddressCity").value = addressData.city;

    document.getElementById("editCustomerAddressState").value = addressData.state;

    document.getElementById("editCustomerAddressCountry").value = addressData.country;

    if (addressData.country !== "US") {

        document.getElementById("editCustomerAddressState").disabled = true;

        document.getElementById("editCustomerAddressState").selectedIndex = 0;

        document.getElementById("editCustomerAddressState").required = false;

    }

    document.getElementById("editCustomerAddressZipcode").value = addressData.zipcode;

    document.getElementById("editCustomerAddressPhone").value = addressData.phone;

    document.getElementById("editCustomerAddressFax").value = addressData.fax;

    if (addressData.default_s == "Y") {

        document.getElementById("editCustomerAddressDefaultShipping").checked = true;

    } else {

        document.getElementById("editCustomerAddressDefaultShipping").checked = false;

    }

    if (addressData.default_b == "Y") {

        document.getElementById("editCustomerAddressDefaultBilling").checked = true;

    } else {

        document.getElementById("editCustomerAddressDefaultBilling").checked = false;

    }

    $('#modalUpdateCustomerAddress').modal('show');

}

/*-------------- APPLY COUPON CODE ----------------*/

function apply_coupon_code(e) {
    e.preventDefault();
    var couponCode = document.getElementById("couponCode").value

    document.getElementById("orderCouponCode").value = couponCode;

    update_checkout_pricing();

}

/*-------------- CALCULATE AND UPDATE CHECKOUT PRICING ----------------*/

function update_checkout_pricing() {
    $.ajax({
        type: "POST",
        url: "/customers/update_checkout_pricing",
        data: {
            couponCode: $("#orderCouponCode").val(),
            shippingAddressID: $("#orderShippingAddressID").val()
        },
        dataType: 'JSON'
    }).done(function(response) {
        var discountAmount = response.discountAmount;
        var savings = response.savings;
        var shippingPrice = response.shippingPrice;
        var totalPrice = response.totalPrice;
        var credit = response.credit;

        $("#checkoutTotalPrice").html(totalPrice);
        $("#payment-form #amount").val(totalPrice.replace(',', ''));
        if (
            (discountAmount == "0.00" &&
                $("#orderCouponCode").val() !== "" &&
                shippingPrice != "0.00") ||
            response.error
        ) {
            $("#couponAlert").html("Invalid Coupon Code");
        }
        if (
            (discountAmount !== "0.00" || shippingPrice == "0.00") &&
            !response.error
        ) {
            $("#checkoutShippingPrice").html(shippingPrice);
            if (discountAmount !== "0.00") {
                $("#checkoutDiscount").html(discountAmount);
                $("#discountLine").show();
            }
            $("#couponAlert").html("Coupon Code Applied");
        } else {
            $("#discountLine").hide();
        }
        if (credit !== "0.00") {
            $("#checkoutCreditsApplied").html(credit);
            $("#creditsAppliedLine").show();
        }
        if (savings !== "0.00") {
            $("#checkoutSavings").html(savings);
            $("#savingsLine").show();
        } else {
            $("#savingsLine").hide();
        }
    });

}

/*------------ UPDATE PAYMENT METHOD --------------*/

function update_payment_method(paymentMethod) {
    if (paymentMethod == "Credit Card") {
        //NEW
        document.getElementById("first_name").required = true;
        document.getElementById("last_name").required = true;
        document.getElementById("cardnumber").required = true;
        document.getElementById("cardnumber").required = true;
        document.getElementById("expmonth").required = true;
        document.getElementById("expyear").required = true;
        document.getElementById("cvv2").required = true;


        document.getElementById("PONumber").required = false;

        document.getElementById("POCompany").required = false;

        document.getElementById("POBuyer").required = false;

        document.getElementById("POPosition").required = false;

        document.getElementById('orderPaymentMethod').value = paymentMethod;

        //OLD
        if (document.getElementById("CCName")) {
            document.getElementById("CCName").required = true;
            document.getElementById("CCNumber").required = true;
            document.getElementById("CCDate").required = true;
            document.getElementById("CCCVV").required = true;

        }

    }

    if (paymentMethod == "Purchase Order") {
        //NEW
        document.getElementById("first_name").required = false;
        document.getElementById("last_name").required = false;
        document.getElementById("cardnumber").required = false;
        document.getElementById("cardnumber").required = false;
        document.getElementById("expmonth").required = false;
        document.getElementById("expyear").required = false;
        document.getElementById("cvv2").required = false;

        document.getElementById("PONumber").required = true;

        document.getElementById("POCompany").required = true;

        document.getElementById("POBuyer").required = true;

        document.getElementById("POPosition").required = true;

        document.getElementById('orderPaymentMethod').value = paymentMethod;

        //OLD
        if (document.getElementById("CCName")) {
            document.getElementById("CCName").required = false;
            document.getElementById("CCNumber").required = false;
            document.getElementById("CCDate").required = false;
            document.getElementById("CCCVV").required = false;
        }

    }

}

/*------------- SUBMIT ORDER ----------------*/

function submit_order() {

    if ($("#orderShippingAddressID").val() === "") {

        $("#submitOrderAlert").html("Please Select Your Shipping Address");

        $("#submitOrderAlert").show();

        return false;

    } else if ($("#orderBillingAddressID").val() === "") {

        $("#submitOrderAlert").html("Please Select Your Billing Address");

        $("#submitOrderAlert").show();

        return false;

    } else {

        return true;

    }


}

/*------------ ADD CUSTOMER EMAIL ADDRESS --------------*/

function add_customer_email_address() {

    // CREATE THE NEW EMAIL

    var emailAddresses = "";

    var error;

    $.ajax({

        'async': false,

        type: "POST",

        url: "/customers/add_email_address",

        data: {

            emailAddress: document.getElementById("newCustomerEmail").value

        },

        dataType: 'JSON',

        success: function(response) {

            emailAddresses = response.emailAddresses;

            error = response.message;

        }

    });

    if (error) {


        document.getElementById("new_customer_email_alert").innerHTML = error;

        document.getElementById("new_customer_email_alert").style.display = "block";

        setTimeout(function() {

            $("#modalNewCustomerEmail").modal('hide');

            document.getElementById("new_customer_email_alert").style.display = "none";

            document.getElementById("new_customer_email_alert").innerHTML = "";

        }, 2000);


    } else {


        // UPDATE THE EMAIL ADDRESSES ON THE PAGE

        document.getElementById("customer_email_addresses").innerHTML = emailAddresses;

        document.getElementById("newCustomerEmail").value = "";

        // SET THE ALERT

        document.getElementById("new_customer_email_alert").innerHTML = "Email Address Added";

        document.getElementById("new_customer_email_alert").style.display = "block";

        setTimeout(function() {

            $("#modalNewCustomerEmail").modal('hide');

            document.getElementById("new_customer_email_alert").style.display = "none";

            document.getElementById("new_customer_email_alert").innerHTML = "";

        }, 2000);

    }

    return false;

}

function admin_update_customer_email_address() {

}

function admin_add_customer_email_address() {

    // CREATE THE NEW EMAIL
    var emailAddresses = "";
    var error;
    //var customerID = $("#customer_email_addresses em").data('customer');
    var customerID = $("#add-email").data('customer');
    $.ajax({
        type: "POST",
        url: "/admin/customers/add_email_address",
        data: {
            customer: customerID,
            emailAddress: document.getElementById("newCustomerEmail").value
        },
        dataType: 'JSON'
    }).done(function(response) {
        emailAddresses = response.emailAddresses;
        error = response.message;
        if (error) {

            document.getElementById("new_customer_email_alert").innerHTML = error;

            document.getElementById("new_customer_email_alert").style.display = "block";

            setTimeout(function() {

                $("#modalNewCustomerEmail").modal('hide');

                document.getElementById("new_customer_email_alert").style.display = "none";

                document.getElementById("new_customer_email_alert").innerHTML = "";

            }, 2000);


        } else {
            var emails = response.data;
            // UPDATE THE EMAIL ADDRESSES ON THE PAGE
            buildEmails(emails);
            // SET THE ALERT
            document.getElementById("new_customer_email_alert").innerHTML = "Email Address Added";
            document.getElementById("new_customer_email_alert").style.display = "block";
            setTimeout(function() {
                $("#modalNewCustomerEmail").modal('hide');
                document.getElementById("new_customer_email_alert").style.display = "none";
                document.getElementById("new_customer_email_alert").innerHTML = "";
            }, 2000);
        }
    });
    return false;
}

function buildEmails(emails) {
    var emailHTML = '';
    $.each(emails, function(index, email) {
        emailHTML += '<tr>'
            + '<td><input class="secondary-email form-control" type="text" name="emails[' + email.customer_id + '][email]" value="' + email.email + '"></td>'
            + '<td class="text-center"><input class="subscribe" type="checkbox" checked="" name="emails[' + email.customer_id + '][send_bes]" value="' + email.send_bes + '"></td>'
            + '<td class="text-center"><input class="subscribe" type="checkbox" checked="" name="emails[' + email.customer_id + '][send_order_receipts]" value="' + email.send_order_receipts + '"></td>'
            + '<td class="text-center"><input class="subscribe" type="checkbox" checked="" name="emails[' + email.customer_id + '][send_invoices]" value="' + email.send_invoices + '"></td>'
            + '<td><button data-email="' + email.id + '" class="delete btn btn-danger"><i class="fa fa-times-circle"></i>Delete </button></td>'
            + '</tr>';
    });
    $("#subscriptions tbody").html(emailHTML);
}

/*--------- DELETE CUSTOMER EMAIL ADDRESS -----------*/

function delete_customer_email(emailID) {

    // CREATE THE NEW EMAIL

    var emailAddresses = "";

    $.ajax({

        'async': false,

        type: "POST",

        url: "/customers/delete_email_address",

        data: {

            deleteEmailID: emailID

        },

        dataType: 'JSON',

        success: function(response) {

            emailAddresses = response.emailAddresses;

        }

    });

    document.getElementById("customer_email_addresses").innerHTML = emailAddresses;

}

function admin_delete_customer_email(customerID, emailID) {
    $.ajax({
        type: "POST",
        url: "/admin/customers/delete_email_address",
        data: {
            customer: customerID,
            deleteEmailID: emailID
        },
        dataType: 'JSON'
    }).done(function(response) {
        var emails = response.data;
        buildEmails(emails);
    });
}

/*---------- UPDATE CUSTOMER ACCOUNT -----------*/

function update_customer_account(customerID) {
    var message = "";
    $.ajax({
        type: "POST",
        url: "/customers/update_customer_account",
        data: {
            customerID: customerID,
            first_name: $("#customer_account_first_name").val(),
            last_name: $("#customer_account_last_name").val(),
            company: $("#customer_account_company").val(),
            taxid: $("#customer_account_taxid").val(),
            phone: $("#customer_account_phone").val(),
            email: $("#customer_email_address").val(),
            membershipid: $("#customer_membershipid").val(),
            username: $("#customer_account_username").val(),
            password: $("#customer_account_password").val(),
            cpassword: $("#customer_account_cpassword").val(),
            store_credit: $("#customer_account_credit").val(),
            default_shipping_rate: $("#customer_account_shipping_rate").val(),
            wire_transfer_fee: $("#customer_account_wire_transfer_fee").val(),
            international_sale: $("#customer_account_international_sales :selected").val(),
        },
        dataType: 'JSON',
    }).done(function(response) {
        message = response.message;
        $("#account_update_alert").html(message);
        $("#account_update_alert").css("display", "block");
        $("#customer_account_password").val("");
        $("#customer_account_cpassword").val("");
    });

    $(this).submit(function(e) {
        e.preventDefault();
    });
    //return false;

}

/*------ REMOVE OPTIONS FROM SELECT BOX ---------*/

function removeOptions(selectbox) {

    var i;

    for (i = selectbox.options.length - 1; i >= 0; i--) {

        selectbox.remove(i);

    }

}

/*---------- ORDER A FUSION PROBE --------------*/

function change_dropdown() {

    var opt = "";

    var gene1color = document.getElementById("gene1color").value;

    removeOptions(document.getElementById("gene2color"));

    if (gene1color === "Orange") {

        opt = document.createElement('option');

        opt.value = "Green";

        opt.innerHTML = "Green";

        document.getElementById('gene2color').appendChild(opt);

    }

    if (gene1color === "Green") {

        opt = document.createElement('option');

        opt.value = "Orange";

        opt.innerHTML = "Orange";

        document.getElementById('gene2color').appendChild(opt);

        opt = document.createElement('option');

        opt.value = "Red";

        opt.innerHTML = "Red";

        document.getElementById('gene2color').appendChild(opt);

        opt = document.createElement('option');

        opt.value = "Gold";

        opt.innerHTML = "Gold";

        document.getElementById('gene2color').appendChild(opt);

    }

    if (gene1color === "Red") {

        opt = document.createElement('option');

        opt.value = "Green";

        opt.innerHTML = "Green";

        document.getElementById('gene2color').appendChild(opt);

        opt = document.createElement('option');

        opt.value = "Gold";

        opt.innerHTML = "Gold";

        document.getElementById('gene2color').appendChild(opt);

    }

    if (gene1color === "Gold") {

        opt = document.createElement('option');

        opt.value = "Green";

        opt.innerHTML = "Green";

        document.getElementById('gene2color').appendChild(opt);

    }

    if (gene1color === "") {

        opt = document.createElement('option');

        opt.value = "";

        opt.innerHTML = "Gene 2 Color";

        document.getElementById('gene2color').appendChild(opt);

    }

}

function order_fusion_probe() {
    if (document.getElementById('gene1color').value !== '' && document.getElementById('gene2color').value !== '' && document.getElementById('fusionGene1').value !== '' && document.getElementById('fusionGene2').value !== '') {
        var dyes = document.getElementById('gene1color').value + "-" + document.getElementById('gene2color').value;
        var genes = document.getElementById('fusionGene1').value + "-" + document.getElementById('fusionGene2').value;
        if (dyes === "Orange-Green") {
            dyes = "5341";
        }
        if (dyes === "Red-Green") {
            dyes = "5342";
        }
        if (dyes === "Red-Gold") {
            dyes = "6522";
        }
        if (dyes === "Gold-Green") {
            dyes = "5343";
        }
        if (dyes === "Green-Orange") {
            dyes = "5344";
        }
        if (dyes === "Green-Red") {
            dyes = "5345";
        }
        if (dyes === "Green-Gold") {
            dyes = "5346";
        }
        add_product_to_cart('16403', 0, "741:" + genes + ",740:" + dyes);
    } else {
        document.getElementById('fusionAlert').innerHTML = "Please Complete All Fields";
        document.getElementById('fusionAlert').style.display = "block";
        setTimeout(function() {
            document.getElementById('fusionAlert').style.display = "none";
            document.getElementById('fusionAlert').innerHTML = "";
        }, 2000);
    }
}

/***********HIDE SEARCH LINK***********/

$('#searchLink').on('click', function() {

    if ($('#headerSearch').hasClass('collapse')) {

        $('#searchLink').hide();

    }

});

/***********DELETE ORDER ITEM***********/

$('.delete_cart_item').on('click', function() {

    var itemID = $(this).data('item-id');

    //var orderID = $(this).data('order-id');

    var product = $(this).data('product');

    $('#modalDeleteOrderItem h4.title span').html(product);

    $("#modalDeleteOrderItem").modal('show');

    $('#modalDeleteOrderItem input[name="itemID"]').val(itemID);

    $("#modalDeleteOrderItem").on('click', '.btn-success', function() {


        $('#modalDeleteOrderItem input[name="confirm"]').val('Y');


        $('#modalDeleteOrderItem form').submit();

    });

});

/**
 * getDyes
 * @param sku {string}
 * @returns Builds HTML for Dyes from portion of Sku {string}
 */
function getDyes(sku) {
    var dyes;
    var html = "";
    var errorMessage = "Error: Invalid Sku";
    var standardDyes = ['AQ', 'GR', 'GO', 'OR', 'RE'];
    var specialDyes = ['DIG', 'BIO'];
    //Explode sku
    sku = sku.split("-");

    dyes = sku[sku.length - 1];
    var dyeColors = [];
    for (var i = 0; i < dyes.length; i++) {
        var dye = dyes[i].concat(dyes[++i]);
        switch (dye) {
            case standardDyes[0]:
                html += '<img title ="Aqua" class="m-bottom-10" src="/img/dye-dots/AQ.png" />';
                break;
            case standardDyes[1]:
                html += '<img title ="Green" class="m-bottom-10" src="/img/dye-dots/GR.png" />';
                break;
            case standardDyes[2]:
                html += '<img title ="Gold" class="m-bottom-10" src="/img/dye-dots/GO.png" />';
                break;
            case standardDyes[3]:
                html += '<img title ="Orange" class="m-bottom-10" src="/img/dye-dots/OR.png" />';
                break;
            case standardDyes[4]:
                html += '<img title ="Red" class="m-bottom-10" src="/img/dye-dots/RE.png" />';
                break;
            default:
                //Check for DIG
                if ((dye.concat(dyes[i + 1]) == specialDyes[0])) {
                    dye = dye.concat(dyes[i + 1]);
                    html += '<img title="Digoxin" class="m-bottom-10" src="/img/dye-dots/DIG.png"/>';
                    i++;//Account for extra character
                }
                //Check for BIO
                else if ((dye.concat(dyes[i + 1]) == specialDyes[1])) {
                    dye = dye.concat(dyes[i + 1]);
                    html += '<img title="Biotin" class="m-bottom-10" src="/img/dye-dots/BIO.png"/>';
                    i++; //Account for extra character
                }
                //Return Error
                else {
                    return errorMessage;
                }
        }
        dyeColors.push(dye);
    }
    if (validateDyes(dyeColors, standardDyes, specialDyes)) {
        return html;
    } else {
        return errorMessage;
    }
}

/**
 * validateColors
 * @param dyes - array of dyes to compare {array}{string}
 * @param standard 1st array to compare against {array}{string}
 * @param special 2nd array to compare against {array}{string}
 * @returns {boolean}
 */
function validateDyes(dyes, standard, special) {
    var hasStandardDye = false;
    var hasSpecialDye = false;
    //Look for standard dyes
    for (var i = 0; i < standard.length; i++) {
        if (dyes.indexOf(standard[i]) > -1) {
            hasStandardDye = true;
        }
    }
    //Look for special dyes
    for (i = 0; i < special.length; i++) {
        if (dyes.indexOf(special[i]) > -1) {
            hasSpecialDye = true;
        }
    }
    if (hasStandardDye && hasSpecialDye) {
        return false;
    }
    return true;
}

/**
 * formatExpirationDate
 * @param exp
 */
function formatExpirationDate(exp) {
    exp.on('keyup', function(e) {
        var mm = exp.val();
        // If not backspace
        if (e.keyCode != 8) {
            if (mm.length == 2 && !mm.includes('/')) {
                exp.val(mm + "/");
            }
        }
    });
    exp.on('blur', function(e) {
        var val = exp.val().split('/');
        var mm = val[0];
        var yy = val[1];
        if (mm.length < 2) {
            mm = mm.padStart(2, '0');
        }
        if (yy.length < 2) {
            yy = mm.padStart(2, '0');
        }
        exp.val(mm + '/' + yy);
    });

}
