/* Minification failed. Returning unminified contents.
(367,44-45): run-time error JS1100: Expected ',': =
(1211,9-10): run-time error JS1014: Invalid character: `
(1212,9-10): run-time error JS1195: Expected expression: <
(1216,94-95): run-time error JS1195: Expected expression: <
(1218,21-22): run-time error JS1197: Too many errors. The file might not be a JavaScript file: $
(1205,1-43): run-time error JS1301: End of file encountered before function is properly closed: function showAddedToCart(product, cartUrl)
(1219,17-18): run-time error JS1195: Expected expression: <
(1219,18-19): run-time error JS1197: Too many errors. The file might not be a JavaScript file: /
 */
function fitFrames(useAutoHt) {
    //New approach
    var maxSizes = [];
    var areImagesLoaded = true;

    $("[class*='resizeGroup-']:visible").each(function () {
        var groupObj = $(this);

        groupObj.find('img:visible').each(function () {
            if (groupObj.height() == 0) {
                areImagesLoaded = false;
            }
        });

        if (areImagesLoaded) {

            if (groupObj.data('height') == null) {
                groupObj.data('height', groupObj.height());
            }

            groupObj.css('height', 'auto');

            var ht = groupObj.height();
            var winWidth = Math.max($(window).width(), window.innerWidth)

            //If XS screen size and XS size is not defined, skip resize
            if (groupObj.is('[class*="col-"]') && !groupObj.is('[class*="col-xs-"]') && winWidth < 751) {
                return;
            } else if (!groupObj.is('[class*="col-"]') && !groupObj.closest('[class*="col-"]').is('[class*="col-xs-"]') && winWidth < 751) {
                return;
            }
            //If SM screen size and SM size is not defined, skip resize
            else if (groupObj.is('[class*="col-"]') && !groupObj.is('[class*="col-sm-"]') && winWidth < 992) {
                return;
            } else if (!groupObj.is('[class*="col-"]') && !groupObj.closest('[class*="col-"]').is('[class*="col-sm-"]') && winWidth < 992) {
                return
            }
            //If SM screen size and SM is not defined
            else if (groupObj.hasClass('col-sm-24') && winWidth < 1008) {
                return;
            }
            else {
                if ($('.ie').length > 0)
                    ht -= 30;
                groupObj.css('height', ht);
            }

            var index = groupObj.attr('class').match(/\bresizeGroup-(\d+)\b/)[1];

            if (maxSizes[index] == undefined) maxSizes[index] = 0;
            //console.log(index + ':' + $(this).height());
            maxSizes[index] = groupObj.height() > maxSizes[index] ? groupObj.height() : maxSizes[index];
        }
    });


    if (areImagesLoaded) {
        $.each(maxSizes, function (index, value) {
            if ($('.ie').length > 0)
                value += 30; // IE can't handle the padding

            if ($('.ie').length > 0 && window.location.pathname == '/resources/quality')
                value += 30;
            if (
                ($('.ie').length > 0 && window.location.pathname == '/medical')
                || ($('.ie').length > 0 && window.location.pathname == '/delivery')
                || ($('.ie').length > 0 && window.location.pathname == '/networking')
                || ($('.ie').length > 0 && window.location.pathname == '/industrial')
            )
                value -= 30;
            if ($('.ie').length > 0 && window.location.pathname == '/quality/pcn-notifications')
                value += 30;
            if ($('.ie').length > 0 && window.location.pathname == '/quality/eol-notifications')
                value += 30;

            if ($('.ie9,.ie8,.ie7,.ie6').length > 0 && window.location.pathname.indexOf("/product/") >= 0)
                value += 90;

            if ($('.ie8,.ie7,.ie6').length > 0 && window.location.pathname.indexOf("/product/") >= 0)
                value += 10;

            if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
                //value = value - 15;
            }

            $(".resizeGroup-" + index).each(function () {
                var groupObj = $(this);

                //If this is not the mobile size
                if (groupObj.is('[class*="col-"]') && !groupObj.is('[class*="col-xs-"]') && $(window).width() < 751) {
                    //Do nothing yet, but maybe will want too eventually
                }
                else if (groupObj.hasClass('col-sm-24') && $(window).width() < 1008) {

                }
                else {
                    groupObj.css('height', value);
                }
            });



            //console.log(index + ' : ' + value);
        });
    }

    //Old approach            
    $('.well-row-wrapper:not(.dontfitframes)').each(function () {
        if ($(".well-row-wrapper:not(.dontfitframes)").find("div[class*='resizeGroup-']").length < 1) {

            var maxHeight = 0;
            $(this).find('.well-row-item:not(.dontfitframes) .well-row-wrapper-text:not(.dontfitframes)').css('height', "");
            $(this).find('.well-row-item:not(.dontfitframes) .well-row-wrapper-text:not(.dontfitframes)').each(function () {
                maxHeight = $(this).height() > maxHeight ? $(this).height() : maxHeight;
            });
            $(this).find('.well-row-item:not(.dontfitframes) .well-row-wrapper-text:not(.dontfitframes)').css('height', maxHeight);


            maxHeight = 0;
            $(this).find('.well-row-item:not(.dontfitframes) .verysmallH1:not(.dontfitframes)').css('height', "");
            $(this).find('.well-row-item:not(.dontfitframes) .verysmallH1:not(.dontfitframes)').each(function () {
                maxHeight = $(this).height() > maxHeight ? $(this).height() : maxHeight;
            });
            $(this).find('.well-row-item:not(.dontfitframes) .verysmallH1:not(.dontfitframes)').css('height', maxHeight);


            maxHeight = 0;
            $(this).find('.well-row-item:not(.dontfitframes) article:not(.dontfitframes)').css('height', "");
            $(this).find('.well-row-item:not(.dontfitframes) article:not(.dontfitframes)').each(function () {
                maxHeight = $(this).height() > maxHeight ? $(this).height() : maxHeight;
            });
            $(this).find('.well-row-item:not(.dontfitframes) article:not(.dontfitframes)').css('height', maxHeight);


            maxHeight = 0;
            $(this).find('.well-row-item:not(.dontfitframes) ul:not(.dontfitframes').css('height', "");
            $(this).find('.well-row-item:not(.dontfitframes) ul:not(.dontfitframes').each(function () {
                maxHeight = $(this).height() > maxHeight ? $(this).height() : maxHeight;
            });
            $(this).find('.well-row-item:not(.dontfitframes) ul:not(.dontfitframes').css('height', maxHeight);

        }
    });
}

$(function () {
    /*Product Resources that are PDF's*/
    $(document).ready(function () {
        if (!document.URL.includes("catalog") && !document.URL.includes("product") && !document.URL.includes("sitesearch")) {

            var charList = ['&Alpha;', '&Beta;', '&Gamma;', '&Delta;', '&Epsilon;', '&Zeta;',
                '&Eta;', '&Theta;', '&Iota;', '&Kappa;', '&Lambda;', '&Mu;', '&Nu;',
                '&Xi', '&Omicron;', '&Pi;', '&Rho;', '&Sigma;', '&Tau;', '&Phi;',
                '&Chi;', '&Psi;', '&Omega;', '&alpha;', '&beta;', '&gamma;', '&delta;',
                '&epsilon;', '&zeta;', '&eta;', '&theta;', '&iota;', '&kappa;', '&lambda;',
                '&mu;', '&mu;', '&xi', '&omicron;', '&pi;', '&rho;', '&sigma;', '&tau;',
                '&phi;', '&chi;', '&psi;', '&omega;'];

            var encodedChars = [915, 916, 917, 918, 919, 920, 921, 922,
                923, 924, 925, 926, 927, 928, 929, 931,
                932, 933, 934, 935, 936, 937, 945, 946,
                947, 948, 949, 950, 951, 953, 954, 955,
                956, 957, 958, 959, 960, 961, 963, 964,
                965, 966, 967, 968, 969];

            //replace encoded characters
            $.map(encodedChars, function (x) {
                var e = String.fromCharCode(x);
                var s = $("main:contains(" + e + ")").not(".img");
                s.each(function () {
                    s.html(s.html().replace(e, '<span class="font-arial">' + e + '</span>'));
                });
            });

            //replace &[character];
            $.map(charList, function (e) {
                var s = $("main:contains(" + e + ")").not(".img");
                s.each(function () {
                    s.html(s.html().replace('&amp;' + e.substring(1), '<span class="font-arial">' + e + '</span>'));
                });
            });
        }

        //Set the windows default behavior
        $(window).bind("contextmenu", function () {
            $("div.custom-menu").remove();
        });

        //Bind the right click to the parent of the link.
        $('.productResourceLink').parent().bind("contextmenu", function (event) {
            //Stop default behavior listed above
            event.stopPropagation();

            //Lets get rid of the current context
            $("div.custom-menu").remove();

            var link = $(this).find('.productResourceLink');
            var href = $(link).attr('href');

            if (href.indexOf('PDF') === -1)
                return;

            //If we made it this far, prevent the default behavior
            event.preventDefault();

            var contextMenu =
                "<div class='custom-menu'>"
                + "<div class='custom-menu-inner'>"
                + "<div class='custom-menu-button open'>"
                + "Open link in new tab"
                + "</div>"
                + "<div class='custom-menu-button save'>"
                + "Save As..."
                + "</div>"
                + "</div>"
                + "</div>"

            $(contextMenu)
                .appendTo("body")
                .css({ top: event.pageY + "px", left: event.pageX + "px" });

            $('.custom-menu-button.open').click(function (e) {
                dataLayer.push({ 'event': 'PDFDownload' });

                window.open(href, '_blank');
                window.focus();
            });

            $('.custom-menu-button.save').click(function (e) {
                var newhref = href.replace('/PDF/', '/');

                dataLayer.push({ 'event': 'PDFDownload' });

                window.open(newhref + '?download=1#toolbar=1&amp;navpanes=0&amp;scrollbar=1&amp;view=FitH');
                window.focus();
            });
        });

        $(document).bind("click", function (event) {
            $("div.custom-menu").remove();
        });
    });
    /*End Product Datasheets*/

    $("input.baseautocomplete").each(function () {
        $(this).autocomplete({
            minLength: 2,
            source: function (request, response) {
                var element = this.element;
                $.ajax({
                    url: '/AutoComplete/AutoCompleteLookup',
                    type: "POST",
                    dataType: "json",
                    data: { searchText: request.term },
                    success: function (data) {
                        if (element.val() !== "") {
                            response($.map(data, function (item) {
                                return { value: item.Label, search: request.term, url: item.URL }
                            }));
                        }
                    } //,
                    //                error: function (jqXHR, textStatus, errorThrown) {
                    //                    alert(textStatus);
                    //                }
                });
            },

            select: function (event, ui) {
                event.preventDefault();
                event.stopPropagation();
                $.ajax({
                    url: '/KeywordTrap/Create',
                    type: "POST",
                    data: { modelNumber: ui.item.value, searchText: ui.item.search }
                });

                if (ui.item.url == "" || ui.item.url === null) {
                    $.ajax({
                        url: '/products/product/redirecttoproduct',
                        type: "POST",
                        data: { modelNumber: ui.item.value },
                        success: function (res) {
                            if (res.isRedirect) {
                                window.location.href = res.redirectUrl;
                                return;
                            }
                        }
                    })
                }
                else {
                    window.location.href = ui.item.url;
                }
            }
        }).autocomplete("widget").addClass("baseAutocompleteResults");
    });


});

// RFQ Functions
$(function () {
    $("#rfqautocomplete").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '/AutoComplete/RFQAutoCompleteLookup',
                type: "POST",
                dataType: "json",
                data: { searchText: request.term },
                success: function (data) {
                    response($.map(data, function (item) {
                        return { value: item.ModelNumber, desc: item.ProductDescription, productID: item.ProductID, search: request.term }
                    }))
                } //,
                //                error: function (jqXHR, textStatus, errorThrown) {
                //                    alert(textStatus);
                //                }
            })
        },

        select: function (event, ui) {
            var partnumber = ui.item.productID;
            var modelnumber = ui.item.value;
            AddToRFQCartByText(partnumber, modelnumber);
        }
    });
});

