/* Minification failed. Returning unminified contents.
(71,25-26): run-time warning JS1004: Expected ';': c
(73,29-30): run-time warning JS1004: Expected ';': p
(74,29-30): run-time warning JS1004: Expected ';': i
(75,29-30): run-time warning JS1004: Expected ';': i
(77,29-30): run-time warning JS1004: Expected ';': f
(91,33-34): run-time warning JS1004: Expected ';': f
(92,33-34): run-time warning JS1004: Expected ';': p
(107,29-30): run-time warning JS1004: Expected ';': c
(108,29-30): run-time warning JS1004: Expected ';': t
(112,29-30): run-time warning JS1004: Expected ';': c
(113,29-30): run-time warning JS1004: Expected ';': c
(114,29-30): run-time warning JS1004: Expected ';': s
(138,29-30): run-time warning JS1004: Expected ';': p
(139,29-30): run-time warning JS1004: Expected ';': i
(140,29-30): run-time warning JS1004: Expected ';': i
(143,33-34): run-time warning JS1004: Expected ';': f
(144,33-34): run-time warning JS1004: Expected ';': p
(174,33-34): run-time warning JS1004: Expected ';': p
(175,33-34): run-time warning JS1004: Expected ';': i
(176,33-34): run-time warning JS1004: Expected ';': p
(177,33-34): run-time warning JS1004: Expected ';': f
(182,37-38): run-time warning JS1004: Expected ';': f
(183,37-38): run-time warning JS1004: Expected ';': p
(201,33-34): run-time warning JS1004: Expected ';': o
(205,33-34): run-time warning JS1004: Expected ';': q
(207,37-38): run-time warning JS1004: Expected ';': n
(214,37-38): run-time warning JS1004: Expected ';': i
(219,37-38): run-time warning JS1004: Expected ';': k
(239,33-34): run-time warning JS1004: Expected ';': f
(249,21-22): run-time warning JS1004: Expected ';': q
(251,21-22): run-time warning JS1004: Expected ';': f
(254,25-26): run-time warning JS1004: Expected ';': f
(255,25-26): run-time warning JS1004: Expected ';': f
(256,25-26): run-time warning JS1004: Expected ';': p
(257,25-26): run-time warning JS1004: Expected ';': p
(270,37-38): run-time warning JS1004: Expected ';': i
(276,37-38): run-time warning JS1004: Expected ';': c
(294,13-14): run-time warning JS1004: Expected ';': f
(297,21-22): run-time warning JS1004: Expected ';': u
(298,21-22): run-time warning JS1004: Expected ';': e
(299,21-22): run-time warning JS1004: Expected ';': e
(300,21-22): run-time warning JS1004: Expected ';': e
(322,21-22): run-time warning JS1004: Expected ';': u
(344,25-26): run-time warning JS1004: Expected ';': n
(345,25-26): run-time warning JS1004: Expected ';': h
(363,33-34): run-time warning JS1004: Expected ';': a
(370,33-34): run-time warning JS1004: Expected ';': a
(493,13-14): run-time warning JS1004: Expected ';': a
(494,13-14): run-time warning JS1004: Expected ';': a
(496,17-18): run-time warning JS1004: Expected ';': e
 */
(function ($) {
    $(function () {
        /* BIG MENU PANEL */
        $('.cd-btn').on('click', function (event) {
            event.preventDefault();
            $('.cd-panel').addClass('is-visible');
        });

        $('.cd-panel-close').on('click', function (event) {
            event.preventDefault();
            $('.cd-panel').removeClass('is-visible');
        });

        $('.cd-panel').on('click', function (event) {
            if ($(event.target).is('.cd-panel') || $(event.target).is('.cd-panel-close')) {
                $('.cd-panel').removeClass('is-visible');
                event.preventDefault();
            }
        });

        /* LOGIN MENU */
        $('.btn-login-toggle').on('click', function (event) {
            event.preventDefault();
            event.stopPropagation();
            $(this).parent().toggleClass('open');
        });
        $(document).on('click', function (event) {
            var parents = $(event.target).parents('.header-login-submenu');
            var headerLogin = $('.header-login-submenu');
            if (parents.length === 0 && headerLogin.hasClass('open')) {
                headerLogin.removeClass('open');
            }
        });
        $('.btn-user-toggle').parent().on('mouseover', function () {
            $(this).addClass('open');
        }).on('mouseout', function () {
            $(this).removeClass('open');
        });

        // PDF Viewer modal
        $('.docViewer').click(function (e) {
            if ($(window).width() > 800) {

                var docUrl = $(this).attr('href');
                var extension = docUrl.substr(docUrl.lastIndexOf('.') + 1);
                if (extension.toLowerCase() === 'pdf') {
                    e.preventDefault();
                    $("#docViewer iframe").prop('src', docUrl);
                    // reset size&pozition
                    var modalStyle = "display:flex;flex-direction:column;height:90vh";
                    $("#docViewer .modal-content").attr("style", modalStyle)
                    $("#docViewer .modal-content").resizable({
                        minHeight: 300,
                        minWidth: 300
                    });
                    $("#docViewer .modal-content").draggable();
                    $("#docViewer").modal('show');
                }
            }
        });

        var initFilters = function () {
            $('.dynamic-filterset-search-select').dropdown({
                clearable: true,
                forceSelection: false,
                fullTextSearch: "exact",
                direction: 'downward',
                showOnFocus: true,

                onChange: function (value, text, $selectedItem) {
                    let contextValue = value;
                    if (value) {
                        let parent = $selectedItem.attr('data-parent');
                        let inputProduct = $selectedItem.attr('product-name');
                        let inputFilter = $selectedItem.attr('filter-name');

                        let firstTime = $selectedItem.closest('.filterset-select-feed').length;
                        if (firstTime) {
                            $selectedItem.closest('.filterset-select-feed').removeClass('filterset-select-feed');
                        } else {
                            $selectedItem.closest('.search-select').nextAll('.filterset-search-select').each(function (index, value) {
                                $(value).dropdown('clear');
                            });
                        }

                        if (parent) {
                            contextValue = parent;
                        }

                        setTimeout(function () {
                            let filterEl = $selectedItem.closest('.dropdown').find('input[name="' + inputFilter + '"]');
                            let productEl = $selectedItem.closest('.dropdown').find('input[name="' + inputProduct + '"]');
                            if (parent && parent != '0') {
                                filterEl.val(parent);
                                productEl.val(productEl.val().replace('fp_', ''));
                            } else {
                                if (parent == '0') {
                                    filterEl.val('');
                                    productEl.val(productEl.val().replace('p_', ''));
                                } else {
                                    filterEl.val(value);
                                    productEl.val('');
                                }
                            }
                        }, 200);

                        let context = $(this).parents("form").attr('id');
                        let type = $(this).attr('data-name').replace('flt_', '');

                        filterOptions(context, type, contextValue);
                    } else {
                        let context = $(this).parents("form").attr('id');
                        let continueReset = true;
                        let selectorName = $(this).data('name');
                        $('#' + context).children('.dynamic-filterset-search-select').each(function (index, el) {
                            if (continueReset) {
                                $(el).removeClass('disabled');
                                $(el).find('.menu .item').removeClass('hidden').addClass('available');
                                if (selectorName === $(this).data('name'))
                                    continueReset = false;
                            }
                        });
                    }
                }
            });

            $('.local-filterset-search-select').dropdown({
                clearable: true,
                forceSelection: false,
                fullTextSearch: "exact",
                // minCharacters: 4,
                direction: 'downward',
                showOnFocus: true,

                onChange: function (value, text, $selectedItem) {

                    if (value) {
                        let parent = $selectedItem.attr('data-parent');
                        let inputProduct = $selectedItem.attr('product-name');
                        let inputFilter = $selectedItem.attr('filter-name');

                        setTimeout(function () {
                            let filterEl = $selectedItem.closest('.dropdown').find('input[name="' + inputFilter + '"]');
                            let productEl = $selectedItem.closest('.dropdown').find('input[name="' + inputProduct + '"]');
                            if (parent && parent != '0') {
                                filterEl.val(parent);
                                productEl.val(productEl.val().replace('fp_', ''));
                            } else {
                                if (parent == '0') {
                                    filterEl.val('');
                                    productEl.val(productEl.val().replace('p_', ''));
                                } else {
                                    filterEl.val(value);
                                    productEl.val('');
                                }
                            }
                        }, 200);
                    }
                }
            });

            $('.remote-filterset-search-select').dropdown()
                .dropdown({
                    clearable: true,
                    forceSelection: false,
                    fullTextSearch: "exact",
                    direction: 'downward',
                    showOnFocus: true,
                    saveRemoteData: false,

                    onChange: function (value, text, $selectedItem) {
                        if (value) {

                            let parentId = parseInt($selectedItem.children('.prd-parent').data('parent'));
                            let isProduct = $selectedItem.children('.prd-code').html().length;
                            let productName = $selectedItem.closest('.dropdown').attr('product-name');
                            let filterName = $selectedItem.closest('.dropdown').attr('data-name');

                            value = value.replace('fp_', '').replace('p_', '');

                            setTimeout(function () {
                                let filterEl = $selectedItem.closest('.dropdown').find('input[name="' + filterName + '"]');
                                let productEl = $selectedItem.closest('.dropdown').find('input[name="' + productName + '"]');
                                if (parentId == 0 && !isProduct) {// filter option
                                    filterEl.val(value);
                                    productEl.val('');
                                }
                                if (parentId == 0 && isProduct) { // product
                                    filterEl.val('');
                                    productEl.val(value);
                                }
                                if (parentId != 0 && isProduct) { // associated product
                                    filterEl.val(parentId);
                                    productEl.val(value);
                                }
                            }, 200);
                        }
                    },
                    apiSettings: {
                        onResponse: function (response) {
                            let options = { success: true, results: [] };
                            if (!response.Results.length)
                                options.success = false;

                            let query = response.Query;
                            options.results = response.Results.map(function (value) {
                                let name = value.Name;
                                if (query) {
                                    var regEx = new RegExp(query, "ig");
                                    name = value.Name.replace(regEx, function (match) {
                                        return '<span style="background-color:yellow">' + match + '</span>'
                                    });
                                }
                                let innerHTML = '<span class="prd-parent" data-parent="{productParent}"></span><span class="prd-code">{productCode}</span><span class="prd-name">{productName}</span>';
                                innerHTML = innerHTML.replace('{productCode}', value.ProductCode ? value.ProductCode : "");
                                innerHTML = innerHTML.replace('{productName}', name);
                                innerHTML = innerHTML.replace('{productParent}', value.Parent ? value.Parent : "0");

                                let key = value.Id;
                                if (value.ProductCode) {
                                    key = 'p_' + key;
                                }
                                if (value.Parent) {
                                    key = 'f' + key;
                                }

                                return { value: key, name: innerHTML };
                            });

                            options.results.push({
                                value: '',
                                name: '',
                                disabled: true,
                            });

                            return options;
                        },
                        beforeSend: function (settings) {
                            let filterId = parseInt($(this).data('name').split('_')[1]);
                            settings.data = { filterId: filterId };
                            return settings;
                        },
                        cache: false,
                        url: '/api/Filter/Search/{query}'
                    }
                });

            $('.remote-filterset-search-select').each(function (index, selector) {
                let query = new URLSearchParams(window.location.search);

                let filterOptionVar = $(selector).data('name')

                if (query.get(filterOptionVar) != null && query.get(filterOptionVar) != '') {
                    let filterId = parseInt(filterOptionVar.split('_')[1]);
                    let filterOptionId = parseInt(query.get(filterOptionVar));
                    let productId = 0;
                    let productVar = $(selector).attr('product-name');
                    if (query.get(productVar) != null && query.get(productVar) != '')
                        productId = parseInt(query.get(productVar));

                    $.ajax({
                        url: '/api/Filter/Product',
                        data: {
                            filterId: filterId,
                            filterOptionId: filterOptionId,
                            productId: productId
                        },
                        success: function (result) {
                            if (result.Id != 0) {
                                let innerHTML = '<div class="item selected" data-value="{value}"><span class="prd-parent" data-parent="{productParent}"></span><span class="prd-code">{productCode}</span><span class="prd-name">{productName}</span></div>';
                                innerHTML = innerHTML.replace('{value}', result.Id);
                                innerHTML = innerHTML.replace('{productCode}', result.ProductCode ? result.ProductCode : "");
                                innerHTML = innerHTML.replace('{productName}', result.Name);
                                innerHTML = innerHTML.replace('{productParent}', result.Parent ? result.Parent : "0");

                                let container = $(selector).children('.menu');
                                container.append(innerHTML);

                                $(selector).dropdown('refresh');
                                setTimeout(function () {
                                    $(selector).dropdown('set selected', result.Id);
                                }, 1);
                            }
                        }
                    });
                }
            });
        };

        // new filters
        var allRules = [];
        var rulesLoaded = false;

        let filterOptions = function (context, type, value) {
            if (rulesLoaded) {
                //console.log(context, type, value);
                let userInputs = [];
                let eligibleRules = [];
                let elValue = null;
                let elKey = null;

                elValue = value;
                if (type !== 'product') {
                    elKey = type;
                } else {
                    return;
                }

                // hide all options
                $('#' + context + ' .search-select .menu .item').removeClass('available').addClass('hidden');
                $('#' + context + ' .search-select').each(function (index, el) { $(el).removeClass('disabled'); });

                allRules.forEach(function (rule, ruleIndex) {
                    rule.forEach(function (ruleEl, ruleElindex) {
                        if (ruleEl.Key == Number(elKey) && ruleEl.Value == Number(elValue)) {
                            eligibleRules.push(ruleIndex);
                        }
                    });
                });

                // Keep only the rules that are valid
                let updatedValidRules = [];
                eligibleRules.forEach(function (eligibleRule) {
                    updatedValidRules.push(allRules.slice(eligibleRule, eligibleRule + 1)[0]);
                });

                validRules = updatedValidRules.slice();

                $('#' + context + ' .search-select[data-name=flt_' + elKey + '] .menu').children('.item').removeClass('hidden').addClass('available');

                validRules.forEach(function (validRule) {
                    validRule.forEach(function (ruleEl) {
                        $('#' + context + ' .search-select[data-name=flt_' + ruleEl.Key + '] .menu').children('.item[data-value=' + ruleEl.Value + ']').removeClass('hidden').addClass('available');
                        // for products filters
                        $('#' + context + ' .search-select[data-name=flt_' + ruleEl.Key + '] .menu').children('.item[data-parent=' + ruleEl.Value + ']').removeClass('hidden').addClass('available');
                        if (ruleEl.Key != elKey) {
                            $('#' + context + ' .search-select[data-name=flt_' + ruleEl.Key + ']').attr('data-against', elKey).attr('data-against-value', value);
                        }

                    });
                });

                $('#' + context + ' .search-select').each(function (index, el) {
                    let numberItems = $(el).find('.menu').children('.item').length;
                    let hiddenItems = $(el).find('.menu').children('.item.hidden').length;
                    if (numberItems == hiddenItems) {
                        $(el).find('.text.default').html('');
                        $(el).addClass('disabled');
                    }
                });
            }
        };

        initFilters();

        $.get('/api/Filter/Combinations',
            function (data) {
                allRules = data;
                if (data.length > 0) {
                    rulesLoaded = true;
                    if ($('.dynamic-hidden-filter').length) {
                        $('.dynamic-hidden-filter').each(function (index, obj) {
                            let autoFill = $(this).find('.item.auto-filtered').attr('data-value');
                            if (autoFill) {
                                $(this).dropdown('set selected', autoFill);
                            }
                        });
                    } else {
                        $('.dynamic-filterset-search-select').each(function (index, obj) {
                            let autoFill = $(this).find('.item.active.selected').attr('data-value');
                            if (autoFill) {
                                $(this).dropdown('set selected', autoFill);
                            }
                        });
                    }
                }
            }
        );

        /* 
         * For detect menu collisions
         * 
         * @param string|object elements_container: parent of elements selector
         * @param string        elementA: first element selector
         * @param string        elementB: second element selector
         * @param int           betweenMargin: margin between the elements
         * 
         * @return: true or false
         */
        function elementsColliding(elementsContainer, elementA, elementB, betweenMargin) {

            var elementsContainer_width = $(elementsContainer).width();
            var elementA_width = $(elementA).width();
            var elementB_width = $(elementB).width();

            return ((elementA_width + elementB_width) + betweenMargin) >= elementsContainer_width;
        }

        /* 
         * Change collision status on #second-nav
         * 
         * @return: none
         */
        function navWatch() {
            if (elementsColliding('#second-nav .container', '#second-nav .left-nav', '#second-nav .navbar-right', 100)) {
                $('#second-nav').addClass('colliding'); //console.log('colliding');
            } else {
                $('#second-nav').removeClass('colliding'); //console.log('no colliding');
            }
        }

        // register resize event on #second-nav
        $('#second-nav').resize(navWatch);
        // fix init calc
        navWatch();

        // resizable elements

        var resizableElementSelector = '.resizable';
        var resizableSelector = '.resizable .resizable-area';
        var resizingElement = null;
        var resizing = false;
        var resizingDirection = '';
        var currentPosition = 0;

        // unbind for prevent multiple instances duplicates
        $(resizableElementSelector).unbind();
        $(resizableSelector).unbind();

        $(resizableSelector).mousedown(function (e) {
            resizing = true;
            currentPosition = e.pageX;
            // for multiple instances
            resizingElement = $(this).closest(resizableElementSelector);
            // for fix elements align
            resizingDirection = resizingElement.attr('resizing-direction') ? resizingElement.attr('resizing-direction') : '';
        });
        $(document, resizableSelector, resizableElementSelector).mouseup(function () {
            resizing = false;
            resizingElement = null;
        });
        $(document).mousemove(function (e) {
            if (resizing == true && resizingElement != null) {
                console.log(resizingElement.width(), (currentPosition - e.pageX));
                var positionDiference = currentPosition - e.pageX;
                var elementWidth = resizingElement.width();
                var nextWidth = resizingDirection == ''
                    ? elementWidth + positionDiference
                    : elementWidth - positionDiference;
                resizingElement.width(nextWidth);
                currentPosition = e.pageX;
            }
        });

        $(document).on('DOMSubtreeModified', '.local-filterset-search-select .text', function () {
            var parentId = $(this).closest('.local-filterset-search-select').attr('product-name');
            var productId = $(this).find('.id').text();
            if (!productId) {
                $('#' + parentId).val('');
            }
        });

        if ($('.hs-toggle').length) {
            $('.hs-toggle').click(function (e) {
                e.preventDefault();
                if ($('.related-products').hasClass('o')) {
                    $('.related-products').slideUp('fast');
                    $('.related-products').removeClass('o');
                    $(this).children('.fa').removeClass('fa-toggle-on').addClass('fa-toggle-off');
                } else {
                    $('.related-products').slideDown('fast');
                    $('.related-products').addClass('o');
                    $(this).children('.fa').removeClass('fa-toggle-off').addClass('fa-toggle-on');
                }
            });
        }

        if ($('.my-expand').length) {
            $('.my-expand:not(.o) .expand-description').slideUp('fast');
            $('.my-expand .main-link').click(function (e) {
                if (e.target.tagName !== 'A') {
                    var parent = $(this).closest('.my-expand');
                    if (parent.hasClass('o')) {
                        parent.children('.expand-description').slideUp('fast');
                    } else {
                        parent.children('.expand-description').slideDown('fast');
                    }
                    parent.toggleClass('o');
                }
            });
        }

        let allAnchors = document.links || document.getElementsByTagName('a');
        let allLinks = Array.prototype.slice.call(allAnchors, 0);
        allLinks.forEach(function (element) {
            let external = element.hostname != window.location.hostname;
            if (external && element.hostname && !element.target) {
                element.target = "_blank";
            }
        });
    });
})(jQuery);
;
(function ($) {
    $(function () {

        $('.btn-yesno').button();
        $('.btn-yesno').on('click', function (e) {
            var radio = $(e.target).find('[type="radio"]');
            var value = $(radio).val();
            var embededUrlSection = $('#embeded-url-section').html();
            embededUrlSection = embededUrlSection.replace('includeSearch=false', 'includeSearch=' + value);
            embededUrlSection = embededUrlSection.replace('includeSearch=true', 'includeSearch=' + value);
            $('#embeded-url-section').html(embededUrlSection);
        });

        $('.btn-opts').button();
        $('.btn-opts').on('click', function (e) {
            var radio = $(e.target).find('[type="radio"]');
            var value = ($(radio).val() == "true");
            $("#embed-search-only").toggle(!value);
            $("#embed-page-only").toggle(value);
        });

        // TODO put this somewhere else
        $('.row-block').on('click', function (e) {
            var block = $(this);
            if (block.hasClass('opened')) {
                block.removeClass('opened');
            } else {
                block.addClass('opened');
            }
        });

        $('#headerResume').on('click', function (e) {
            if ($(this).hasClass('opened')) {
                $(this).removeClass('opened');
                $('.row-block').removeClass('opened');
                $('.block-step-container').collapse('hide')
            } else {
                $(this).addClass('opened');
                $('.row-block').addClass('opened');
                $('.block-step-container').collapse('show')
            }
        });

        var isChanging = false;
        //bind show/hide cr
        $(".checkCR").change(function (e) {
            
            if (!isChanging) {

                isChanging = true;

                $(".checkCR").prop('checked', $(this).prop('checked'));

                var url = '/Base/ToggleConsistency/';
                //ajax
                $.get(url,
                    function (data) {
                        if (data === true) {
                            $(".crItem").show();
                            $(".crMenuItem").show();
                            $("img.online").addClass("lefted");
                        } else {
                            $(".crItem").hide();
                            $(".crMenuItem").hide();
                            $("img.online").removeClass("lefted");
                        }

                        isChanging = false;
                    })
                    .fail(
                    function (jqXHR, textStatus, err) {

                            $("#errorsPane").html("<span class='error'>" + err + "</span>").show();

                            isChanging = false;
                        }
                    );
            }
        });

        var changingAB = false;
        $(".checkAB").on("change", function (e) {
            var url = '/Base/ToggleAdminBurden/';
            if (!changingAB) {
                // for logical checks
                changingAB = true;
                $(".checkAB").prop('checked', $(this).prop('checked'));
                //ajax
                $.get(url,
                function () {
                    changingAB = false;
                })
                .fail(
                function (jqXHR, textStatus, err) {
                    $("#errorsPane").html("<span class='error'>" + err + "</span>").show();
                    changingAB = false;
                });
            }
        });

        var bigMenuContainer = $("#big-menu-container");
        if (!_.isUndefined(bigMenuContainer)) {
            bigMenuContainer.find('.submenu.level2').slideToggle();
            bigMenuContainer.find('.side-menu-submenu').click(function () {
                var $this = $(this);
                if (!$this.parent().parent().hasClass('level2')) {
                    $this.next('.submenu').slideToggle();
                    $this.parent().parent().toggleClass('active');
                }
            });
        }
            
        $.getJSON("/api/Feedback/Countries", function (result) {
            var $dropdown = $("#cboCountry");
            $.each(result, function () {
                $dropdown.append($("<option />").val(this.Code).text(this.Text));
            });
        });

        $(".contact-us-anchor").click(function () {
            $("#feedbackModal").modal();
            $('body > .modal-backdrop').css('opacity', 0);
            document.dispatchEvent(new CustomEvent('feedbackButtonClick', { detail: { typeId: 0, stepId: 0 } }));
        });
    });
})(jQuery);
;