function AddToRFQCartByText(partnumber, modelnumber) {

    $("#rfqautocomplete")[0].value = '';

    // this needs to be ajax-y
    //window.location.href = "/Products/RFQ/AddProductToRFQ?productID=" + partnumber;
    $.get("/products/rfq/addproducttorfqpartial?productID=" + partnumber, function (data) {
        $("#productPartial").replaceWith(data);
        $('.notes-textarea').autogrow();
        $('.notes-textarea').keyup();
        $('.showonqty').show();
        $('#rfqautocomplete').val("");
        //$('#rfqautocomplete').css('height', '15px');

    });

}

function AddToRFQCartByProductID(productID) {
    window.location.href = "/products/rfq/addproducttorfq?productID=" + productID;


}

function OpenRFQ() {
    var dialogDiv = $('<div/>')

    $(dialogDiv).html('<iframe src="/products/rfq?layout=RFQContent"/ style="width:100%;height:' + ($(window).height() * 0.9) + 'px;">');
    $(dialogDiv).dialog({
        title: '',
        modal: true,
        dialogClass: "rfqDialog",
        width: '90%',
        resizable: false,
        autoOpen: true,
        position: "center center"
    });
}

function AddToRFQCart(partNumber, quantity = 0) {
    // grab the part number
    var partLabel = $("label#partnumber")[0];
    var partNumber = (partNumber != null ? partNumber : partLabel.innerHTML);
    var cartCount = 0

    // if the part number is okay, try to add the product through AJAX
    if (partNumber != "") {
        $.ajax({
            url: "/products/rfq/addproductbymodelnumber",
            type: "POST",
            dataType: "json",
            data: {
                modelNumber: partNumber,
                quantity: quantity
            },
            success: function (res) {
                window.location.href = "/products/rfq";
            }
        })
    }
}

//From http://mdn.beonex.com/en/DOM/document.cookie.html
docCookies = {
    getItem: function (sKey) {
        if (!sKey || !this.hasItem(sKey)) { return null; }
        return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
    },
    /** 
    * docCookies.setItem(sKey, sValue, vEnd, sPath, sDomain, bSecure) 
    * 
    * @argument sKey (String): the name of the cookie; 
    * @argument sValue (String): the value of the cookie; 
    * @optional argument vEnd (Number, String, Date Object or null): the max-age in seconds (e.g., 31536e3 for a year) or the 
    *  expires date in GMTString format or in Date Object format; if not specified it will expire at the end of session;  
    * @optional argument sPath (String or null): e.g., "/", "/mydir"; if not specified, defaults to the current path of the current document location; 
    * @optional argument sDomain (String or null): e.g., "example.com", ".example.com" (includes all subdomains) or "subdomain.example.com"; if not 
    * specified, defaults to the host portion of the current document location; 
    * @optional argument bSecure (Boolean or null): cookie will be transmitted only over secure protocol as https; 
    * @return undefined; 
    **/
    setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
        if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/.test(sKey)) { return; }
        var sExpires = "";
        if (vEnd) {
            switch (typeof vEnd) {
                case "number": sExpires = "; max-age=" + vEnd; break;
                case "string": sExpires = "; expires=" + vEnd; break;
                case "object": if (vEnd.hasOwnProperty("toGMTString")) { sExpires = "; expires=" + vEnd.toGMTString(); } break;
            }
        }
        document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    },
    removeItem: function (sKey) {
        if (!sKey || !this.hasItem(sKey)) { return; }
        var oExpDate = new Date();
        oExpDate.setDate(oExpDate.getDate() - 1);
        document.cookie = escape(sKey) + "=; expires=" + oExpDate.toGMTString() + "; path=/";
    },
    hasItem: function (sKey) { return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); }
};

//$(function () {
//    checkCarts();
//    $("form#rfqForm").keypress(function (e) {
//        if (e.target.id == "rfqautocomplete") {
//            //13 is enter, 9 is tab (which doesn't always fire keypress)
//            if (e.keyCode == 13 || e.keyCode == 9) {
//                var partnumber = e.target.value;
//                e.target.value = '';

//                //$('#rfqautocomplete').css('height', '15px');

//                // if the part number is okay, try to add the product through AJAX
//                if (partnumber != "") {
//                    $.get("/products/rfq/addproductbymodelnumberpartial?modelNumber=" + partnumber, function (data) {
//                        $("#productPartial").replaceWith(data);
//                        $('.notes-textarea').autogrow();
//                        $('.notes-textarea').keyup();
//                    });
//                }

//                return false;
//            }
//        }
//        else {
//            if (e.keyCode == 13) {
//                return false;
//            }
//        }
//    });
//});

//$(function () {
//    $("input#product_Quantities").focusout(function (e) {
//        var productid = e.target.nextElementSibling.value;
//        var modelnumber = e.target.nextElementSibling.nextElementSibling.value;
//        var newquantity = e.target.value;

//        // update this product with the quantity
//        $.ajax({
//            url: "/Products/RFQ/UpdateProductQuantity",
//            type: "POST",
//            dataType: "json",
//            data: { productID: productid, modelNumber: modelnumber, quantities: newquantity },
//            success: function (res) {
//            } 
//        })
//    });
//});

function DeleteProduct(productid, modelnumber) {
    $.get("/products/leadcapture/deleteproductfromcart?productID=" + productid + "&modelNumber=" + modelnumber, function (data) {
        $("#productPartial").replaceWith(data);
        $('.notes-textarea').autogrow();
        $('.notes-textarea').keyup();
    });
}

// Multi-Spec Product Configuration
function GetMultiSpecPartNum(item, productID) {
    //    var currentNumber = $("label#partnumber")[0].innerHTML;

    //    $("label#partnumber")[0].innerHTML = '<em>Generating model number...</em>';
    //    $.ajax({
    //        url: '/Products/Product/BuildMultiSpecPartNumber',
    //        type: 'POST',
    //        data: { parentIDAsString: productID, currentModelNumber: currentNumber, specificationID: item.attributes['specid'].value, specificationValue: item.options[item.selectedIndex].text },
    //        success: function (response) {
    //            $("label#partnumber")[0].innerHTML = response;
    //        }//,
    ////        error: function (jqXHR, textStatus, errorThrown) {
    ////            alert('failure');
    ////        }
    //    });

    var partnumber = "";
    $('.multi-spec .multi-options select').each(function () {
        partnumber += $(this).val().trim();
    });

    $("#partnumber").html(partnumber);
};

// Resources
function show3DView(model) {
    //var sURL = '/Products/ThreeDModel/ModelViewer?model=' + model.toString();
    var sURL = '/product/resource/3dmodel/' + model.toString().toLowerCase();

    window.open(sURL, '3DView', 'toolbar=1,scrollbars=1,status=0,location=0,width=1070,height=695')
}


function showConnectorMatingGuide(model, title) {
    var dialogDiv = $('<div/>')
    $(dialogDiv).html('<div id="loading-spinner" style="display:block;" ><div class="loading-dot"></div></div>');
    $(dialogDiv).dialog({
        modal: true,
        dialogClass: "cmgDialog",
        width: '70%',
        resizable: false,
        draggable: false,
        autoOpen: true,
        open: function (event, ui) {
            removeDialogFocus(this);
        },
        close: function (event, ui) {
            $(this).dialog('destroy').remove();
        },
        create: function (event, ui) {
            var widget = $(this).dialog("widget");
            $(".ui-dialog-titlebar-close span", widget)
                .removeClass("ui-icon-closethick")
                .removeClass("ui-button-icon")
                .removeClass("ui-icon"),
                $(".ui-dialog-titlebar-close", widget)
                    .removeClass("ui-icon-closethick")
                    .removeClass("ui-corner-all")
                    .removeClass("ui-button-icon")
                    .removeClass("ui-button")
                    .addClass("icon")
                    .addClass("icon-remove-x");
        }
    });
    $.ajax({
        url: '/products/product/GetConnectorMatingGuideModal?id=' + model,
        dataType: "html",
        type: "POST",
        success: function (data) {
            $(dialogDiv).dialog("close");
            $(dialogDiv).html(data);
            $(dialogDiv).dialog({
                modal: true,
                dialogClass: "cmgDialog",
                width: '70%',
                resizable: false,
                draggable: false,
                autoOpen: true,
                open: function (event, ui) {
                    removeDialogFocus(this);
                },
                close: function (event, ui) {
                    $(this).dialog('destroy').remove();
                },
                create: function (event, ui) {
                    var widget = $(this).dialog("widget");
                    $(".ui-dialog-titlebar-close span", widget)
                        .removeClass("ui-icon-closethick")
                        .removeClass("ui-button-icon")
                        .removeClass("ui-icon"),
                        $(".ui-dialog-titlebar-close", widget)
                            .removeClass("ui-icon-closethick")
                            .removeClass("ui-corner-all")
                            .removeClass("ui-button-icon")
                            .removeClass("ui-button")
                            .addClass("icon")
                            .addClass("icon-remove-x");
                }
            });
            var resizeFunction = function () {
                $(dialogDiv).dialog("close")
                $(dialogDiv).dialog("open")
            }

            $(window).resize(resizeFunction);

            $(dialogDiv).bind("clickoutside", function (event) {
                $(this).dialog("destroy");
                $(window).unbind("resize", resizeFunction);
            });
        }
        , error: function (XMLHttpRequest, textStatus, errorThrown) {
            $(dialogDiv).dialog("close")
            $(dialogDiv).html("Sorry! Your search for \"" + model + "\" produced no results.<br/>" + errorThrown);
            $(dialogDiv).dialog({
                title: title,
                modal: true,
                dialogClass: "cmgDialog",
                width: '70%',
                resizable: false,
                autoOpen: true
            });

            var resizeFunction = function () {
                $(dialogDiv).dialog("close")
                $(dialogDiv).dialog("open")
            }

            $(window).resize(resizeFunction);
        }
    });
}
function showUsbCablesMatingGuide(productId, model) {
    var dialogDiv = $('<div/>')
    $(dialogDiv).html('<div id="loading-spinner" style="display:block;" ><div class="loading-dot"></div></div>');
    $(dialogDiv).dialog({
        title: model + ' Cable Mating Guide',
        modal: true,
        dialogClass: "cmgDialog",
        width: '70%',
        resizable: false,
        draggable: false,
        autoOpen: true,
        open: function (event, ui) {
            removeDialogFocus(this);
        },
        close: function (event, ui) {
            $(this).dialog('destroy').remove();
        },
        create: function (event, ui) {
            var widget = $(this).dialog("widget");
            $(".ui-dialog-titlebar-close span", widget)
                .removeClass("ui-icon-closethick")
                .removeClass("ui-button-icon")
                .removeClass("ui-icon"),
                $(".ui-dialog-titlebar-close", widget)
                    .removeClass("ui-icon-closethick")
                    .removeClass("ui-corner-all")
                    .removeClass("ui-button-icon")
                    .removeClass("ui-button")
                    .addClass("icon")
                    .addClass("icon-remove-x");
        }
    });
    $.ajax({
        url: '/products/product/GetUsbCableMatingGuideModal?id=' + productId,
        dataType: "html",
        type: "POST",
        success: function (data) {
            $(dialogDiv).dialog("close");
            $(dialogDiv).html(data);
            $(dialogDiv).dialog({
                title: model + ' Cable Mating Guide',
                modal: true,
                dialogClass: "cmgDialog",
                width: '70%',
                resizable: false,
                draggable: false,
                autoOpen: true,
                open: function (event, ui) {
                    removeDialogFocus(this);
                },
                close: function (event, ui) {
                    $(this).dialog('destroy').remove();
                },
                create: function (event, ui) {
                    var widget = $(this).dialog("widget");
                    $(".ui-dialog-titlebar-close span", widget)
                        .removeClass("ui-icon-closethick")
                        .removeClass("ui-button-icon")
                        .removeClass("ui-icon"),
                        $(".ui-dialog-titlebar-close", widget)
                            .removeClass("ui-icon-closethick")
                            .removeClass("ui-corner-all")
                            .removeClass("ui-button-icon")
                            .removeClass("ui-button")
                            .addClass("icon")
                            .addClass("icon-remove-x");
                }
            });
            var resizeFunction = function () {
                $(dialogDiv).dialog("close")
                $(dialogDiv).dialog("open")
            }

            $(window).resize(resizeFunction);

            $(dialogDiv).bind("clickoutside", function (event) {
                $(this).dialog("destroy");
                $(window).unbind("resize", resizeFunction);
            });
        }
        , error: function (XMLHttpRequest, textStatus, errorThrown) {
            $(dialogDiv).dialog("close")
            $(dialogDiv).html("Sorry! Your search for \"" + model + "\" produced no results.<br/>" + errorThrown);
            $(dialogDiv).dialog({
                title: 'USB Cable Mating Guide for part #' + model,
                modal: true,
                dialogClass: "cmgDialog",
                width: '70%',
                resizable: false,
                autoOpen: true
            });

            var resizeFunction = function () {
                $(dialogDiv).dialog("close")
                $(dialogDiv).dialog("open")
            }

            $(window).resize(resizeFunction);
        }
    });
}
function showPCNList(model) {
    var dialogDiv = $('<div/>')
    $(dialogDiv).html('<div id="loading-spinner" style="display:block;" ><div class="loading-dot"></div></div>');
    $(dialogDiv).dialog({
        modal: true,
        dialogClass: "cmgDialog",
        width: '70%',
        resizable: false,
        draggable: false,
        autoOpen: true,
        open: function (event, ui) {
            removeDialogFocus(this);
        },
        close: function (event, ui) {
            $(this).dialog('destroy').remove();
        },
        create: function (event, ui) {
            var widget = $(this).dialog("widget");
            $(".ui-dialog-titlebar-close span", widget)
                .removeClass("ui-icon-closethick")
                .removeClass("ui-button-icon")
                .removeClass("ui-icon"),
                $(".ui-dialog-titlebar-close", widget)
                    .removeClass("ui-icon-closethick")
                    .removeClass("ui-corner-all")
                    .removeClass("ui-button-icon")
                    .removeClass("ui-button")
                    .addClass("icon")
                    .addClass("icon-remove-x");
        }
    });
    $.ajax({
        url: '/products/product/GetPCNListModal?id=' + model,
        dataType: "html",
        type: "POST",
        success: function (data) {
            $(dialogDiv).dialog("close");
            $(dialogDiv).html(data);
            $(dialogDiv).dialog({
                modal: true,
                dialogClass: "cmgDialog",
                width: '70%',
                resizable: false,
                draggable: false,
                autoOpen: true,
                open: function (event, ui) {
                    removeDialogFocus(this);
                },
                close: function (event, ui) {
                    $(this).dialog('destroy').remove();
                },
                create: function (event, ui) {
                    var widget = $(this).dialog("widget");
                    $(".ui-dialog-titlebar-close span", widget)
                        .removeClass("ui-icon-closethick")
                        .removeClass("ui-button-icon")
                        .removeClass("ui-icon"),
                        $(".ui-dialog-titlebar-close", widget)
                            .removeClass("ui-icon-closethick")
                            .removeClass("ui-corner-all")
                            .removeClass("ui-button-icon")
                            .removeClass("ui-button")
                            .addClass("icon")
                            .addClass("icon-remove-x");
                }
            });

            //The Japan website domain is odd because of how translation works
            //We need to just check if it's a US Domain
            var isJapan = "true";
            // console.log(window.location.hostname);
            if (window.location.hostname === 'www.sameskydevices.com'
                || window.location.hostname === 'test.sameskydevices.com'
                || window.location.hostname === 'stage.sameskydevices.com'
                || window.location.hostname === 'redesign-test.sameskydevices.com'
                || window.location.hostname.includes('localhost')
                || window.location.hostname.includes('sameskydevices')
            ) {
                isJapan = "false";
            }
            var input = document.createElement("input");
            input.setAttribute("type", "hidden");
            input.setAttribute("name", "IsJapan");
            input.setAttribute("value", isJapan);
            $('#notificationForm').append(input);


            var resizeFunction = function () {
                $(dialogDiv).dialog("close");
                ; $(dialogDiv).dialog("open");
            };

            $(window).resize(resizeFunction);

            $(dialogDiv).bind("clickoutside", function (event) {
                $(this).dialog("destroy");
                $(window).unbind("resize", resizeFunction);
            });
        }
        , error: function (XMLHttpRequest, textStatus, errorThrown) {
            $(dialogDiv).dialog("close");
            $(dialogDiv).html("Oops! The page you are looking for is temporarily unavailble. <a href='https://www.sameskydevices.com/quality'>PCN & EOL Notifications</a>");
            $(dialogDiv).dialog({
                title: 'Product Notifications',
                modal: true,
                dialogClass: "cmgDialog",
                width: '70%',
                resizable: false,
                autoOpen: true
            });

            $(".ui-dialog-titlebar-close span")
                .removeClass("ui-icon-closethick")
                .removeClass("ui-button-icon")
                .removeClass("ui-icon");

            $(".ui-dialog-titlebar-close")
                .removeClass("ui-icon-closethick")
                .removeClass("ui-corner-all")
                .removeClass("ui-button-icon")
                .removeClass("ui-button")
                .addClass("icon")
                .addClass("icon-remove-x");

            var resizeFunction = function () {
                $(dialogDiv).dialog("close");
                $(dialogDiv).dialog("open");
            };

            $(window).resize(resizeFunction);
        }
    });
}

function showPCNEOLList(model) {
    var dialogDiv = $('<div/>')
    $(dialogDiv).html('<div id="loading-spinner" style="display:block;" ><div class="loading-dot"></div></div>');
    $(dialogDiv).dialog({
        modal: true,
        dialogClass: "cmgDialog",
        width: '70%',
        resizable: false,
        draggable: false,
        autoOpen: true,
        open: function (event, ui) {
            removeDialogFocus(this);
        },
        close: function (event, ui) {
            $(this).dialog('destroy').remove();
        },
        create: function (event, ui) {
            var widget = $(this).dialog("widget");
            $(".ui-dialog-titlebar-close span", widget)
                .removeClass("ui-icon-closethick")
                .removeClass("ui-button-icon")
                .removeClass("ui-icon"),
                $(".ui-dialog-titlebar-close", widget)
                    .removeClass("ui-icon-closethick")
                    .removeClass("ui-corner-all")
                    .removeClass("ui-button-icon")
                    .removeClass("ui-button")
                    .addClass("icon")
                    .addClass("icon-remove-x");
        }
    });

    $.ajax({
        url: '/products/product/GetPCNEOLListModal?id=' + model,
        dataType: "html",
        type: "POST",
        success: function (data) {
            $(dialogDiv).dialog("close");
            $(dialogDiv).html(data);
            $(dialogDiv).dialog({
                modal: true,
                dialogClass: "cmgDialog",
                width: '70%',
                resizable: false,
                draggable: false,
                autoOpen: true,
                open: function (event, ui) {
                    removeDialogFocus(this);
                },
                close: function (event, ui) {
                    $(this).dialog('destroy').remove();
                },
                create: function (event, ui) {
                    var widget = $(this).dialog("widget");
                    $(".ui-dialog-titlebar-close span", widget)
                        .removeClass("ui-icon-closethick")
                        .removeClass("ui-button-icon")
                        .removeClass("ui-icon"),
                        $(".ui-dialog-titlebar-close", widget)
                            .removeClass("ui-icon-closethick")
                            .removeClass("ui-corner-all")
                            .removeClass("ui-button-icon")
                            .removeClass("ui-button")
                            .addClass("icon")
                            .addClass("icon-remove-x");
                }
            });

            //The Japan website domain is odd because of how translation works
            //We need to just check if it's a US Domain
            var isJapan = "true";
            // console.log(window.location.hostname);
            if (window.location.hostname === 'www.sameskydevices.com'
                || window.location.hostname === 'test.sameskydevices.com'
                || window.location.hostname === 'stage.sameskydevices.com'
                || window.location.hostname === 'redesign-test.sameskydevices.com'
                || window.location.hostname.includes('localhost')
                || window.location.hostname.includes('sameskydevices')
            ) {
                isJapan = "false";
            }
            var input = document.createElement("input");
            input.setAttribute("type", "hidden");
            input.setAttribute("name", "IsJapan");
            input.setAttribute("value", isJapan);
            $('#notificationForm').append(input);


            var resizeFunction = function () {
                $(dialogDiv).dialog("close");
                ; $(dialogDiv).dialog("open");
            };

            $(window).resize(resizeFunction);

            $(dialogDiv).bind("clickoutside", function (event) {
                $(this).dialog("destroy");
                $(window).unbind("resize", resizeFunction);
            });
        }
        , error: function (XMLHttpRequest, textStatus, errorThrown) {
            $(dialogDiv).dialog("close");
            $(dialogDiv).html("Oops! The page you are looking for is temporarily unavailble. <a href='https://www.sameskydevices.com/quality'>PCN & EOL Notifications</a>");
            $(dialogDiv).dialog({
                title: 'Product Notifications',
                modal: true,
                dialogClass: "cmgDialog",
                width: '70%',
                resizable: false,
                autoOpen: true
            });

            $(".ui-dialog-titlebar-close span")
                .removeClass("ui-icon-closethick")
                .removeClass("ui-button-icon")
                .removeClass("ui-icon");

            $(".ui-dialog-titlebar-close")
                .removeClass("ui-icon-closethick")
                .removeClass("ui-corner-all")
                .removeClass("ui-button-icon")
                .removeClass("ui-button")
                .addClass("icon")
                .addClass("icon-remove-x");

            var resizeFunction = function () {
                $(dialogDiv).dialog("close");
                $(dialogDiv).dialog("open");
            };

            $(window).resize(resizeFunction);
        }
    });
}

function openEmailWindow(url) {
    window.open(url, 'Email Product List', 'toolbar=1,scrollbars=1,status=0,location=0,width=700,height=800');
}

function showMultiSpec3DView() {
    var model = $("label#partnumber")[0].innerHTML;

    show3DView(model);
}

function showGeneratedResource(generatedResourceID, typeName) {
    //var sURL = '/Products/Product/GeneratedResource?resourceGeneratedXrefID=' + generatedResourceID.toString();
    var sURL = '/product/resource/material-compliance/' + generatedResourceID.toString();
    showPane(sURL, typeName);
}

function showPane(sURL, typeName) {

    window.open(sURL, typeName, 'toolbar=1,scrollbars=1,status=0,location=0,width=612,height=792')
}

// Twitter
function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp, "<a href='$1' target='_blank'>$1</a>");
}

function replaceTwitterHashtagswithHTMLLinks(text) {
    var exp = /(\#)([a-zA-Z0-9_%]*)/ig;
    return text.replace(exp, "<a href='https://twitter.com/#!/search/$2' target='_blank'>$1$2</a>");
}

function replaceTwitterUsernameswithHTMLLinks(text) {
    var exp = /(\@)([a-zA-Z0-9_%]*)/ig;
    return text.replace(exp, "<a href='https://twitter.com/#!/$2' target='_blank'>$1$2</a>");
}

// pass in the 'created_at' string returned from twitter //
// stamp arrives formatted as Tue Apr 07 22:52:51 +0000 2009 //
function parseTwitterDate($stamp) {
    $stamp = $stamp.substr(0, 19);

    // convert to local string and remove seconds and year //		
    var date = new Date(Date.parse($stamp)).toLocaleString().substr(0, 16);
    // get the two digit hour //
    var hour = date.substr(-5, 2);
    // convert to AM or PM //
    var ampm = hour < 12 ? ' AM' : ' PM';
    if (hour > 12) hour -= 12;
    if (hour == 0) hour = 12;
    // return the formatted string //
    return date.substr(0, 11) + ' ' + hour + ':' + date.substr(13) + ampm;
}

function parseDate(str) {
    var v = str.split(' ');
    return new Date(Date.parse(v[1] + " " + v[2] + ", " + v[5] + " " + v[3] + " UTC")).toDateString();
}

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
    return pattern.test(emailAddress);
};

function isValidEmailAddressList(emailAddress) {
    //Space to ;
    //, to ;
    emailAddress = emailAddress.replace(/  /gi, " ");
    emailAddress = emailAddress.replace(/  /gi, " ");
    emailAddress = emailAddress.replace(/ /gi, ";");
    emailAddress = emailAddress.replace(/,/gi, ";");

    var parts = emailAddress.split(";"), i, l;

    var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);

    var valid = (parts.length > 0 ? true : false);
    var partscount = 0;
    for (i = 0; i < parts.length; i++) {
        if (parts[i] != "") {
            if (!pattern.test(parts[i]))
                valid = false;
            else
                partscount++;
        }
    }

    //Must be valid and have parts
    return valid && partscount > 0;
};

$(document).ready(function () {
    $('body').delegate('.resource-link', 'click', function (e) {

        if ($(this).hasClass('resource-Video') && this.href.indexOf('/resources/resource-library/videos') < 0) {
            var name = $(this).attr('href').replace('/resources/resource-library/', '').replace('/resources/product-resources/', '');

            var url = (name.substring(0, 1) === "#" ? "/resources/VideoByLink?videoName=" + name.slice(1) : "/resources/Video?videoName=" + name);
            var videoTitle = $(this).find('.video-name').text();

            $.get(url, function (data) {
                $("#video-wrapper-dialog").html(data);
                $(window).resize(function () {
                    $("#video-wrapper-dialog").dialog("option", "position", "center");
                });
                $("#video-wrapper-dialog").dialog({
                    title: videoTitle,
                    modal: true,
                    dialogClass: "videoDialog",
                    width: '80%',
                    //height: (window.innerWidth * .3345),
                    resizable: false,
                    autoOpen: true,
                    close: function () {


                        // destroy the player                 
                        try {
                            var player = _V_('videoPlayer');
                            player.stopTrackingProgress();
                            player.stopTrackingCurrentTime();
                            _V_.players[player.id] = null;
                            delete _V_.players[player.id];
                            player.tech.destroy();
                            player.el.parentNode.removeChild(player.el);

                        }
                        catch (e) { }

                        $(this).dialog("destroy");
                        $("#video-wrapper-dialog").html('');
                    }
                });
            });
            e.preventDefault();
        }

    });
});


function LogError(message) {
    $.post("/Error/LogError", { errorMessage: message }, function (data) {
        return true;
    });
}


function showSPLView(type) {
    var sURL = '/product/resource/calculators/' + type + '-spl';

    window.location = sURL;
}


$(function () {
    //Show disabled text as gray
    //$('body').delegate('select:not(.noDarkGray)', 'change', function () {        
    //    if ($(this).children().first().val() == $(this).val()) {
    //        $(this).css('color', 'DarkGray');
    //    }
    //    else {
    //        $(this).css('color', 'initial');
    //    }
    //});

    //$('body').delegate('input[type=text], textarea', 'keyup', function () {
    //    if ($(this).val() == null || $(this).val().length == undefined || $(this).val().length == 0) {
    //        $(this).css('color', 'DarkGray');
    //    }
    //    else {
    //        $(this).css('color', 'initial');
    //    }
    //});


    $('select').change();
    $('input, textarea').keyup();

    $("[data-eventaction][data-eventlabel]").click(function () {
        dataLayer.push({ 'event': 'ClickTracking', 'EventAction': $(this).data("eventaction"), 'EventLabel': $(this).data("eventlabel") });
    });
});

function showDialogPopup(title, html, defaultWidth, hideXButton, defaultTop) {
    var width = $(window).width();
    if (width > 1028)
        width = 1028;
    else
        width = width * .8;

    if (defaultWidth != null)
        width = defaultWidth;

    var dialogDiv = $('<div/>')
    $(dialogDiv).html(html);
    $(dialogDiv).dialog({
        title: title,
        modal: true,
        closeOnEscape: !hideXButton,
        open: function (event, ui) { if (hideXButton) $(".ui-dialog-titlebar-close", ui.dialog | ui).hide(); },
        dialogClass: "siteDialog",
        width: width,
        //maxWidth: 1000,
        resizable: false,
        autoOpen: true,
        position: "center top"
    });
    var pos = $('.siteDialog').position();

    pos.top += (defaultTop == null ? 50 : defaultTop);

    $('.siteDialog').css("top", pos.top + "px");
}

function showAddedToCart(product, cartUrl) {

    var imgSrc = $('#main-prod-img').attr('src');
    var height = $(window).height();
    var dialogDiv = $('<div/>')
    $(dialogDiv).html(
        `
        <div class="d-flex flex-column h-100 justify-content-around">
            <div class="sidebar-content">
                <h1 class="text-center">Added to Cart</h1>
                <img src="${imgSrc ? imgSrc : product.mediaLinks.largeImageUrl}" />
                <h2 class="text-center h3 f-industry font-weight-bold">${product.productName}</h2>
                <p class="lead f-industry text-center">
                    ${product.detailedDescription}
                </p>
            </div>
            <div>
                <a href="${cartUrl}" class="btn btn-primary w-100 mb-4 text-light">Go to Cart</a>
                <button id="closeCartDialogSidebar" class="btn btn-outline-primary w-100 mb-4">Continue Shopping</button>
            </div>
        </div>
        `
    );

    $(dialogDiv).dialog({
        modal: true,
        closeOnEscape: true,
        dialogClass: "added-to-cart",
        //width: 480,
        height: height,
        resizable: false,
        autoOpen: true,
        position: { my: "right top", at: "right bottom", of: window }
    });

    $("#closeCartDialogSidebar, .added-to-cart + .ui-widget-overlay.ui-front").click(() => {
        $(dialogDiv).dialog("close");
    })
}

// Prevent jquery ui dialog from setting focus to the first tabbable element when shown.
function removeDialogFocus(container) {
    $(document.activeElement).blur();
}

var $_ICV = {
    init: function () {
        document.getElementById("ic_signupform").addEventListener("submit", $_ICV.validate);
    },
    validate: function (e) {
        var emailField = document.querySelectorAll('div.formEl input[name="email"]')[0],
            errors = [];
        try {
            var value = emailField.value;

            if (value == '') {
                errors.push("The Email field is required.");
            }
            var valid = value.match(/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i, value);

            if (!valid) {
                errors.push("The Email is an invalid format.");
            }

        } catch (ex) {
            $("#errorlist").html(ex);
            e.preventDefault();
            e.stopPropagation();
            return false;
        }

        if (errors.length > 0) {
            $("#errorlist").html(errors.join("\n"));
            e.preventDefault();
            e.stopPropagation();
            return false;
        }

        return true;
    }
}

var $_bannerSignup = {
    init: function () {
        document.getElementById("ic_signupform-banner").addEventListener("submit", $_bannerSignup.validate);
    },
    validate: function (e) {
        e.preventDefault();
        var emailField = document.querySelectorAll('#ic_signupform-banner div.formEl input[name="email"]')[0],
            errors = [];
        try {
            var value = emailField.value;

            if (value == '') {
                errors.push("The Email field is required.");
            }
            var valid = value.match(/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i, value);

            if (!valid) {
                errors.push("The Email is an invalid format.");
            }

        } catch (ex) {
            $("#errorlist-banner").html(ex);
            e.preventDefault();
            e.stopPropagation();
            return false;
        }

        if (errors.length > 0) {
            $("#errorlist-banner").html(errors.join("\n"));
            e.preventDefault();
            e.stopPropagation();
            return false;
        }

        submitBannerNewsletterSignup();
    }
}

function submitBannerNewsletterSignup() {
    $.ajax({
        type: "POST",
        url: "/newsletters/jsonsubscribe",
        data: $('#ic_signupform-banner').serialize(),
        dataType: "html",
        type: "POST",
        success: function (response) {
            if (response == "Error") {
                $("#errorlist-banner").html("We're sorry, there was an error signing you up");
            } else {
                $(".newsletter-banner .newsletterTxt").html("<p class='bold center white italic'>Thanks for signing up! Keep an eye out for a welcome message coming to your inbox soon!</p>");
            }
        },
        error: function (response) {
            $("#errorlist-banner").html(response.statusText);
        }
    });
    return false;
}

$(document).ready(function () {
    if (!!document.getElementById("ic_signupform")) $_ICV.init();
    if (!!document.getElementById("ic_signupform-banner")) $_bannerSignup.init();
    var queryString = location.search;
    var params = queryString.substring(1).split('&');
    for (var i = 0; i < params.length; i++) {
        var pair = params[i].split('=');
        if (decodeURIComponent(pair[0]) == 'showmessage' && pair[1] && pair[1] == 'true') {
            showDialogPopup('', '<h1>REDIRECT NOTICE</h1><h2>www.cui.com > www.sameskydevices.com</h2><hr><p>Same Sky, formed by several former CUI Inc senior managers in September 2019, acquired the product or resource you are attempting to view. To learn more about the update read the <a style="color:#57c8df;" href="/news/press-releases/senior-managers-purchase-cui-incs-electronic-components-business-and-form-cui-devices">press release</a>. If you are searching for power supplies return to <a style="color:#57c8df;" href="https://www.cui.com">www.cui.com</a>.<p>')
            $(".ui-widget-overlay").one("click", function (event) { $(".siteDialog :ui-dialog").dialog("close"); $(".siteDialog :ui-dialog").dialog("destroy"); });
            removeDialogFocus();
        }
    }

});



resizeElementsToSameHeight = function (elementToGetSizeFrom, elementToPutSizeOn, timer) {
    if (typeof timer !== "undefined") {
        clearTimeout(timer);
    }
    timer = setTimeout(function () {
        $(elementToPutSizeOn).css("height", "auto");
        var maxHeight = 0;
        $(elementToGetSizeFrom).each(function () {
            if ($(this).outerHeight() > maxHeight) {
                maxHeight = $(this).outerHeight();
            }
        });
        $(elementToPutSizeOn).height(maxHeight);
    }, 250);
};

function LookupCountry() {
    var ddl = $("#CountryIDAsString")[0];
    var countryid = ddl.options[ddl.selectedIndex].value;
    $.get("/Contact/ContactUs/LookupCountry?countryID=" + countryid, function (data) {
        if (data.length == 0)
            $('#stateWrapper').hide();
        else {
            $('#stateWrapper').html(data);
            //$('#stateWrapper select').addClass("form-control");
            $('#stateWrapper').show();
        }
    });
}

function ShowStateOrProvidence() {
    var ddl = $('#CountryIDAsString')[0];
    var countryid = ddl.options[ddl.selectedIndex].value;
    $('#stateWrapper #State').val("");
    $('#provinceWrapper #Province').val("");

    if (countryid === '551') { //United States show States dropdown
        $('#stateWrapper').removeClass('d-none');
        $('#provinceWrapper').addClass('d-none');
        $('label[for=PostalZip]').html("Postal Code *");
    } else if (countryid === '554') { //Canada show States dropdown
        $('#stateWrapper').addClass('d-none');
        $('#provinceWrapper').removeClass('d-none');
        $('label[for=PostalZip]').html("Postal Code *");
    } else {
        $('#stateWrapper').addClass('d-none');
        $('#provinceWrapper').addClass('d-none');
        $('label[for=PostalZip]').html("Postal Code");
    }
}

function LC_clearChatParam() {

    var params = new URLSearchParams(window.location.search);

    params.delete("chat");
    var q = "";
    if (params.toString().length > 0) {
        q = "?"
    };

    window.history.replaceState({}, "", decodeURIComponent(`${window.location.pathname}${q}${params}`).replace(/\+/g, '%20'));

    // Clear form values
    $("#prechatForm :input:not(#prechatSubmissionURL)").val("");

}
function LC_getChatGroup() {
    const params = new URLSearchParams(window.location.search);
    var grp = params.get("chat");

    return grp;
}
function LC_changeGroup(grp) {
    var params = new URLSearchParams(window.location.search);
    var oldGrp = LC_getChatGroup();

    //If the group is new or changed, setup the url param
    if (oldGrp === null || grp !== oldGrp) {
        params.set("chat", grp);
        window.history.replaceState({}, "", decodeURIComponent(`${window.location.pathname}?${params}`));
    }
}

function LC_destroyWidget() {
    window.liveChatLoaded = false;
    if (typeof LiveChatWidget !== 'undefined' && LiveChatWidget !== null) {
        LiveChatWidget.call("destroy");
    }
    $.cookie("LiveChatGroup", null, { path: '/' });
}

function LC_showPrechatForm() {

    var grp = LC_getChatGroup();
    if (grp === "eng") {
        $("#prechatTitleText").text("Ask an Engineer");
        $("#prechatSubTitleText").text("Please leave a message for our engineering team and we'll get back to you as soon as possible.");
        $(".chat-title").addClass("bg-cuid-teal");
        $(".chat-title").removeClass("bg-cuid-magenta");
    }
    else if (grp === "sales") {
        $("#prechatTitleText").text("Contact Sales");
        $("#prechatSubTitleText").text("Please leave a message for our sales team and we'll get back to you as soon as possible.");
        $(".chat-title").addClass("bg-cuid-magenta");
        $(".chat-title").removeClass("bg-cuid-teal");
    }
    $('.livechat-department-btn').hide();
    $("#prechatCloseBtn").hide();
    $('#livechat-prechat-wrapper').show();
}

function getDateInMinutes(mins) {
    var date = new Date();
    date.setTime(date.getTime() + mins * 60 * 1000);
    return date;
}

function LC_hidePrechatMessageAlreadySent() {
    $.removeCookie("preChatFormSubmitted", null);
    $("#prechatMessageAlreadySent").hide();

}

var doSubmit = true;//problem w/ repeat submissions, maybe due to form submit handler firing too many times. use this var to make sure only one post occurs
function submitLCForm(token) {
    $("#prechatForm").trigger("submit");
}

function LC_submitPrechatform(event) {

    event.preventDefault();

    if (doSubmit) {
        doSubmit = false;

        if (LC_validateForm()) {
            var obj = LC_loadChatFormData();
            $("#prechatLoadingMessage").html("Submitting Message...");
            $("#prechatForm").hide();
            $("#prechatLoading").show();

            dataLayer = window.dataLayer || [];
            dataLayer.push({ event: 'LiveChat', eventCategory: 'LiveChat Offline', eventAction: 'Ticket form filled in', eventLabel: LC_getChatGroup() });


            var fileIsOkay = true;
            $('#lc-file-validation').hide();
            var file = $('#liveChat-files')[0];
            var newFiles = new DataTransfer();
            for (let i = 0; i < lcfilesToUpload.length; i++) {
                newFiles.items.add(lcfilesToUpload[i].file);
            }
            file.files = newFiles.files;

            if (file.files && file.files.length > 0) {
                if (file.files[0].size && file.files[0].size >= 10485760) { // 10MB limit
                    // show error
                    $('#lc-file-validation').show();
                    fileIsOkay = false;
                }
            }

            var fd = new FormData();
            
            for(const key in obj) {
                fd.append(key, obj[key]);
            } 

            if (fileIsOkay) {
                for (let i = 0; i < file.files.length; i++) {
                    fd.append('files', file.files[i]);
                }
            }
            
            $.ajax({
                url: '/contact/contactus/livechatoffline',
                data: fd,
                processData: false,
                contentType: false,
                type: 'POST',
                success: function (data) {
                    $("#prechatLoadingMessage").html("Thank you, a Same Sky representative will contact you shortly.");
                    $("#prechatCloseBtn").show();
                    grecaptcha.reset();
                },
                error: function (jqCHR, textStatus, errorThrown) {
                    $("#prechatLoadingMessage").html("Something Went wrong. <br/> status:" + textStatus + "<br/>error: " + jqCHR.responseText);
                    $("#prechatCloseBtn").show();
                    grecaptcha.reset();
                }
            });

        }
        setTimeout(function () { doSubmit = true; }, 2000);
    }
}

function LC_minimizePrechatform(clearParams = true) {
    $("#prechatForm").show();
    //$("#prechatOfflineConfirm").hide();
    $('#livechat-prechat-wrapper').hide();
    //$('#livechat-prechat-wrapper .wavedots').hide();
    $('.field-validation-error').hide();
    $("#prechatCloseBtn").hide();
    $('.livechat-department-btn').show();
    $("#prechatLoadingMessage").html("");
    $("#prechatLoading").hide();

    if (clearParams) LC_clearChatParam();
}

function LC_loadCountries() {
    $.get("/Contact/ContactUs/ListCountries", function (data) {
        $("#prechatCountry").find('option').remove().end();
        $.map(data, function (val) {
            var option = $('<option>').val(val.CountryID).text(val.CountryName);
            $('#prechatCountry').append(option);
        });
    });
}

function LC_loadStates() {

    var CountryId = $("#prechatCountry").val();
    if (CountryId) {
        $("#prechatState").find('option').remove().end();
        $.get("/Contact/ContactUs/ListStates?countryId=" + CountryId, function (data) {
            if (data !== null && data.length) {
                $.map(data, function (val) {
                    var option = $('<option>').val(val.StateCode).text(val.StateName);
                    $('#prechatState').append(option);
                })
                $('#prechatState').prop("disabled", false);
                $("#prechatStateWrapper").show();
            }
        })
            .fail(function () {
                $('#prechatState').prop("disabled", true);
                $("#prechatStateWrapper").hide();
            });
    }
}

function LC_launchChatClick() {
    var grp = $(this).find(".livechat-label").data("group");
    LC_changeGroup(grp);
    LC_showPrechatForm();
}
function LC_validateForm() {
    var data = LC_loadChatFormData();
    var valid = true;
    if (data["FirstName"] === "") {
        $("#prechatFirstNameAlert").show();
        valid = false;
    }
    else {
        $("#prechatFirstNameAlert").hide();
    }

    if (data["LastName"] === "") {
        $("#prechatLastNameAlert").show();
        valid = false;
    }
    else {
        $("#prechatLastNameAlert").hide();
    }

    if (data["Company"] === "") {
        $("#prechatCompanyAlert").show();
        valid = false;
    }
    else {
        $("#prechatCompanyAlert").hide();
    }

    var emailReg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    if (data["Email"] === "" || !emailReg.test(data["Email"])) {
        $("#prechatEmailAlert").show();
        valid = false;
    }
    else {
        $("#prechatEmailAlert").hide();
    }

    if (data["Country"] === "--Select Country--" || data["Country"] == "") {
        $("#prechatCountryAlert").show();
        valid = false;
    }
    else {
        $("#prechatCountryAlert").hide();
    }

    if ((data["State"] === "" || data["State"] === "--Select State--") && $("#prechatState").is(":visible")) {
        $("#prechatStateAlert").show();
        valid = false;
    }
    else {
        $("#prechatStateAlert").hide();
    }

    if (data["Message"] === "") {
        $("#prechatOfflineMessageAlert").show();
        valid = false;
    }
    else {
        $("#prechatOfflineMessageAlert").hide();
    }

    return valid;
}
function LC_loadChatFormData() {

    var obj = {};
    var grp = LC_getChatGroup();
    if (grp === "sales") { obj["ChatType"] = "Sales"; }
    else if (grp === "eng") { obj["ChatType"] = "Engineering"; }
    obj["Message"] = $("#prechatOfflineMessage").val();
    obj["Technology"] = $("#prechatTech input:checkbox:checked").map(function () { return $(this).val(); }).get().join(", ");
    $("#prechatForm input:not(:checkbox) ").serializeArray().map(function (v) { obj[v.name] = v.value; });
    obj["Country"] = $("#prechatCountry option:selected").text();
    obj["CountryId"] = $("#prechatCountry option:selected").val();
    obj["State"] = $("#prechatState option:selected").val();
    obj["SubscribeNewsletter"] = $("#SubscribeNewsletterCheckbox input:checkbox:checked").map(function () { return $(this).val(); }).get().join(", ");
    obj["g-Recaptcha-Response"] = grecaptcha.getResponse()
    return obj;
}

var LC_widgetID;
function LC_prechatPageLoad() {
    $(".chat-minimize, #prechatCloseBtn").on("click", LC_minimizePrechatform);

    $("#livechat-launch-eng, #livechat-launch-sales").on("click", LC_launchChatClick);

    LC_loadCountries();

    $("#prechatForm").submit(LC_submitPrechatform);

    $("#prechatSubmitOffline").on('click', function (e) {
        e.preventDefault();
        if (LC_widgetID == null) {
            LC_widgetID = renderLCRecaptcha();
        }

        if (grecaptcha.getResponse().length !== 0) {
            submitLCForm();
        } else {
            grecaptcha.execute(LC_widgetID);
        }
    });

    $('.livechat-department-btn').show();    
}

//  BEGIN GTM SECTION put this snippet in GTM to enable Chat
$(document).ready(LC_prechatPageLoad); //Do chat stuff
//  END GTM SECTION

/* END LIVE CHAT FUNCTIONS */


/* CUID Devices From Animations START */
function focusForms() {
    $('.form-group option, .form-group input, .form-group textarea').each(function () {
        if ($(this).text() != "" && $(this).val() != "" || $(this).val() != 0 || $(this).attr('type') === 'date') {
            $(this).closest(".form-group").addClass('focused');
        }
    })
}
$(document).ready(function () {
    focusForms()
})
$(document).ajaxComplete(function () {
    focusForms()
})
$(document).on('focus', '.form-group input, .form-group select, .form-group textarea', function () {
    $(this).parents('.form-group').addClass('focused');
});
$(document).on('blur', '.form-group input, .form-group select, .form-group textarea', function () {
    var inputValue = $(this).val();
    var label = $(this).siblings('label')[0];
    if ((inputValue == "" || inputValue == 0) && !$(label).hasClass('multi-spec-label') && !$(this).attr('type') === 'date') {
        $(this).removeClass('filled');
        $(this).parents('.form-group').removeClass('focused');
    } else {
        $(this).addClass('filled');
    }
});
/* CUID Devices From Animations END */

/* Stock Check BEGIN */
function changeStockCheckCountry(model, ddl) {
    var countryCode = $("#CountryCode").val();
    var currencyCode = $("#CurrencyCode").val();

    $.ajax({
        url: '/products/stockcheck/GetRegionalStockCheckForProduct?countryCode=' + countryCode + '&currencyCode=' + currencyCode + '&modelNumber=' + model,
        dataType: "html",
        type: "POST",
        beforeSend: function () {
            $('#stockCheckPartial #loading-spinner').show();
        },
        complete: function () {
            $('#stockCheckPartial #loading-spinner').hide();
        },
        success: function (data) {
            $("#stockCheckPartial").replaceWith(data);
            var dialogDiv = $('<div/>')

            $(dialogDiv).html(data);
        }
        , error: function (XMLHttpRequest, textStatus, errorThrown) {
            $("#stockCheckPartial").html("Sorry! Your search for \"" + model + "\" produced no results.");
            $(dialogDiv).dialog({
                title: 'Stock Check',
                modal: true,
                dialogClass: "stockCheckDialog",
                width: '70%',
                resizable: false,
                autoOpen: true,
                close: function (event, ui) {
                    $(".stock-check").css("pointer-events", "auto");
                    $("#stockchecklibrary td.link a").css("pointer-events", "auto");
                }
            });

            var resizeFunction = function () {
                $(dialogDiv).dialog("close")
                $(dialogDiv).dialog("open")
            }

            $(window).resize(resizeFunction);
        }
    }).done(function () {
        focusForms();
    });
}

function changeStockCheckCountryPartial(model, ddl) {
    // console.log("Check Country");

    var countryCode = $("#CountryCode").val();
    var currencyCode = $("#CurrencyCode").val();

    $.ajax({
        url: '/products/stockcheck/GetRegionalStockCheckForProduct?countryCode=' + countryCode + '&currencyCode=' + currencyCode + '&modelNumber=' + model + '&layout=ProductStockCheckPartial',
        dataType: "html",
        type: "POST",
        beforeSend: function () {
            $('#loading-spinner').show();
        },
        complete: function () {
            $('#loading-spinner').hide();
        },
        success: function (data) {
            $("#productStockCheckPartial").replaceWith(data);
            var dialogDiv = $('<div/>')
            $(dialogDiv).html(data);
        }
        , error: function (XMLHttpRequest, textStatus, errorThrown) {
            $("#productStockCheckPartial").html("Sorry! Your search for \"" + model + "\" produced no results.");
            $(dialogDiv).dialog({
                title: 'Stock Check',
                modal: true,
                dialogClass: "stockCheckDialog",
                width: '70%',
                resizable: false,
                autoOpen: true,
                close: function (event, ui) {
                    $(".stock-check").css("pointer-events", "auto");
                    $("#stockchecklibrary td.link a").css("pointer-events", "auto");
                }
            });
        }
    }).done(function () {
        focusForms();
    });
}

function distributorStockCheckPartial(model) {

    var browserLanguage = "US";
    if (window.navigator && window.navigator.language && window.navigator.language.indexOf("-") >= 0) {
        browserLanguage = window.navigator.language;
        browserLanguage = browserLanguage.substring(browserLanguage.indexOf("-") + 1);
    }

    $(".stock-check").css("pointer-events", "none");
    $("#stockchecklibrary td.link a").css("pointer-events", "none");

    var viewportWidth = window.innerWidth - 20;
    var viewportHeight = window.innerHeight * 0.9;
    if (viewportWidth > 1000) viewportWidth = 1000;
    $.ajax({
        url: '/products/stockcheck/GetDistributorStockCheckParial?countryCode=' + browserLanguage + '&modelNumber=' + model,
        dataType: "html",
        type: "POST",
        timeout: 120000,
        beforeSend: function () {
            $("#main-overlay-loading").show();
        },
        complete: function () {
            $("#main-overlay-loading").hide();

        },
        success: function (data) {

            var dialogDiv = $('<div/>')
            $(dialogDiv).html(data);
            $(dialogDiv).dialog({
                //title: 'Distributor Stock Check | ' + model,
                modal: true,
                dialogClass: "stockCheckDialog",
                height: viewportHeight,
                width: viewportWidth,
                resizable: false,
                draggable: false,
                autoOpen: true,
                open: function (event, ui) {
                    if ($(event.target).height() > $(event.target).find("#StockCheckList").height()) {
                        $(event.target).css('max-height', $(event.target).height());
                        $(event.target).css('height', 'auto');
                    } else {
                        $(event.target).css('max-height', $(event.target).height());
                        $(event.target).css('height', '');
                    }
                    $(".ui-widget-overlay").on("click", function () {
                        $(".ui-dialog-titlebar-close").trigger('click');
                    });

                    removeDialogFocus(this);
                },
                close: function (event, ui) {
                    $(this).dialog('destroy').remove();
                    $(window).unbind("resize", resizeFunction);
                    $(window).off("popstate");
                    $("body").css({ overflow: 'inherit', height: 'inherit' })

                    $(".stock-check").css("pointer-events", "auto");
                    $("#stockchecklibrary td.link a").css("pointer-events", "auto");
                },
                position: {
                    my: "center center",
                    at: "center center",
                    of: window,
                    collision: "none"
                },
                create: function (event, ui) {
                    $(event.target).parent().css('position', 'fixed');
                    $("body").css({ overflow: 'hidden', height: '100vh !important' })

                }
            });

            var resizeFunction = function () {
                var viewportHeight = window.innerHeight * 0.9;
                var viewportWidth = window.innerWidth - 20;
                if (viewportWidth > 1000) { viewportWidth = 1000 }
                else {
                    viewportWidth = viewportWidth - 40;
                };

                //$(dialogDiv).dialog("option", "position", { my: "center center", at: "center center", of: window, collision: "none" });
                $(dialogDiv).dialog("option", "width", viewportWidth);
                $(dialogDiv).dialog("option", "height", viewportHeight);
            }

            $(window).resize(resizeFunction);

            var buyNowEvent = function () {
                dataLayer.push({ 'event': 'ClickTracking', 'EventAction': $(this).data("eventaction"), 'EventLabel': $(this).data("eventlabel") });
            }
            var showNonExactResize = function () {
                var viewportHeight = window.innerHeight * 0.9;
                var needHt = $(dialogDiv).find("#StockCheckList").height() + $(dialogDiv).find(".privacy-policy").outerHeight() + $(dialogDiv).find(".ui-dialog-titlebar").outerHeight();
                if (viewportHeight > needHt) {
                    viewportHeight = "auto";
                }
                $(dialogDiv).dialog("option", "height", viewportHeight);
                $(dialogDiv).dialog("option", "position", "center");
            }
            $(dialogDiv).off("click", "a.buynow[data-eventaction][data-eventlabel]", buyNowEvent);
            $(dialogDiv).on("click", "a.buynow[data-eventaction][data-eventlabel]", buyNowEvent);
            $(dialogDiv).on("click", ".showNonExact a", showNonExactResize);

            $(dialogDiv).bind("clickoutside", function (event) {
                $(this).dialog("close");
                $(this).dialog("destroy");
                $(window).unbind("resize", resizeFunction);
            });

            $(window).on('popstate', function () {
                $(dialogDiv).dialog("close");
            });
        }
        , error: function (XMLHttpRequest, textStatus, errorThrown) {
            var dialogDiv = $('<div/>')
            $(dialogDiv).html("Sorry! Your search for \"" + model + "\" produced no results.");
            $(dialogDiv).dialog({
                title: 'Stock Check',
                modal: true,
                dialogClass: "stockCheckDialog",
                width: '70%',
                resizable: false,
                autoOpen: true,
                close: function (event, ui) {
                    $(".stock-check").css("pointer-events", "auto");
                    $("#stockchecklibrary td.link a").css("pointer-events", "auto");
                }
            });

            var resizeFunction = function () {
                var viewportWidth = window.innerWidth - 20;
                if (viewportWidth > 1000) { viewportWidth = 1000 }
                else {
                    viewportWidth = viewportWidth - 40;
                };
                $(dialogDiv).dialog("option", "position", { my: "center cetner", at: "center center", of: window, collision: "none" });
                $(dialogDiv).dialog("option", "width", viewportWidth);
                $(dialogDiv).dialog("option", "height", "auto");
            }

            $(window).resize(resizeFunction);
        }
    });
}

var runGetProductStockCheckPartial = false;
function getProductStockCheckPartial(modelNumber, modelStatus, productUrl) {
    if (!runGetProductStockCheckPartial) {
        // console.log('Render Partial')
        var browserLanguage = "US";

        if (window.navigator && window.navigator.language && window.navigator.language.indexOf("-") >= 0) {
            browserLanguage = window.navigator.language;
            browserLanguage = browserLanguage.substring(browserLanguage.indexOf("-") + 1);
        }

        $.ajax({
            url: `/products/stockcheck/GetRegionalStockCheckForProduct?countryCode=${browserLanguage}&modelNumber=${modelNumber}&layout=${"ProductStockCheckPartial"}`,
            dataType: "html",
            type: "POST",
            beforeSend: function () {
                $("#loading-spinner").show();
            },
            complete: function () {
                $('#loading-spinner').hide();
            },
            success: function (data) {

                // Band-Aid, do not remove.
                if ($('#productStockCheckPartial').length > 0) {
                    //return;
                }

                var productStockCheckDiv = $('<div/>')
                $(productStockCheckDiv).html(data);
                //hide product stock container if no stock and product is discontinued
                if ($(productStockCheckDiv).html().indexOf("not-stocked-message") > -1 && modelStatus.toLowerCase() == "d") {
                    $("#product-stock-check-container").hide();
                }
                else {
                    $('#product-stock-check').append(productStockCheckDiv);
                }
                return false;
            }
            , error: function (XMLHttpRequest, textStatus, errorThrown) {
                //Add Error
            }
        });
    }
    runGetProductStockCheckPartial = true
}


function showAMTKitModal(path) {

    var viewportWidth = window.innerWidth - 20;
    var viewportHeight = window.innerHeight * 0.9;
    if (viewportWidth > 1000) viewportWidth = 1000;
    $.ajax({
        url: `/products/product/GetSeriesPartial?path=${path}`,
        dataType: "html",
        type: "POST",
        timeout: 60000,
        beforeSend: function () {
            $("#main-overlay-loading").show();
        },
        complete: function () {
            $("#main-overlay-loading").hide();

        },
        success: function (data) {

            var dialogDiv = $('<div/>')
            $(dialogDiv).html(data);
            $(dialogDiv).dialog({
                //title: 'Distributor Stock Check | ' + model,
                modal: true,
                dialogClass: "stockCheckDialog",
                height: viewportHeight,
                width: viewportWidth,
                resizable: false,
                draggable: false,
                autoOpen: true,
                open: function (event, ui) {
                    if ($(event.target).height() > $(event.target).find("#StockCheckList").height()) {
                        $(event.target).css('max-height', $(event.target).height());
                        $(event.target).css('height', 'auto');
                    } else {
                        $(event.target).css('max-height', $(event.target).height());
                        $(event.target).css('height', '');
                    }
                    $(".ui-widget-overlay").on("click", function () {
                        $(".ui-dialog-titlebar-close").trigger('click');
                    });

                    removeDialogFocus(this);
                },
                close: function (event, ui) {
                    $(this).dialog('destroy').remove();
                    $(window).unbind("resize", resizeFunction);
                    $(window).off("popstate");
                    $("body").css({ overflow: 'inherit', height: 'inherit' })

                    window.history.replaceState(null, null, oldUrl);
                    //if (oldUrl.indexOf("/parametric-search") > -1) {
                    //    window.history.replaceState(null, null, oldUrl);
                    //}
                    //else {
                    //    window.history.back();
                    //}

                    $(".stock-check").css("pointer-events", "auto");
                    $("#stockchecklibrary td.link a").css("pointer-events", "auto");
                },
                position: {
                    my: "center center",
                    at: "center center",
                    of: window,
                    collision: "none"
                },
                create: function (event, ui) {
                    $(event.target).parent().css('position', 'fixed');
                    $("body").css({ overflow: 'hidden', height: '100vh !important' })

                }
            });

            var resizeFunction = function () {
                var viewportHeight = window.innerHeight * 0.9;
                var viewportWidth = window.innerWidth - 20;
                if (viewportWidth > 1000) { viewportWidth = 1000 }
                else {
                    viewportWidth = viewportWidth - 40;
                };

                //$(dialogDiv).dialog("option", "position", { my: "center center", at: "center center", of: window, collision: "none" });
                $(dialogDiv).dialog("option", "width", viewportWidth);
                $(dialogDiv).dialog("option", "height", viewportHeight);
            }

            $(window).resize(resizeFunction);

            var buyNowEvent = function () {
                dataLayer.push({ 'event': 'ClickTracking', 'EventAction': $(this).data("eventaction"), 'EventLabel': $(this).data("eventlabel") });
            }
            var showNonExactResize = function () {
                var viewportHeight = window.innerHeight * 0.9;
                var needHt = $(dialogDiv).find("#StockCheckList").height() + $(dialogDiv).find(".privacy-policy").outerHeight() + $(dialogDiv).find(".ui-dialog-titlebar").outerHeight();
                if (viewportHeight > needHt) {
                    viewportHeight = "auto";
                }
                $(dialogDiv).dialog("option", "height", viewportHeight);
                $(dialogDiv).dialog("option", "position", "center");
            }
            $(dialogDiv).off("click", "a.buynow[data-eventaction][data-eventlabel]", buyNowEvent);
            $(dialogDiv).on("click", "a.buynow[data-eventaction][data-eventlabel]", buyNowEvent);
            $(dialogDiv).on("click", ".showNonExact a", showNonExactResize);

            $(dialogDiv).bind("clickoutside", function (event) {
                $(this).dialog("close");
                $(this).dialog("destroy");
                $(window).unbind("resize", resizeFunction);
            });

            $(window).on('popstate', function () {
                if (oldUrl.indexOf("/parametric-search") > -1) {
                    window.history.replaceState(null, null, oldUrl);
                }
                else {
                    window.history.back();
                }

                $(dialogDiv).dialog("close");
            });
        }
        , error: function (XMLHttpRequest, textStatus, errorThrown) {
            var dialogDiv = $('<div/>')
            $(dialogDiv).html("Sorry! Your search for \"" + model + "\" produced no results.");
            $(dialogDiv).dialog({
                title: 'Stock Check',
                modal: true,
                dialogClass: "stockCheckDialog",
                width: '70%',
                resizable: false,
                autoOpen: true,
                close: function (event, ui) {
                    $(".stock-check").css("pointer-events", "auto");
                    $("#stockchecklibrary td.link a").css("pointer-events", "auto");
                }
            });

            var resizeFunction = function () {
                var viewportWidth = window.innerWidth - 20;
                if (viewportWidth > 1000) { viewportWidth = 1000 }
                else {
                    viewportWidth = viewportWidth - 40;
                };
                $(dialogDiv).dialog("option", "position", { my: "center cetner", at: "center center", of: window, collision: "none" });
                $(dialogDiv).dialog("option", "width", viewportWidth);
                $(dialogDiv).dialog("option", "height", "auto");
            }

            $(window).resize(resizeFunction);
        }
    });
}


function showStockCheckFilter(model, productUrl, layout) {
    var browserLanguage = "US";

    // console.log(model, productUrl, layout)

    if (window.navigator && window.navigator.language && window.navigator.language.indexOf("-") >= 0) {
        browserLanguage = window.navigator.language;
        browserLanguage = browserLanguage.substring(browserLanguage.indexOf("-") + 1);
    }

    $(".stock-check").css("pointer-events", "none");
    $("#stockchecklibrary td.link a").css("pointer-events", "none");

    var oldUrl = location.href.toLowerCase();
    var newUrl = oldUrl;
    if (newUrl.indexOf("product-stock-check") > -1) {
        // replace the model number at the end
        newUrl = newUrl.substring(0, newUrl.lastIndexOf('/') + 1) + model.toLowerCase();
    }
    else if (newUrl.indexOf("/product/") > -1) {
        // replace the model number at the end
        newUrl = newUrl.replace("/product/", "/product-stock-check/");
        newUrl = newUrl.substring(0, newUrl.lastIndexOf('/') + 1) + model.toLowerCase();
    }
    else if (newUrl.indexOf("/parametric-search") > -1) {
        // replace the model number at the end
        newUrl = productUrl.replace("/product/", "/product-stock-check/");
        var baseUrl = new URL(oldUrl);
        newUrl = baseUrl.origin + newUrl;
        newUrl = newUrl.substring(0, newUrl.lastIndexOf('/') + 1) + model.toLowerCase();
    }
    else {
        if (newUrl.endsWith("stock-check")) {
            newUrl += "/" + model.toLowerCase();
        }
        else {
            // replace the model number at the end
            newUrl = newUrl.substring(0, newUrl.lastIndexOf('/') + 1) + model.toLowerCase();
        }
    }

    if (oldUrl.indexOf("/parametric-search/") > -1) {
        window.history.replaceState(null, null, newUrl);
    }
    else {
        window.history.pushState(null, null, newUrl);
    }


    dataLayer.push({ 'event': 'ClickTracking', 'EventAction': 'Stock Check', 'EventLabel': model });
    var viewportWidth = window.innerWidth - 20;
    var viewportHeight = window.innerHeight * 0.9;
    var partialLayout = layout ? `&layout=${layout}` : '';
    if (viewportWidth > 1000) viewportWidth = 1000;
    $.ajax({
        url: '/products/stockcheck/GetRegionalStockCheckForProduct?countryCode=' + browserLanguage + '&modelNumber=' + model + partialLayout,
        dataType: "html",
        type: "POST",
        timeout: 60000,
        beforeSend: function () {
            $("#main-overlay-loading").show();
        },
        complete: function () {
            $("#main-overlay-loading").hide();

        },
        success: function (data) {

            var dialogDiv = $('<div/>')
            $(dialogDiv).html(data);
            $(dialogDiv).dialog({
                //title: 'Distributor Stock Check | ' + model,
                modal: true,
                dialogClass: "stockCheckDialog",
                height: viewportHeight,
                width: viewportWidth,
                resizable: false,
                draggable: false,
                autoOpen: true,
                open: function (event, ui) {
                    if ($(event.target).height() > $(event.target).find("#StockCheckList").height()) {
                        $(event.target).css('max-height', $(event.target).height());
                        $(event.target).css('height', 'auto');
                    } else {
                        $(event.target).css('max-height', $(event.target).height());
                        $(event.target).css('height', '');
                    }
                    $(".ui-widget-overlay").on("click", function () {
                        $(".ui-dialog-titlebar-close").trigger('click');
                    });

                    removeDialogFocus(this);
                },
                close: function (event, ui) {
                    $(this).dialog('destroy').remove();
                    $(window).unbind("resize", resizeFunction);
                    $(window).off("popstate");
                    $("body").css({ overflow: 'inherit', height: 'inherit' })

                    window.history.replaceState(null, null, oldUrl);
                    //if (oldUrl.indexOf("/parametric-search") > -1) {
                    //    window.history.replaceState(null, null, oldUrl);
                    //}
                    //else {
                    //    window.history.back();
                    //}

                    $(".stock-check").css("pointer-events", "auto");
                    $("#stockchecklibrary td.link a").css("pointer-events", "auto");
                },
                position: {
                    my: "center center",
                    at: "center center",
                    of: window,
                    collision: "none"
                },
                create: function (event, ui) {
                    $(event.target).parent().css('position', 'fixed');
                    $("body").css({ overflow: 'hidden', height: '100vh !important' })

                }
            });

            var resizeFunction = function () {
                var viewportHeight = window.innerHeight * 0.9;
                var viewportWidth = window.innerWidth - 20;
                if (viewportWidth > 1000) { viewportWidth = 1000 }
                else {
                    viewportWidth = viewportWidth - 40;
                };

                //$(dialogDiv).dialog("option", "position", { my: "center center", at: "center center", of: window, collision: "none" });
                $(dialogDiv).dialog("option", "width", viewportWidth);
                $(dialogDiv).dialog("option", "height", viewportHeight);
            }

            $(window).resize(resizeFunction);

            var buyNowEvent = function () {
                dataLayer.push({ 'event': 'ClickTracking', 'EventAction': $(this).data("eventaction"), 'EventLabel': $(this).data("eventlabel") });
            }
            var showNonExactResize = function () {
                var viewportHeight = window.innerHeight * 0.9;
                var needHt = $(dialogDiv).find("#StockCheckList").height() + $(dialogDiv).find(".privacy-policy").outerHeight() + $(dialogDiv).find(".ui-dialog-titlebar").outerHeight();
                if (viewportHeight > needHt) {
                    viewportHeight = "auto";
                }
                $(dialogDiv).dialog("option", "height", viewportHeight);
                $(dialogDiv).dialog("option", "position", "center");
            }
            $(dialogDiv).off("click", "a.buynow[data-eventaction][data-eventlabel]", buyNowEvent);
            $(dialogDiv).on("click", "a.buynow[data-eventaction][data-eventlabel]", buyNowEvent);
            $(dialogDiv).on("click", ".showNonExact a", showNonExactResize);

            $(dialogDiv).bind("clickoutside", function (event) {
                $(this).dialog("close");
                $(this).dialog("destroy");
                $(window).unbind("resize", resizeFunction);
            });

            $(window).on('popstate', function () {
                if (oldUrl.indexOf("/parametric-search") > -1) {
                    window.history.replaceState(null, null, oldUrl);
                }
                else {
                    window.history.back();
                }

                $(dialogDiv).dialog("close");
            });
        }
        , error: function (XMLHttpRequest, textStatus, errorThrown) {
            var dialogDiv = $('<div/>')
            $(dialogDiv).html("Sorry! Your search for \"" + model + "\" produced no results.");
            $(dialogDiv).dialog({
                title: 'Stock Check',
                modal: true,
                dialogClass: "stockCheckDialog",
                width: '70%',
                resizable: false,
                autoOpen: true,
                close: function (event, ui) {
                    $(".stock-check").css("pointer-events", "auto");
                    $("#stockchecklibrary td.link a").css("pointer-events", "auto");
                }
            });

            var resizeFunction = function () {
                var viewportWidth = window.innerWidth - 20;
                if (viewportWidth > 1000) { viewportWidth = 1000 }
                else {
                    viewportWidth = viewportWidth - 40;
                };
                $(dialogDiv).dialog("option", "position", { my: "center cetner", at: "center center", of: window, collision: "none" });
                $(dialogDiv).dialog("option", "width", viewportWidth);
                $(dialogDiv).dialog("option", "height", "auto");
            }

            $(window).resize(resizeFunction);
        }
    });
}

function downloadStockCheck(model) {
    var countryCode = $("#CountryCode").val();
    var currencyCode = $("#CurrencyCode").val();

    window.open('/products/stockcheck/GetUnfilteredStockCheckforProduct?countryCode=' + countryCode + '&currencyCode=' + currencyCode + '&modelNumber=' + model)
}

//global stock check partial
function stockCheckMoreDistributorsClick(target) {
    var distributorName = $(target).closest('tr').data('distributor');
    var modelNum = $(target).attr("model-num");
    var modelNumCol = $(`#${modelNum}`);
    var rowSpan = modelNumCol.attr("rowspan");

    $(target).closest('tr').toggleClass('expanded');

    $('.childRow[data-distributor="' + distributorName + '"][data-model="' + modelNum + '"]').each(function () {
        if ($(this).is(':visible')) {
            $(target).html("more &#9660");
            rowSpan--;
            modelNumCol.attr("rowspan", rowSpan);
            $(this).hide();
        }
        else {
            $(target).html("less &#9650;");
            rowSpan++;
            modelNumCol.attr("rowspan", rowSpan);
            $(this).show();
        }
    });
}

//product stock check partial
function productStockCheckMoreDistributorsClick(target) {
    var distributorName = $(target).closest('tr').data('distributor');
    var modelNum = $(target).attr("model-num");
    $(target).closest('tr').toggleClass('expanded');

    $('.childRow[data-distributor="' + distributorName + '"][data-model="' + modelNum + '"]').each(function () {
        if ($(this).is(':visible')) {
            $(target).html("more &#9660");
            $(this).hide();
        }
        else {
            $(target).html("less &#9650;");
            $(this).show();
        }
    });
}

function stockCheckPriceMatrixClick(target) {
    $('.stock-check-price-matrix').each(function () {
        if ($(this)[0].style.display == "none") {
            $(this).show();
        }
        else {
            $(this).hide();
        }
    });
}
/* Stock Check END */

function playSound(file) {
    let audio = new Audio(file);
    audio.play()
}


//Cart Count
function updateCartCount(response) {
    let count;

    if (response.data
        && response.data.orderLines
        && response.data.orderStatus == "Open"
    ) {
        count = response.data.orderLines.length;
    } else {
        DigiKeyCart.clearCart();
        count = 0;
    }

    $.ajax({
        type: "POST",
        url: window.location.origin + "/home/updateDKCartCount",
        data: { cartCount: count }
    });
    $("#cuid-navbar .DK-cart-count").text(count !== 0 ? count : "");
}


// Get Distributor model number 
async function getDistributorModelNumber(cuidModelNumber, distCode) {
    const result = await $.ajax({
        type: "GET",
        timeout: 120000,
        url: `/products/stockcheck/GetDistributorModelNumber?cuidModelNumber=${cuidModelNumber}&distCode=${distCode}`,
        success: function (data) {
            return data;
        },
        error: function () {
            return false;
        }
    });
    return result;

}

async function addToCart(modelNumber, quantity, productDetailUrl) {

    // Add to cart
    const url = window.location.origin + "/cart";
    DigiKeyCart.initialize(url, '@System.Configuration.ConfigurationManager.AppSettings["DigiKeyClientId"]');

    if (!quantity) {
        quantity = parseInt($('#add-to-cart-quantity').val()) ? parseInt($('#add-to-cart-quantity').val()) : 1;
    }

    // console.log("ADD TO CART", modelNumber, quantity)

    var response = await DigiKeyCart.addToCart(modelNumber, quantity, false, null, productDetailUrl);
    console.log("Add To Cart Response:", response);
    if (response.data && response.data.orderLines) {
        $.ajax({
            type: "POST",
            url: window.location.origin + "/home/updateDKCartCount",
            data: { cartCount: response.data.orderLines.length }
        });
        $("#cuid-navbar .DK-cart-count").text(response.data.orderLines.length);
    }
    return response;
};
$(function () {

    $("button.cboxSampleRequest").on("click", function (e) {
        e.preventDefault();
        getSampleRequestDialog($(this).val())
    });

    $("a.cboxSampleRequest").on("click", function (e) {
        e.preventDefault();

        getSampleRequestDialog($(this).data("value"));

        return false;
    });
});

function getSampleRequestDialog(productID) {
    var selectedIds = [productID];
    if (selectedIds.length > 0) {
        $.ajax({
            url: "/products/samplerequest/AddProductToCart",
            type: "POST",
            dataType: "json",
            traditional: true,
            data: { selectedIds: selectedIds },
            success: function (res) {
                window.location.href = "/products/samplerequest";
            }
        });
    }
}


function old_getSampleRequestDialog(productID) {
    var selectedIds = [productID];
    if ($('#SampleRequestDialog').length === 0)
        $('<div id="SampleRequestDialog"></ div>').appendTo('body');

    if (selectedIds.length > 0) {
        $.ajax({
            type: "GET",
            url: '/products/samplerequest/getsamplerequestform',
            data: { selectedIds: selectedIds },
            traditional: true,
            success: function (data) {
                $('#SampleRequestDialog').html(data);

                $('#SampleRequestDialog').dialog({
                    modal: true
                            , width: '90%'
                            , resizable: false
                            , dialogClass: 'requestDialog'
                            , position: 'center'
                            , open: function (event, ui) {
                                $(".layoutWrapper").addClass("sampleDialogOpen");
                                $(".ui-widget-overlay").addClass("sampleDialogOpen");
                                $(".ui-dialog").addClass("sampleDialogOpen");

                                
                                
                            }
                            , close: function (event, ui) {
                                $(".layoutWrapper").removeClass("sampleDialogOpen");
                                $(".ui-widget-overlay").removeClass("sampleDialogOpen");
                                $(".ui-dialog").removeClass("sampleDialogOpen");
                            }


                });

                //Fit container on the screen
                var container = $(window),
                    scrollTo = $('#SampleRequestDialog');

                container.scrollTop(
                    scrollTo.offset().top - 40
                );

                $('.ui-dialog-titlebar-close').removeClass('ui-corner-all');
            }
        });
        
    }
}

;
$(function () {

    $('.navbar-nav-li .navitem').click(function (e) {
        if (!$(this).hasClass('navitem-lang')) {
            e.preventDefault();
            e.stopPropagation();

            if (!$(this).hasClass('navbar-nav-li-lang') && !$(this).hasClass('navitem-lang') && $(this).find('a').length > 0) {
                window.location = $(this).find('a').attr("href");
            }
        }
    });

    $('.navbar-nav-li-submenu').click(function (e) {
        e.preventDefault();
        e.stopPropagation();
    });

    $('.navbar-nav-li:not(".navbar-search-carts-lang")').click(function (e) {
        e.preventDefault();
        e.stopPropagation();

        if ($(this).find('a.navbar-brand').length > 0) {
            window.location = $(this).find('a.navbar-brand').attr("href");
        }
        else if ($(window).width() >= 768) {
            if ($(this).find('a.catLink').length > 0)
                window.location = $(this).find('a.catLink').attr("href");
        }
        else {
            var $toggle = $(this).find('a.sub-nav-toggle');
            var $submenu = $(this).find('.navbar-nav-li-submenu');

            $('a.sub-nav-toggle').removeClass('sub-nav-toggle-on');
            if ($submenu.is(":visible")) {
                $toggle.removeClass('sub-nav-toggle-on');
            }
            else {
                $toggle.addClass('sub-nav-toggle-on');
            }

            // hide all other submenus
            $(".navbar-nav-li-submenu")
                .filter(function () { return $(this).attr('id') != $submenu.attr('id'); })
                .hide();

            $submenu.toggle();

            if ($(".navbar-nav-li-lang .navbar-nav-li-span span:visible").hasClass("OneLinkShow_en")) { //on english site hide enlish option
                $(".OneLinkKeepLinks.OneLinkHide_en.navitem").hide();
            }
        }
    });

    $('.navbar-nav-li').hover(
        function () {
            if ($(window).width() < 768) {
                return;
            }

            $(this).find('.navbar-nav-li-submenu').show(); // this will show the hidden submenu
            $("select").blur();
            if ($(".navbar-nav-li-lang .navbar-nav-li-span span:visible").hasClass("OneLinkShow_en")) { //on english site hide enlish option
                $(".OneLinkKeepLinks.OneLinkHide_en.navitem").hide();
            }
        },
        function () {
            hideAllSubmenus();
        }
    );

    $('body, html, div').click(function (e) {
        if (!$(e.target).closest(".navbar-nav-li").length) {
            hideAllSubmenus();
        }
    });

    var hideAllSubmenus = function () {
        if ($(window).width() < 768) {
            return;
        }
        $(".navbar-nav-li-submenu").hide().end(); // this will hide all the submenus
    }

});;
function getDataLayerMetaTag() {
    var dataLayerObj = {};
    var datalayerMetaTags = $('meta[name="datalayer"]');
    if (datalayerMetaTags.length > 0) {
        datalayerMetaTags.each((i) => {
            var jsonStr = (`{${datalayerMetaTags[i].getAttribute('content')}}`).replace(/'/g, '"');
            dataLayerObj = JSON.parse(jsonStr);
        })
    }
    return dataLayerObj
}

function csvStringToObjectArray(csvString) {

    if (typeof csvString !== 'string' || csvString.length == 0) {
        return []; // Return an empty array if the input is not a string
    }

    const items = csvString.split(',');
    const result = [];

    for (let i = 0; i < items.length; i++) {
        const item = {
            [`item_category${i === 0 ? '' : i + 1}`]: items[i]
        };
        result.push(item);
    }

    return result;
}

function getItemIndex(rowIdx) {
    rowIdx = parseInt(rowIdx);
    var pageNumber = parseInt($('#PageToShow').val()) - 1;
    var showCount = parseInt($('#resultsToDisplay').find(':selected').val());

    // showCount is 999 when 'All' is selected
    if (pageNumber && showCount && showCount !== 999) {
        return (rowIdx + (pageNumber * showCount))

    } else {
        return rowIdx;
    }
}


// New IDEA:
// We'll use this every time getCart() is called, which I believe is gonna be every page load in the navigation 
function syncProductsInCartToLS(dkCartResponse) {



    if (dkCartResponse.data
        && dkCartResponse.data.orderLines
        && dkCartResponse.data.orderStatus == "Open"
    ) {
        var dkCart = dkCartResponse.data.orderLines,
            lsCart = getProductsFromLocalStorage();

        // Extract orderLineIds for efficient lookup
        var dkCartOrderLineIds = new Set(dkCart.map(p => p.orderLineId));
        var lsCartOrderLineIds = new Set(lsCart.map(p => p.orderLineId));

        // Check for additional items in dkCart
        var additionalItems = dkCart.filter(p => !lsCartOrderLineIds.has(p.orderLineId));
        if (additionalItems.length > 0) {
            //console.log("Additional Items in DK:", additionalItems);

            // Convert and add to lsCart
            var newLsProducts = convertDkToLsProducts(additionalItems);

            //todo Add to cart datalayer event
            newLsProducts.forEach(p => {
                //console.log("DL add_to_cart:", p)
                dataLayer.push({
                    event: 'add_to_cart',
                    ecommerce: {
                        items: [p]
                    }
                });
            })

            // Use concat to add the new items
            lsCart = lsCart.concat(newLsProducts);
        }

        // Check for missing items in dkCart
        var missingItems = lsCart.filter(p => !dkCartOrderLineIds.has(p.orderLineId));
        if (missingItems.length > 0) {
            //console.log("Missing Items in DK:", missingItems);

            //todo Remove from cart datalayer event
            missingItems.forEach(p => {
                //console.log("DL remove_from_cart:", p)
                dataLayer.push({
                    event: 'remove_from_cart',
                    ecommerce: {
                        items: [p]
                    }
                })
            })

            // Remove missing items from lsCart
            lsCart = lsCart.filter(p => dkCartOrderLineIds.has(p.orderLineId));
        }

        // Sync quantities and prices
        lsCart.forEach(lsProduct => {
            var dkProduct = dkCart.find(dkProduct => dkProduct.orderLineId === lsProduct.orderLineId);

            // check to see if there is a delta and fire datalayer
            if (dkProduct && lsProduct.quantity !== dkProduct.quantity) {

                //console.log(lsProduct, dkProduct);
                var updatedProduct = convertDkToLsProducts([dkProduct])[0];
                updatedProduct.quantity = Math.abs(dkProduct.quantity - lsProduct.quantity);
                updatedProduct.extended_price = (updatedProduct.quantity * updatedProduct.price);

                if (dkProduct.quantity > lsProduct.quantity) {
                    //todo Add to cart datalayer event
                    //console.log("DL add_to_cart:", updatedProduct)
                    dataLayer.push({
                        event: 'add_to_cart',
                        ecommerce: {
                            items: [updatedProduct]
                        }
                    })
                } else {
                    //todo remove from cart datalayer event
                    //console.log("DL remove_from_cart:", updatedProduct)

                    dataLayer.push({
                        event: 'remove_from_cart',
                        ecommerce: {
                            items: [updatedProduct]
                        }
                    })
                }

                lsProduct.price = parseFloat(dkProduct.unitPrice);
                lsProduct.extended_price = parseFloat(dkProduct.extendedPrice);
                lsProduct.quantity = dkProduct.quantity;
            }
        });

        // Set local storage variable
        localStorage.setItem('dataLayerProducts', JSON.stringify(lsCart));
    } else {
        // No items in DK cart, remove anything in local storage
        //console.log("No items in DK Cart, removing all LS products");
        localStorage.removeItem('dataLayerProducts');
    }
}



function addProductToLocalStorage(product, dkCart) {
    //console.log("Add to local storage")

    // Get all products from local storage
    var productsFromLS = getProductsFromLocalStorage();
    var productsFromLSOrderLineId = new Set(productsFromLS.map(p => p.orderLineId));
    var newProducts = dkCart.filter(p => !productsFromLSOrderLineId.has(p.orderLineId));

    // Check if there is only one line in the cart, if so that is the newly added product
    if (newProducts.length === 1) {
        product.orderLineId = newProducts[0].orderLineId;
    } else if (newProducts.length > 1) {
        //console.log("Uh Oh")
        // Edge case, if there are more than one "new" products from filtering out missing orderLineIds, refine by modelNumber and add the "extra" as is
        var randoPartThatMatches = newProducts.find(p => product.item_name == p.manufacturerPartNumber)
        product.orderLineId = randoPartThatMatches.orderLineId;
    }

    var allProducts = [
        product,
        ...productsFromLS
    ];

    // Set local storage variable
    localStorage.setItem('dataLayerProducts', JSON.stringify(allProducts));
}



function removeProductFromLocalStorage(product) {
    // We'll use the item_name and quantity to find the item to remove. There could be multiple of the same item, so make sure to only remove the first item.
    //console.log("Remove from local storage:", product)
    var products = getProductsFromLocalStorage();
    var matchFound = false;
    var filteredProducts = products.filter(p => {
        if (!matchFound && p.item_name == product.item_name && parseInt(p.quantity) == product.quantity) {
            matchFound = true;
            return false; // Skip first match
        }
        return true; // Include all other products
    });

    localStorage.setItem('dataLayerProducts', JSON.stringify(filteredProducts));
}


function getProductsFromLocalStorage() {
    var products = JSON.parse(localStorage.getItem('dataLayerProducts'));
    return products ? products : [];
}

// Fire dataLayer push with any meta tags
$(document).ready(function () {
    var dataLayerObj = getDataLayerMetaTag();
    if (Object.keys(dataLayerObj).length !== 0) {
         //console.log("DATALAYER PUSH:", dataLayerObj)
        dataLayer.push(dataLayerObj);
    }

    // Mouse up is a hack because "click" was not firing on the first click
    $(document).on("mouseup", ".dataLayerClickEvent", function () {

        var dataLayerObj = getDataLayerMetaTag();
        var itemCategories = this.getAttribute('dl-itemCategories');
        var categoriesArray = csvStringToObjectArray(itemCategories)
        var eventName = this.getAttribute('dl-eventName');
        var listName = this.getAttribute('dl-listName');
        var itemNumber = this.getAttribute('dl-itemNumber');
        var resourceType = this.getAttribute('dl-resourceType');
        var resourceTags = this.getAttribute('dl-resourceTags');
        var affiliation = eventName ? "Same Sky" : null;
        var varsPartner = this.getAttribute('dl-varsPartner');
        var socialNetwork = this.getAttribute('dl-socialNetwork');
        var distributorname = this.getAttribute('dl-distributorName');
        var itemIndex = this.getAttribute('dl-itemIndex');
        var isEcommerce = this.hasAttribute('dl-ecommerce');

        $.extend(
            dataLayerObj,
            ...categoriesArray,
            { 'event': eventName ? eventName : undefined },
            { 'item_list_name': listName ? listName : undefined },
            { 'item_name': itemNumber ? itemNumber : undefined },
            { 'item_id': itemNumber ? itemNumber : undefined },
            { 'resource_type': resourceType ? resourceType : undefined },
            { 'resource_tags': resourceTags ? resourceTags : undefined },
            { 'affiliation': affiliation ? affiliation : undefined },
            { 'item_brand': affiliation ? affiliation : undefined },
            { 'vars_partner': varsPartner ? varsPartner : undefined },
            { 'social_network': socialNetwork ? socialNetwork : undefined },
            { 'distributor_name': distributorname ? distributorname : undefined },
            { 'index': itemIndex ? getItemIndex(itemIndex) : undefined }
        )

        if (isEcommerce) {
            var { event, ...rest } = dataLayerObj;
            rest.quantity = 1;

            dataLayerObj = {
                event,
                'ecommerce': {
                    'items': [rest]
                }
            }
        } 

         //console.log("DATALAYER CLICK EVENT:", dataLayerObj)
        dataLayer.push(dataLayerObj);
    })
});
