/* Minification failed. Returning unminified contents.
(8323,6): run-time error JS1004: Expected ';'
(8324,26): run-time error JS1004: Expected ';'
(8325,44): run-time error JS1004: Expected ';'
 */

function smartSearching(searchType, subSearchType) {
    if (getSearchPhrase() != "" && searchType != "-1") {
        $(".flex-smart-search").find('.flex-smart-search-whisperer').slideUp({ duration: 400, easing: 'easeInBack' });
        __searching(searchType, subSearchType, getSearchPhrase());
    } else if (getSearchPhrase() != "" && searchType == "-1") {
        flexShowToastError($(this).attr('data-flex-no-search-target-selected-message'));
    } else {
        flexShowToastError($(this).attr('data-flex-no-value-error-message'));
    }
}

function getSearchPhrase() {
    return $('#SmartSearchInput').val().trim();
}

function __searching(searchType, subSearchType, searchText) {
    __redirect("/navigation/search/smartsearch/?searchType=" + searchType + "&subSearchType=" + subSearchType + "&searchText=" + searchText)
}

function __redirect(searchAdress) {
    window.location.href = searchAdress;
};
(function ($) {
    let initialWidth = $(window).width();

    ['mousemove', 'touchmove', 'wheel'].forEach(function (event) {
        let currentWidth = $(window).width();
        if (currentWidth !== initialWidth && currentWidth < 990 && initialWidth >= 990 || currentWidth >= 990 && initialWidth < 990) {
            initialWidth = currentWidth;

            $('.products .flex-delivery-times[data-flex="true"]').FlexCollapseDeliveryBoxInitialState();
            $('.products .flex-delivery-times[data-flex!="true"]').FlexCollapsibleDeliveryTimes();
        }
    });

    flexCollapsibleSideItemsCollection = function () {
        let toggleElement = $(".flex-side-vehicle-info .toogle-collapse-button");
        let elements = $(".items-collections");
        let span = toggleElement.find(".text");

        if (elements.attr("data-flex") == "false") {
            elements.attr("data-flex", "true");
            elements.show();
            span.text(toggleElement.attr("data-expanded-text"));
            return;
        }

        elements.attr("data-flex", "false");
        elements.hide();
        span.text(toggleElement.attr("data-collapsed-text"));
    }

    var layer = 999;

    // Detects if user is using mobile device.
    isSmallScreen = function (element) {
        return $(".flex-screen-detection").css("float") == "right";
    }

    isKeyPrintable = function (keyCode) {
        return (keyCode > 47 && keyCode < 58) ||                 // number keys
            keyCode == 8 || keyCode == 32 || keyCode == 46 || // backspace, space, delete
            (keyCode > 64 && keyCode < 91) ||                    // letter keys
            (keyCode > 95 && keyCode < 112) ||                   // numpad keys
            (keyCode > 185 && keyCode < 193) ||                  // ;=,-./` (in order)
            (keyCode > 218 && keyCode < 223) ||                  // [\]' (in order)
            keyCode === 229;                                     //some androids https://stackoverflow.com/questions/36753548/keycode-on-android-is-always-229
    }

    setCaretAtEnd = function (element) {
        element = $(element).get(0);
        var elemLen = element.value.length;
        // For IE Only
        if (document.selection) {
            // Set focus
            element.focus();
            // Use IE Ranges
            var oSel = document.selection.createRange();
            // Reset position to 0 & then set at end
            oSel.moveStart('character', -elemLen);
            oSel.moveStart('character', elemLen);
            oSel.moveEnd('character', 0);
            oSel.select();
        }
        else if (element.selectionStart || element.selectionStart == '0') {
            // Firefox/Chrome
            element.selectionStart = elemLen;
            element.selectionEnd = elemLen;
            element.focus();
        } // if
    }

    sleep = function (ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    debounce = function (func, delay = 300) {
        let timerId;
        return (...args) => {
            clearTimeout(timerId);
            timerId = setTimeout(() => {
                func.apply(this, args);
            }, delay);
        };
    };
    const debounceAndGetPromise = function (func, delay = 300) {
        let timerId;
        let lastPromise;

        return (...args) => {
            // Return a new promise each time the debounced function is called
            lastPromise = new Promise((resolve, reject) => {
                clearTimeout(timerId);
                timerId = setTimeout(() => {
                    try {
                        // Call the function and handle its result
                        const result = func.apply(this, args);
                        // Wrap result in a promise if it's not already one
                        Promise.resolve(result).then(resolve).catch(reject);
                    } catch (error) {
                        reject(error);
                    }
                }, delay);
            });

            // Return the last created promise
            return lastPromise;
        };
    };
    isPositiveInteger = function (text) {
        return text >>> 0 === parseFloat(text);
    }

    getCurrentLangCode = function (text) {
        return window.location.pathname.split('/')[1] || "";
    }

    $.fn.FlexCookiesStatement = function () {
        this.each(function () {
            var element = $(this);

            if (window.localStorage.getItem('CookiesStatementConfirmed') != 'true') {
                element.slideDown({ duration: 600 });

                element.find('input[type="button"]').on('click', function (e) {
                    window.localStorage.setItem('CookiesStatementConfirmed', 'true');
                    element.slideUp({ duration: 400 });
                });
            }
        });
    };

    jQuery.expr[':'].containsInsensitive = function (a, i, m) {
        return jQuery(a).text().toUpperCase()
            .indexOf(m[3].toUpperCase()) >= 0;
    };

    let attributeHash = [];

    $.fn.FlexAttributeLoad = function () {
        attributeHash = [];
        this.each(function () {
            if ($(this).hasClass("flex-selected")) {
                attributeHash.push(
                    $(this).attr("id")
                );
            }
        });

        setTimeout(function () {
            sessionStorage.setItem("attributeHash", attributeHash);
        }, 2)
    }

    $.fn.FlexDropDown = function () {
        this.each(function () {
            $(this).css('display', 'none');

            var elementId = $(this).attr('id'); // ID of element we are currently work with.
            var disabled = $(this).is(':disabled');
            var selected = $(this).find('option[selected]'); // Determines if some option is selected.
            var options = $('option', $(this)); // Contains list of options.
            var cssClass = $(this).attr('class');
            var isIconsVisible = $(this).attr('data-show-icons') === 'true';
            var watermarkText = $(this).attr('data-flex-watermark-text');
            var isSearchEnabled = $(this).attr('data-flex-search-enabled') === 'true';
            var appendedTitleText = $(this).attr('data-appended-title-text');
            var titleText = $(this).attr('data-flex-title-text');

            $('#' + elementId).attr('data-flex', 'true');

            if (disabled) {
                $('#' + elementId).after('<dl id="' + elementId + '_FlexDropDown" class="' + cssClass + ' flex-disabled" data-flex="true"></dl>');
            } else {
                $('#' + elementId).after('<dl id="' + elementId + '_FlexDropDown" class="' + cssClass + '" data-flex="true"></dl>');
            }

            // Option element's attribute for is set to ID of dl element 
            $(this).attr('for', elementId + '_FlexDropDown');

            if (watermarkText && !selected.val()) {
                $('#' + elementId + '_FlexDropDown').append('<dt><span class="flex-drop-down-link" data-value="-1">' + watermarkText + '<span class="flex-drop-down-value">-1</span></span></dt>');
            } else {
                var itemsCount = selected.attr("data-flex-items-count");
                var additionalText = selected.attr('data-flex-additional-text');
                var titleText = selected.attr('data-flex-title-text');
                // var showTitleText = titleText != undefined;

                var optionHtml = '<dt><span class="flex-drop-down-link selected" data-value="' + selected.val() + '">' + (isIconsVisible ? '<div class="flag" style="background-image: url(/Plugins/FlexView/Images/Flags/' + selected.attr('data-icon') + '.png);"></div>' : '') + '<span class="flex-text">' + selected.text() + (appendedTitleText != undefined ? ' ' + appendedTitleText : '') + '</span>';

                if (titleText != undefined)
                    optionHtml += '<span class="flex-title-text">' + titleText + '</span>';
                //if (itemsCount != undefined)
                //    optionHtml += '<span class="flex-drop-down-items-count">' + itemsCount + '</span>';

                if (additionalText != undefined)
                    optionHtml += '<span class="flex-additional-text">' + additionalText + '</span>';

                optionHtml += '<span class="flex-drop-down-value">' + selected.val() + '</span></span></dt>';

                $('#' + elementId + '_FlexDropDown').append(optionHtml);
            }

            $('#' + elementId + '_FlexDropDown').append('<dd><div class="flex-collapsible" translate="no"><ul></ul></div></dd>');

            if (isSearchEnabled) {
                var searchHtml = '<div class="flex-drop-down-search"><input type="text" /><input type="button" /></div>';
                $('#' + elementId + '_FlexDropDown dd .flex-collapsible').prepend(searchHtml);
            }

            options.each(function () {
                var itemsCount = $(this).attr("data-flex-items-count");
                var additionalText = $(this).attr('data-flex-additional-text');
                var titleText = $(this).attr('data-flex-title-text');


                var optionHtml = '<li><span class="flex-drop-down-link ' + ($(this).attr("data-flex-item-favourite") == 1 ? 'flex-drop-down-link-favourite' : '') + '" data-value="' + $(this).val() + '">' + (isIconsVisible ? '<div class="flag" style="background-image: url(/Plugins/FlexView/Images/Flags/' + $(this).attr('data-icon') + '.png);"></div>' : '') + '<span class="flex-text">' + $(this).text() + '</span>';

                if (itemsCount != undefined)
                    optionHtml += '<span class="flex-drop-down-items-count">' + itemsCount + '</span>';

                if (additionalText != undefined)
                    optionHtml += '<span class="flex-additional-text">' + additionalText + '</span>';

                if (titleText != undefined)
                    optionHtml += '<span class="flex-title-text">' + titleText + '</span>';

                optionHtml += '<span class="flex-drop-down-value">' + $(this).val() + '</span></span></li>';

                $('#' + elementId + '_FlexDropDown dd .flex-collapsible ul').append(optionHtml);
            });

            if (!disabled) {
                $('#' + elementId + '_FlexDropDown dd ul li .flex-drop-down-link').click(function (event) {
                    event.stopPropagation();

                    var arg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1;

                    var text = $(this).html() + (appendedTitleText != undefined ? ' ' + appendedTitleText : '');
                    $('#' + elementId + '_FlexDropDown dt .flex-drop-down-link').html(text);
                    $('#' + elementId + '_FlexDropDown dd .flex-collapsible').hide(0);
                    $('#' + elementId).val($(this).find('span.flex-drop-down-value').html());
                    $('#' + elementId).trigger('change', arg);

                    var value = $('#' + elementId + '_FlexDropDown dt .flex-drop-down-link.selected .flex-drop-down-value').text();
                    $('#' + elementId + '_FlexDropDown dt .flex-drop-down-link.selected').attr("data-value", value);
                });

                $('#' + elementId + '_FlexDropDown dt .flex-drop-down-link').click(function (event) {

                    if ($(this).parents().hasClass("flex-transport-methods-container"))
                        event.stopPropagation();

                    var isOpened = $('#' + elementId + '_FlexDropDown dd .flex-collapsible').is(':visible');

                    $('.flex-drop-down dd .flex-collapsible').slideUp({ duration: 400, easing: 'easeInBack' });

                    if (!isOpened) {
                        $('#' + elementId + '_FlexDropDown dd .flex-collapsible').slideDown({ duration: 600, easing: 'easeOutExpo' });

                        layer++;
                        $('#' + elementId + '_FlexDropDown dd .flex-collapsible').css('z-index', layer);

                        if (isSearchEnabled) {
                            $('#' + elementId + '_FlexDropDown dd .flex-collapsible .flex-drop-down-search input[type="text"]').focus();
                        }
                    }
                });

                $('#' + elementId + '_FlexDropDown dd .flex-collapsible .flex-drop-down-search input[type="text"]').keyup(function (event) {
                    if (isKeyPrintable(event.which)) {
                        $('#' + elementId + '_FlexDropDown dd .flex-collapsible ul li').removeClass('flex-selected');

                        var searchText = $('#' + elementId + '_FlexDropDown dd .flex-collapsible .flex-drop-down-search input[type="text"]').val().toLowerCase();

                        // Pokud se jedná o ManufacturerSelector_FlexDropDown tak odstraníme háčky a čárky
                        var el = $(event.target).parent().parent().parent().parent()[0].id;
                        if (el == "ManufacturerSelector_FlexDropDown") {
                            searchText = searchText.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
                        }

                        $('#' + elementId + '_FlexDropDown dd ul li').each(function (index) {
                            var text = $(this).find('.flex-drop-down-link .flex-text').text().toLowerCase() + ' ' + $(this).find('.flex-drop-down-link .flex-additional-text').text().toLowerCase()

                            if (text.indexOf(searchText) > -1) {
                                $(this).show();
                            } else {
                                $(this).hide();
                            }
                        });
                    }
                });

                $('#' + elementId + '_FlexDropDown dd .flex-collapsible .flex-drop-down-search input[type="text"]').on('keydown', function (e) {
                    var selectedItem = $('#' + elementId + '_FlexDropDown dd .flex-collapsible ul li.flex-selected:visible');

                    if (e.which === 38) {
                        e.preventDefault();

                        if (selectedItem.length > 0) {
                            selectedItem.removeClass('flex-selected');

                            var nextItem = selectedItem.prevAll("li:visible").first();

                            if (nextItem.length > 0) {
                                nextItem.addClass('flex-selected');

                            } else {
                                selectedItem = $('#' + elementId + '_FlexDropDown dd .flex-collapsible ul li:visible').last().addClass('flex-selected');
                            }
                        } else {
                            selectedItem = $('#' + elementId + '_FlexDropDown dd .flex-collapsible ul li:visible').last().addClass('flex-selected');
                        }

                        var list = $('#' + elementId + '_FlexDropDown dd .flex-collapsible ul li:visible');
                        var li = $('#' + elementId + '_FlexDropDown dd .flex-collapsible ul li.flex-selected');
                        var container = $('#' + elementId + '_FlexDropDown dd .flex-collapsible ul');

                        if (((li.outerHeight() * list.index(li)) < container.scrollTop()) || ((container.scrollTop() + container.innerHeight() - parseInt(container.css("paddingTop"))) < (li.outerHeight() * list.index(li)))) {
                            container.scrollTop(li.outerHeight() * list.index(li));
                        }

                    } else if (e.which === 40) {
                        e.preventDefault();

                        if (selectedItem.length > 0) {
                            selectedItem.removeClass('flex-selected');

                            var nextItem = selectedItem.nextAll("li:visible").first();

                            if (nextItem.length > 0) {
                                nextItem.addClass('flex-selected');
                                nextItem.focus();
                            } else {
                                selectedItem = $('#' + elementId + '_FlexDropDown dd .flex-collapsible ul li:visible').eq(0).addClass('flex-selected');
                                selectedItem.focus();
                            }
                        } else {
                            selectedItem = $('#' + elementId + '_FlexDropDown dd .flex-collapsible ul li:visible').eq(0).addClass('flex-selected');
                            selectedItem.focusin();
                        }

                        var list = $('#' + elementId + '_FlexDropDown dd .flex-collapsible ul li:visible');
                        var li = $('#' + elementId + '_FlexDropDown dd .flex-collapsible ul li.flex-selected');
                        var container = $('#' + elementId + '_FlexDropDown dd .flex-collapsible ul');

                        if ((li.outerHeight() * list.index(li) + li.outerHeight()) > (container.scrollTop() + container.innerHeight() - parseInt(container.css("paddingTop"))) || (li.outerHeight() * list.index(li) + li.outerHeight()) < container.scrollTop()) {
                            container.scrollTop(li.outerHeight() * list.index(li) - container.innerHeight() + li.outerHeight() + parseInt(container.css("paddingTop")));
                        }

                    } else if (e.which === 13) {
                        e.preventDefault();

                        selectedItem = $('#' + elementId + '_FlexDropDown dd .flex-collapsible ul li.flex-selected');

                        if (selectedItem.length > 0) {
                            selectedItem.find('.flex-drop-down-link').click();
                        }
                    }
                });

                //Hover list
                $('#' + elementId + '_FlexDropDown dd .flex-collapsible ul li').on('mousemove', function () {
                    $('#' + elementId + '_FlexDropDown dd .flex-collapsible ul li').removeClass('flex-selected');
                    $(this).addClass('flex-selected');
                });

                //Search input click
                $('#' + elementId + '_FlexDropDown dd .flex-collapsible .flex-drop-down-search input[type="button"]').click(function (event) {
                    $('#' + elementId + '_FlexDropDown dd .flex-collapsible ul li').removeClass('flex-selected');

                    $('#' + elementId + '_FlexDropDown dd ul li').each(function (index) {
                        var searchText = $('#' + elementId + '_FlexDropDown dd .flex-collapsible .flex-drop-down-search input[type="text"]').val().toLowerCase();

                        if ($(this).find('.flex-drop-down-link .flex-text').text().toLowerCase().indexOf(searchText) > -1) {
                            $(this).slideDown({ duration: 400 });
                        } else {
                            $(this).slideUp({ duration: 400 });
                        }
                    });
                });
            }
        });

        $(document).bind('click', function (e) {
            var clicked = $(e.target);
            if (!clicked.parents().hasClass("flex-drop-down")) {
                $('.flex-drop-down dd .flex-collapsible').slideUp({ duration: 400, easing: 'easeInBack' });
            }
        });
    };

    $.fn.FlexCheckbox = function () {
        this.each(function () {
            var elementId = $(this).prop('id');
            var checked = $(this).is(':checked');
            var disabled = $(this).is(':disabled');
            var toogleText = $(this).attr('data-flex-toogle-text');
            var systemClass = $(this).attr('data-system-class');
            //var falseText = $(this).attr('data-flex-false-text');
            //var trueText = $(this).attr('data-flex-true-text');
            var keyText = $(this).attr('data-flex-key-text');

            $('#' + elementId).attr('data-flex', 'true');

            var html = '';

            /*if (falseText !== undefined)
                html += '<span id="' + elementId + '_FlexCheckboxFalseText" class="flex-checkbox-false-text">' + falseText + '</span>';*/

            if (disabled || elementId !== "PurchasePricePriorized") {
                html += '<div id="' + elementId + '_FlexCheckbox" class="flex-checkbox flex-disabled display-none" data-flex-key-text="' + keyText + '"  data-flex="true"></div>';
            } else {
                html += '<div id="' + elementId + '_FlexCheckbox" class="flex-checkbox" data-flex-key-text="' + keyText + '"  data-flex="true"></div>';
            }

            /*if (trueText !== undefined) {
                html += '<span id="' + elementId + '_FlexCheckboxTrueText" class="flex-checkbox-true-text">' + trueText + '</span>';
            }*/

            if (toogleText !== undefined) {
                let isCountZero = $(this).attr("data-flex-params-count");
                let disabledClass = "flex-disabled-checkbox";
                if (isCountZero == null || isCountZero > 0) {
                    disabledClass = "";
                }
                html += '<span id="' + elementId + '_FlexCheckboxToogleText" class="flex-checkbox-toogle-text  ' + systemClass + ' ' + disabledClass + '">' + toogleText + '</span>';
            }

            let currentElement = $(this);

            if (currentElement.attr("data-flex-put-before") == "true") {
                $(currentElement.parent()).after(html);
            } else {
                currentElement.after(html);
            }


            if (checked)
                $('#' + elementId + '_FlexCheckbox').addClass('flex-selected');

            $('#' + elementId + '_FlexCheckbox').click(function () {
                if (!disabled) {
                    if ($('#' + elementId + '_FlexCheckbox').hasClass('flex-selected')) {
                        $('#' + elementId + '_FlexCheckbox').removeClass('flex-selected');
                        $('#' + elementId).prop('checked', false);
                    }
                    else {
                        $('#' + elementId + '_FlexCheckbox').addClass('flex-selected');
                        $('#' + elementId).prop('checked', true);
                    }

                    $('#' + elementId).change();
                }
            });

            $('#' + elementId).change(function () {
                if ($('#' + elementId).prop('checked'))
                    $('#' + elementId + '_FlexCheckbox').addClass('flex-selected');
                else
                    $('#' + elementId + '_FlexCheckbox').removeClass('flex-selected');
            });

            $('#' + elementId + '_FlexCheckboxFalseText').click(function () {
                if ($('#' + elementId + '_FlexCheckbox').hasClass('flex-selected')) {
                    $('#' + elementId + '_FlexCheckbox').removeClass('flex-selected');
                    $('#' + elementId).prop('checked', false);

                    $('#' + elementId).change();
                }
            });

            $('#' + elementId + '_FlexCheckboxTrueText').click(function () {
                if (!$('#' + elementId + '_FlexCheckbox').hasClass('flex-selected')) {
                    $('#' + elementId + '_FlexCheckbox').addClass('flex-selected');
                    $('#' + elementId).prop('checked', true);

                    $('#' + elementId).change();
                }
            });

            $('#' + elementId + '_FlexCheckboxToogleText').click(function () {
                if (!disabled) {
                    if ($('#' + elementId + '_FlexCheckbox').hasClass('flex-selected')) {
                        $('#' + elementId + '_FlexCheckbox').removeClass('flex-selected');
                        $('#' + elementId).prop('checked', false);
                    }
                    else {
                        $('#' + elementId + '_FlexCheckbox').addClass('flex-selected');
                        $('#' + elementId).prop('checked', true);
                    }

                    $('#' + elementId).change();
                }
            });
        });
    };

    $.fn.FlexRangeSlider = function () {
        this.each(function () {
            var element = $(this);
            var values = element.attr('data-flex-values');

            element.attr('data-flex', 'true');

            var snapSlider = document.getElementById(element.attr('ID'));

            var valuePairs = {};

            var valueArray = values.split(';');

            var minValue = parseFloat(valueArray[0].replace(',', '.'));
            var maxValue = parseFloat(valueArray[valueArray.length - 1].replace(',', '.'));

            var startValue = minValue;
            var stopValue = maxValue;

            if (element.attr('data-flex-start-value')) {
                startValue = parseFloat(element.attr('data-flex-start-value').replace(',', '.'))
            }

            if (element.attr('data-flex-stop-value')) {
                stopValue = parseFloat(element.attr('data-flex-stop-value').replace(',', '.'))
            }

            var stepSize = 100.0 / (valueArray.length - 1);

            valuePairs["min"] = minValue;

            var currentStepSize = 0.0;

            for (var i = 1, len = valueArray.length; i < len - 1; i++) {

                var percentage = (parseFloat(valueArray[i].replace(',', '.')) - parseFloat(minValue)) / (parseFloat(maxValue) - parseFloat(minValue)) * 100.0;

                currentStepSize += stepSize;

                //valuePairs[percentage + '%'] = parseFloat(valueArray[i].replace(',', '.'));
                valuePairs[currentStepSize + '%'] = parseFloat(valueArray[i].replace(',', '.'));
            }

            valuePairs["max"] = maxValue;

            noUiSlider.create(snapSlider, {
                start: [startValue, stopValue],
                snap: (element.attr('data-flex-snap') == 'true'),
                connect: (element.attr('data-flex-connect') == 'true'),
                range: valuePairs,
                format: {
                    to: function (value) {
                        return value;
                    },
                    from: function (value) {
                        return Number(value);
                    }
                }
            });

            snapSlider.noUiSlider.on('update', function (values, handle) {
                $('#FlexRangeSliderFromRange_' + element.attr('data-flex-generic-article-key') + '_' + element.attr('data-flex-attribute-key')).html(values[0]);
                $('#FlexRangeSliderToRange_' + element.attr('data-flex-generic-article-key') + '_' + element.attr('data-flex-attribute-key')).html(values[1]);
            });

            snapSlider.noUiSlider.on("set", function () {
                let values = snapSlider.noUiSlider.get();
                if (values[0] == startValue && values[1] == stopValue) {
                    return;
                }

                let button = $("#flex-filtrate");

                if (button.length === 0) {
                    return;
                }
                if (element.attr("data-flex-instant-filter") === "false") {
                    button.show();
                    return;
                }

                button.click();
            });
        });
    };

    $.fn.FlexFileUpload = function () {
        this.each(function () {
            var element = $(this);
            var elementId = element.attr('id');
            var browseText = element.attr('data-flex-browse-text');
            var notSelectedText = element.attr('data-flex-not-selected-text');

            element.attr('data-flex', 'true');

            element.after('<div id="' + elementId + '_FlexFileUpload" class="flex-file-upload" data-flex="true"><input type="button" value="' + browseText + '" /><span>' + notSelectedText + '</span></div>');

            $('#' + elementId + '_FlexFileUpload input[type="button"]').click(function () {
                element.click();
            });

            element.change(function () {
                $('#' + elementId + '_FlexFileUpload span').html(element.val().replace(/^.*[\\\/]/, ''));
            });
        });
    };

    $.fn.OneClickSelectable = function () {
        this.each(function () {
            var element = $(this);
            var selected = false;

            element.attr('data-flex', 'true');

            element.click(function () {
                if (selected == false) {
                    element.focus();
                    element.select();
                    selected = true;
                }
            });

            element.focusout(function () {
                selected = false;
            });
        });
    };

    $.fn.FlexRadioButtons = function () {
        this.each(function () {
            var element = $(this);
            var elementId = $(this).attr('id');

            $('#' + elementId).attr('data-flex', 'true');

            element.after('<ul id="' + elementId + '_FlexRadioButtons" class="flex-radio-buttons"></ul>');

            element.find('input[type="radio"]').each(function () {
                var checked = $(this).is(':checked');
                var disabled = $(this).is(':disabled');

                var fontAwesomeIcon = $(this).attr('data-flex-font-awesome-icon-class');
                var urlIcon = $(this).attr('data-flex-icon-url');
                var additionalText = $(this).attr('data-flex-additional-text');
                let currentElementContent = [];
                let idAttr = $(this).attr('id');
                let dataTextAttr = $(this).attr('data-text');

                var cssClass = (checked ? 'flex-selected' : '') + (disabled ? ' flex-disabled' : '')

                currentElementContent.push('<li data-target-input-id="' + idAttr + '" class="' + cssClass + '">');
                currentElementContent.push(`<div class="flex-transport-method-item">`)
                currentElementContent.push(`<div class="flex-radio"></div>`);

                if (fontAwesomeIcon) {
                    currentElementContent.push(`<i class="${fontAwesomeIcon}"></i>`)
                }

                if (urlIcon) {
                    currentElementContent.push(`<img src="'${urlIcon}'" />`)
                }

                currentElementContent.push(`<div class="flex-text-wrapper">`);
                currentElementContent.push(`<span>${dataTextAttr}</span></div>`)

                if (additionalText) {
                    currentElementContent.push(`<span class="flex-additional-text">${additionalText}</span>`)
                }

                currentElementContent.push(`</li>`)

                $('#' + elementId + '_FlexRadioButtons').append(currentElementContent.join(" "));
            });


            $('#' + elementId + '_FlexRadioButtons li').click(function () {
                var isDisabled = $(this).hasClass('flex-disabled');
                if (!isDisabled) {
                    $('#' + elementId + '_FlexRadioButtons li').removeClass('flex-selected');
                    $(this).addClass('flex-selected');

                    if (elementId == 'TransportMethods') {
                        if (prevChild !== undefined) {
                            if (prevChild.length === 2) {
                                $(prevChild[1]).hide(250);
                            }

                            if (prevChild.length === 3) {
                                $(prevChild[2]).hide(250);
                            }
                        }

                        let inputId = $(this).attr("data-target-input-id");
                        let description = $("#TransportMethodDescription" + inputId.replace('TransportMethod', ''));

                        prevChild = $(this).children();
                        if (prevChild.length == 2) {
                            $(prevChild[1]).show(250);
                            $(prevChild[1]).before(description);
                        } else {
                            $(prevChild).show(250);
                            $(prevChild).after(description);
                        }
                    }

                    var $dataTarget = $('#' + $(this).attr('data-target-input-id'));
                    $dataTarget.parent().find("input").removeAttr('checked');
                    $dataTarget.attr('checked', 'checked');
                    $dataTarget.prop('checked', true);
                    $dataTarget.change();
                }
            });
        });
    };

    var prevChild = undefined;

    $.fn.FlexCatalogMenu = function () {
        
        
        this.each(function () {
            var element = $(this);
            if (element.parents().hasClass('flex-main-menu')) {

                if (isSmallScreen()) {
                    element.children('ul').addClass('flex-menu-compact');
                    element.children('ul').hide(0);
                    element.children('.flex-menu-button').show(0);
                } else {
                    element.children('.flex-menu-button').hide(0);
                    element.children('ul').show(0);
                    element.children('ul').removeClass('flex-menu-compact');
                }
            }

            $(window).on('resize', function () {
                if (element.parents().hasClass('flex-main-menu')) {
                    if (isSmallScreen()) {
                        element.children('ul').addClass('flex-menu-compact');
                        element.children('.flex-menu-button').show(0);
                    } else {
                        element.children('.flex-menu-button').hide(0);
                        element.children('ul').show(0);
                        element.children('ul').removeClass('flex-menu-compact');
                    }
                }
            });

            $(this).find('.flex-menu-button').click(function () {
                element.children('.flex-close-menu-button').toggleClass('selected');
                element.children('ul').slideToggle(600, 'easeOutBounce');
            });
            $(this).find('.flex-close-menu-button').click(function () {
                element.children('.flex-close-menu-button').toggleClass('selected');
                element.children('ul').slideToggle(600, 'easeOutBounce');
            });

            $('.flex-main-menu .flex-menu a').each(function () {
                var url = location.pathname.substring(0, $(this).attr('href').length);
                var menuItemUrlParams = new URLSearchParams($(this).attr('href').split('?')[1]);

                if ($(this).attr('href') == url || app.getUrlParameter("root") == menuItemUrlParams.get('root')) {
                    $(this).addClass('flex-selected');

                    if ($(this).parent().parent().hasClass('flex-menu-has-children')) {
                        if ($(this).parents('flex-menu-compact').length > 0) {
                            $(this).parent().parent().parent().children('span').addClass('flex-selected');
                        }
                    }
                }
            });

            $(this).find('.flex-menu-has-children').each(function () {

                $(this).css("top", $('.flex-main-menu .flex-menu ul li').height() + "px");

            });

            $(this).find('.flex-menu-has-children').prev().on("click", function () {
                $(this).next().slideToggle(600, 'easeOutExpo', function () { });
                $(this).toggleClass('flex-selected');
                $(this).parent().toggleClass('flex-selected');
            });

            $(document).bind('click', function (e) {
                var clicked = $(e.target);
                if (!clicked.parents().hasClass('flex-main-menu')) {
                    $('.flex-main-menu .flex-menu ul li ul').slideUp(400, 'easeInBack', function () {
                        $(this).prev().removeClass('flex-selected');
                        $('.flex-main-menu .flex-menu ul li').each(function () {
                            $(this).removeClass('flex-selected');
                            $(this).parent().removeClass('flex-selected');
                        });
                    });
                    $('.flex-main-menu .flex-menu ul.flex-menu-compact').slideUp(400, 'easeInBack', function () {
                        $(this).prev().removeClass('flex-selected');
                        $('.flex-main-menu .flex-menu ul li').each(function () {
                            $(this).removeClass('flex-selected');
                            $(this).parent().removeClass('flex-selected');
                        });
                    });

                    $('.flex-main-menu .flex-close-menu-button').removeClass('selected');
                }
            });


        });


    }


    $.fn.FlexMenu = function () {
        this.each(function () {

            var element = $(this);
            var isSelectionPermanent = element.attr("data-flex-permanent-selection");

            if (element.parents().hasClass('flex-top-panel-container') && !isSmallScreen()) {
                var containerWidth = element.parents('.flex-top-panel-container').innerWidth();
                var contentWidth = 0;

                element.parents('.flex-top-panel-container').children().each(function () {
                    if (!$(this).hasClass('flex-menu')) {
                        contentWidth += parseInt($(this).outerWidth());
                    }
                });

                if (containerWidth < contentWidth) {
                    element.children('.flex-expand-menu-button').css('display', 'inline-block');
                    var maxMenuWidth = (element.find('ul').outerWidth() - (contentWidth - containerWidth)) - element.children('.flex-expand-menu-button').outerWidth() - 1;

                    var userOwnerPhoneWidth = $(".flex-top-panel-container div.user-owner-contact").outerWidth();
                    if (userOwnerPhoneWidth > 0) {
                        maxMenuWidth -= userOwnerPhoneWidth;
                    }

                    var linkToOldVersionWidth = $(".flex-top-panel-container a.flex-redirect-to-older-version-button").outerWidth();
                    if (linkToOldVersionWidth > 0) {
                        maxMenuWidth += linkToOldVersionWidth;
                    }

                    element.find('ul').css('max-width', maxMenuWidth + 'px');

                    var menuItemsWidth = 0;
                    var showCollapseButton = false;

                    element.children('ul').children('li').each(function (index, element) {
                        menuItemsWidth += parseInt($(this).outerWidth());
                        if (menuItemsWidth >= maxMenuWidth) {
                            $(this).addClass('flex-collapsed');
                            showCollapseButton = true;
                        }
                    });

                    if (showCollapseButton) {
                        var $menu = $("div.flex-container.flex-top-panel-container div.flex-menu").find("ul");
                        $menu.append('<li><span class=\"flex-expand-menu-button\" style=\"background: transparent; padding: 0;\"><i class=\"fas fa-angle-down\"></i></span></li>');
                        $("input.flex-expand-menu-button").show();
                    }
                }
            }

            $(this).find('.flex-expand-menu-button').bind('click', function (e) {
                $(this).closest('ul').toggleClass('flex-expanded');
                $(this).children('i').toggleClass('fa-angle-up');
            });

            $(this).find('ul li a').bind('click', function (e) {
                if ($(this).attr('target') == '_blank') {
                    window.open($(this).attr('href'), '_blank');
                } else {
                    window.location.href = $(this).attr('href');
                }

                return false;
            });

            $(this).find('ul li').bind('click', function (e) {
                $('.flex-menu ul li').each(function () {
                    $(this).removeClass('flex-selected');
                    $(this).find('ul').hide(0);
                });

                var clicked = $(e.target);
                if (!clicked.parents().hasClass("flex-menu-compact")) {
                    $('.flex-menu ul.flex-menu-compact').hide(0);
                }

                if (isSelectionPermanent == 'true') {
                    $(this).addClass('flex-selected-permanent');
                } else {
                    $(this).addClass('flex-selected');
                }

                if ($(this).find('ul li a').length > 1) {
                    $(this).find('ul').slideDown({ duration: 600, easing: 'easeOutExpo' });
                } else {
                    $(this).find('ul li a').click();
                }

                layer++;

                $(this).find('ul').css('z-index', layer);

                layer++;

                $(this).find('span').css('z-index', layer);
            });

            $(this).find('.flex-menu-button').click(function () {
                element.children('.flex-close-menu-button').fadeIn(600);
                element.children('ul').slideDown(600, 'easeOutExpo', function () {
                    $('.flex-menu ul li').each(function () {
                        $(this).removeClass('flex-selected');
                        $(this).find('ul').hide(0);
                    });
                });
            });

            $(this).find('.flex-close-menu-button').click(function () {
                $(this).fadeOut(400);
                $('.flex-menu ul.flex-menu-compact').slideUp(400, 'easeInBack', function () {
                    $('.flex-menu ul li').each(function () {
                        $(this).removeClass('flex-selected');
                    });
                });
            });

            var isFirstLoad = true;
            var screedWidth = $(window).width();

            $(window).on('resize', function () {
                if ($(window).width() == screedWidth && !isFirstLoad)
                    return;

                if (element.parents().hasClass('flex-panel-wide') && element.parents().hasClass('flex-container')) {
                    if (isSmallScreen()) {
                        element.children('ul').addClass('flex-menu-compact');
                        element.children('ul').hide(0);
                        element.children('.flex-menu-button').show(0);
                    } else {
                        element.children('.flex-menu-button').hide(0);
                        element.children('.flex-close-menu-button').hide();
                        element.children('ul').show(0);
                        element.children('ul').removeClass('flex-menu-compact');
                    }
                }
            });

            $(window).trigger('resize');
            isFirstLoad = false;
        });

        $(document).bind('click', function (e) {
            var clicked = $(e.target);
            if (!clicked.parents().hasClass("flex-menu")) {
                $('.flex-top-panel-container .flex-menu .flex-close-menu-button').fadeOut(400);
                $('.flex-top-panel-container .flex-menu ul li ul').slideUp(400, 'easeInBack', function () {
                    $('.flex-top-panel-container .flex-menu ul li').each(function () {
                        $(this).removeClass('flex-selected');
                    });
                });
                $('.flex-top-panel-container .flex-menu ul.flex-menu-compact').slideUp(400, 'easeInBack', function () {
                    $('.flex-top-panel-container .flex-menu ul li').each(function () {
                        $(this).removeClass('flex-selected');
                    });
                });
            }
        });
    };

    $.fn.FlexTabs = function () {
        this.each(function () {
            var element = $(this);

            var isFirstTabExpanded = element.attr("data-flex-expand-first");

            if (isFirstTabExpanded == 'true' && !element.find('.flex-header .flex-tab').first().hasClass('flex-selected'))
                element.find('.flex-header .flex-tab')[0].click();
        });
    };

    $.fn.FlexHalfCollapsedBox = function () {
        var element = $(this);

        markRow = function (element) {
            element.each(function () {
                var top;
                $(this).find('.flex-item').each(function (i) {
                    var thisTop = $(this).offset().top

                    if (i == 0) {
                        top = thisTop;
                    }
                    if (top == thisTop || top == thisTop - $(this).css("marginTop").replace('px', '')) {
                        $(this).addClass('flex-first-row');
                    } else {
                        $(this).removeClass('flex-first-row');
                    }
                });
            });
        }

        getCollapsedHeight = function (element) {
            var maxHeight = 0;

            element.find('.flex-inner-wrapper .flex-first-row').each(function () {
                if (maxHeight < $(this).height()) {
                    maxHeight = $(this).height();
                }
            });

            return maxHeight;
        }

        markRow(element);

        element.each(function () {

            element.find('.flex-inner-wrapper').height(getCollapsedHeight($(this)));
            element.find('img').on('load', function () {
                element.find('.flex-inner-wrapper').height(getCollapsedHeight(element));
            }).each(function () {
                if (this.complete) $(this).trigger('load');
            });
        });

        $(window).on('resize', function () {
            markRow(element);

            element.each(function () {

                if ($(this).find(".flex-show-all-button").css('display') != 'none') {
                    $(this).find('.flex-inner-wrapper').height(getCollapsedHeight($(this)));
                } else {
                    var newHeight = 0;

                    $(this).find('.flex-inner-wrapper').height(getCollapsedHeight($(this)));
                    newHeight = $(this).parents().find('.flex-inner-wrapper').get(0).scrollHeight;

                    $(this).find('.flex-inner-wrapper').height(newHeight);
                }
            });

        });

        $(".flex-show-all-button").click(function () {
            $(this).hide(0);
            $(this).parent('.flex-half-collapsed-box').find('.flex-collapse-button').show(0);

            $(this).parent('.flex-half-collapsed-box').find('.flex-inner-wrapper').animate({
                height: $(this).parent('.flex-half-collapsed-box').find('.flex-inner-wrapper').get(0).scrollHeight
            }, 1000, 'easeOutExpo');
        });

        $(".flex-collapse-button").click(function () {
            $(this).hide(0);
            $(this).parent('.flex-half-collapsed-box').find('.flex-show-all-button').show(0);

            $(this).parent('.flex-half-collapsed-box').find('.flex-inner-wrapper').animate({
                height: getCollapsedHeight($(this).parent('.flex-half-collapsed-box'))
            }, 400, 'easeInBack');
        });
    };

    $.fn.FlexCollapsibleAttributes = function () {
        this.each(function () {
            var element = $(this);

            if (!element.parents().hasClass('compare-tile-view')) {
                if (element.text().trim().length > 0) {
                    element.attr('data-flex', 'true');
                }

                if ($(this).find('.flex-toogle-collapse-button').length) {

                    var expandedHeight = element.find('.flex-wrapper').height();

                    var collapsedHeight = 0;
                    for (var i = 0; i < 5; i++) {
                        collapsedHeight += $(this).find('table tr').eq(i).outerHeight();
                    }

                    $(this).find('.flex-wrapper').css('max-height', collapsedHeight + 'px');

                    $(this).find('.flex-toogle-collapse-button').click(function () {

                        if (element.attr("data-flex-expanded") == "true") {
                            element.find('.flex-wrapper').animate({ maxHeight: collapsedHeight }, 300);
                            element.attr('data-flex-expanded', 'false');
                        } else {
                            element.find('.flex-wrapper').animate({ maxHeight: expandedHeight }, 300);
                            element.attr('data-flex-expanded', 'true');
                        }

                        return false;
                    });
                }
            } else {
                $('.flex-toogle-collapse-button').remove();
            }
        });
    };

    $.fn.FlexCollapsibleDeliveryTimes = function () {
        this.each(function () {
            var element = $(this);

            if (element.text().trim().length > 0) {
                element.attr('data-flex', 'true');
            }

            if ($(this).find('.toogle-collapse-button').length) {

                var expandedItemsCount = $('.products-list').attr('data-flex-directly-visible-delivery-times');

                if (expandedItemsCount == undefined) {
                    expandedItemsCount = $('.flex-delivery-times').attr('data-flex-directly-visible-delivery-times');
                }

                var collapsedHeight = 0;
                for (var i = 0; i < parseInt(expandedItemsCount); i++) {
                    collapsedHeight += $(this).find('.flex-delivery-time-item').eq(i).outerHeight();
                    collapsedHeight += parseInt($(this).find('.flex-delivery-time-item').eq(i).css('marginTop'));
                    collapsedHeight += parseInt($(this).find('.flex-delivery-time-item').eq(i).css('marginBottom'));
                }

                $(this).find('.wrapper').css('overflow', 'hidden');
                $(this).find('.wrapper').css('max-height', collapsedHeight + 'px');

                $(this).find('.toogle-collapse-button').unbind("click");

                $(this).find('.toogle-collapse-button').click(function () {
                    if (element.attr("data-expanded") == "true") {
                        var collapsedText = $(this).attr('data-collapsed-text');
                        $(this).find('.text').html(collapsedText);

                        element.find('.wrapper').animate({ maxHeight: collapsedHeight }, 300);
                        element.attr('data-expanded', 'false');

                        $(this).find('.info').show();
                    } else {
                        var expandedText = $(this).attr('data-expanded-text');
                        $(this).find('.text').html(expandedText);

                        element.find('.wrapper').animate({ maxHeight: 99999 }, 300);
                        element.attr('data-expanded', 'true');

                        $(this).find('.info').hide();
                    }

                    return false;
                });
            }
        });
    };


    $.fn.FlexCollapseDeliveryBoxInitialState = function () {
        this.each(function () {
            let element = $(this);

            element.attr("data-flex", 'false');
            element.attr("data-expanded", 'false');
        });
    }



    $.fn.FlexSlider = function () {

        var currentSlide = 1;

        slideToLeft = function (element) {
            if ((element.find('.flex-inner-wrapper').scrollLeft() + element.find('.flex-inner-wrapper').width()) < element.find('.flex-inner-wrapper').get(0).scrollWidth && !element.find('.flex-inner-wrapper').is(':animated')) {
                element.find('.flex-inner-wrapper').stop().animate({ scrollLeft: element.find('.flex-inner-wrapper').scrollLeft() + element.find('.flex-inner-wrapper').width() }, 800);

                currentSlide += 1;
                element.find('.bullets .item').removeClass('selected');
                element.find('.bullets .item[data-number="' + currentSlide + '"]').addClass('selected');
            }
        }

        slideToRight = function (element) {
            if (element.find('.flex-inner-wrapper').scrollLeft() > 0 && !element.find('.flex-inner-wrapper').is(':animated')) {
                element.find('.flex-inner-wrapper').stop().animate({ scrollLeft: element.find('.flex-inner-wrapper').scrollLeft() - element.find('.flex-inner-wrapper').width() }, 800);

                currentSlide -= 1;
                element.find('.bullets .item').removeClass('selected');
                element.find('.bullets .item[data-number="' + currentSlide + '"]').addClass('selected');
            }
        }

        autoSlide = function (element) {
            var intv = setInterval(function () {
                if ((element.find('.flex-inner-wrapper').scrollLeft() + element.find('.flex-inner-wrapper').width()) < element.find('.flex-inner-wrapper').get(0).scrollWidth) {
                    slideToLeft(element);
                } else {
                    element.find('.flex-inner-wrapper').stop().animate({ scrollLeft: 0 }, 800);

                    currentSlide = 1;
                    element.find('.bullets .item').removeClass('selected');
                    element.find('.bullets .item[data-number="' + currentSlide + '"]').addClass('selected');
                }
            }, 5000);

            return intv;
        }

        this.each(function () {

            var element = $(this);

            var bulletsHtml = '<div class="bullets">';

            var slidesCount = element.find('.flex-inner-wrapper > div').length;
            slidesCount += element.find('.flex-inner-wrapper > a').length;


            for (var i = 1; i <= slidesCount; i++) {
                if (i == 1) {
                    bulletsHtml += '<span class="item selected" data-number="' + i + '"></span>';
                } else {
                    bulletsHtml += '<span class="item" data-number="' + i + '"></span>';
                }
            }

            bulletsHtml += '</div>';

            element.append(bulletsHtml);

            var bullets = element.find('.bullets');

            bullets.css('marginLeft', '-' + (bullets.outerWidth() / 2) + 'px');

            element.find('img').on('load', function () {
                element.find('.flex-left-button').css('top', ((element.height() - element.find(".flex-left-button").height()) / 2) + 'px');
                element.find('.flex-right-button').css('top', ((element.height() - element.find(".flex-left-button").height()) / 2) + 'px');
                element.find('.flex-inner-wrapper').scrollLeft(0);
            }).each(function () {
                if (this.complete) $(this).trigger('load');
            });

            $(window).on('resize', function () {
                element.find('.flex-left-button').css('top', ((element.height() - element.find(".flex-left-button").height()) / 2) + 'px');
                element.find('.flex-right-button').css('top', ((element.height() - element.find(".flex-left-button").height()) / 2) + 'px');
            });

            var intv = autoSlide(element);

            element.find('.flex-left-button').click(function () {
                slideToRight(element);
            });

            element.find('.flex-right-button').click(function () {
                slideToLeft(element);
            });

            element.find('.flex-inner-wrapper').on('swipeleft', function () {
                slideToLeft(element);
            });

            element.find('.flex-inner-wrapper').on('swiperight', function () {
                slideToRight(element);
            });

            element.on('mouseenter mouseleave', function (e) {
                if (e.type == 'mouseenter') {
                    clearInterval(intv);
                } else {
                    intv = autoSlide(element);
                }
            });
        });
    };

    $.fn.FlexWatermark = function () {
        this.each(function () {
            if ($(this).val() == '') {
                $(this).val($(this).attr('data-flex-watermark'));
                $(this).addClass('flex-watermark');
            } else if ($(this).val() == $(this).attr('data-flex-watermark')) {
                $(this).addClass('flex-watermark');
            }
        });

        //$(this).on('keypress', function (e) {
        //    if ($(this).val() === $(this).attr('data-flex-watermark')) {
        //        $(this).val('');
        //        $(this).removeClass('flex-watermark');
        //    }
        //});

        $(this).focusin(function () {
            if ($(this).val() == $(this).attr('data-flex-watermark')) {
                $(this).val('');
                $(this).removeClass('flex-watermark');
            }
        });

        $(this).focusout(function () {
            if ($(this).val() == '') {
                $(this).val($(this).attr('data-flex-watermark'));
                $(this).addClass('flex-watermark');
            }
        });
    };











    $.fn.FlexSearchBar = function () {
        var enableCollapse = true;

        this.each(function () {
            var element = $(this);

            var edited = false;

            element.find('.flex-search-button').on('click', function () {

                var searchType = "-1";
                var subSearchType = "-1";

                if ($('.flex-filters').length > 0) {
                    searchType = $('.flex-search-whisperer').attr('data-search-type');
                    subSearchType = $('.flex-filters input[name=SearchByNumberType]:checked').val();
                }

                if ($('#SearchInput').val().trim() != "") {
                    showSearchLoading();
                    $(".flex-search").find('.flex-search-whisperer').slideUp({ duration: 400, easing: 'easeInBack' });
                    __searching(searchType, subSearchType, $('#SearchInput').val().trim());
                }
                else {
                    flexShowToastError($(this).attr('data-no-value-error-message'));
                }

            });

            element.find('.flex-search-locations span').on('click', function () {
                changeDefaultSearchMethod($(this).attr('data-search-type'));

                element.find('.flex-search-locations span').removeClass('flex-selected');
                $('#' + $(this).attr('id')).addClass('flex-selected');

                element.find('.flex-search-input input.flex-search-button:button').attr('onclick', '__searching(\'' + $(this).attr('data-search-type') + '\', -1,\'' + $('#SearchInput').val().trim() + '\')');
                element.find('.flex-search-input input:text').attr('placeholder', $(this).attr('data-watermark-text'));

                //if (edited === false)
                //    element.find('.flex-search-input input:text').val('');

                element.find('.flex-search-input input:text').focusout();

                element.find('.flex-search-whisperer').attr('data-search-type', $(this).attr('data-search-type'));

                $('.flex-search-input .flex-count').fadeOut({ duration: 600 });

                enableCollapse = false;
                element.find('.flex-search-input input:text').focus();
            });

            element.find('input[type="radio"][name="SearchByNumberType"]').on('change', function () {
                $('.flex-search-input .flex-count').fadeOut({ duration: 600 });
                getSearchWhispers('.flex-search-whisperer .flex-items', $('#SearchInput').val(), 1, $('input[name=SearchByNumberType]:checked').val());
            });

            element.find('input[type="text"]').on('focusin', function () {
                element.find('.flex-search-whisperer .flex-items').hide(0);

                if (element.find('.flex-search-whisperer').attr('data-search-type') == 1) {
                    element.find('.flex-search-whisperer .flex-filters').show(0);
                    element.find('.flex-search-whisperer').slideDown({ duration: 600, easing: 'easeOutExpo' });
                } else if (element.find('.flex-search-whisperer').attr('data-search-type') == 4) {
                    element.find('.flex-search-whisperer .flex-filters').hide(0);
                    element.find('.flex-search-whisperer').slideDown({ duration: 600, easing: 'easeOutExpo' });
                } else if (element.find('.flex-search-whisperer').attr('data-search-type') == 5) {
                    element.find('.flex-search-whisperer .flex-filters').hide(0);
                    element.find('.flex-search-whisperer').slideDown({ duration: 600, easing: 'easeOutExpo' });
                } else {
                    element.find('.flex-search-whisperer').slideUp({ duration: 400, easing: 'easeInBack' });
                }
            });

            element.find('input[type="text"]').on('focusout', function () {
                if (element.find('.flex-search-input input:text').val() == '')
                    edited = false;
            });

            element.find('input[type="button"].flex-history-button').on('click', function () {
                getSearchHistoryDialog('.flex-history-wrapper', true, 10);
            });

            element.find('.flex-search-input input[type="text"]').on('keypress', function (e) {
                edited = true;

                if (e.which == 13) {
                    element.find('.flex-search-input input[type="button"].flex-search-button').click();
                    return false;
                }
            });
        });

        $(document).bind('click', function (e) {
            var clicked = $(e.target);

            if (enableCollapse) {
                if (!clicked.parents().hasClass("flex-search-input")) {
                    $(".flex-search").find('.flex-search-whisperer').slideUp({ duration: 400, easing: 'easeInBack' });
                }

                if (!clicked.parents().hasClass("flex-history-wrapper") && !clicked.hasClass("flex-history-wrapper") && !clicked.hasClass("flex-show-all-button")) {
                    $(".flex-search").find('.flex-history-wrapper').slideUp({ duration: 400, easing: 'easeInBack' });
                }
            }

            enableCollapse = true;
        });
    };














    $.fn.FlexSmartSearchBar = function () {

        this.each(function () {
            var element = $(this);

            setCaretAtEnd(element.find('input[type="text"]'));

            getSmartSearchWhispers('.flex-smart-search-whisperer', $('#SmartSearchInput').val(), 0, false, false, null);

            const debouncedSmartSearchInput = debounceAndGetPromise(function () {
                return getSmartSearchWhispers('.flex-smart-search-whisperer', $('#SmartSearchInput').val(), 0, true, false, event)
            });

            element.find('.flex-smart-search-button').on('click', function () {

                let buttonElement = $(this);

                let searchRoute = buttonElement.attr('data-search-route');
                let currentLanguageRoute = buttonElement.attr('data-current-language-code');


                let smartSearchingAndSearchTypeGetting = function (selectedSearchType) {
                    let searchType = "-1";
                    let subSearchType = "-1";
                    if (selectedSearchType.hasClass("flex-code")) {
                        searchType = "1";
                        subSearchType = "9";
                    }
                    if (selectedSearchType.hasClass("flex-text")) {
                        searchType = "5";
                    }
                    if (selectedSearchType.hasClass("flex-vehicle")) {
                        searchType = "4";
                    }
                    if (selectedSearchType.hasClass("flex-vin")) {
                        searchType = "2";
                    }
                    if (selectedSearchType.hasClass("flex-kba")) {
                        searchType = "3";
                    }
                    if (selectedSearchType.hasClass("flex-code") && selectedSearchType.hasClass("flex-text")) {
                        searchType = "14";
                        subSearchType = "1";
                    }
                    smartSearching(searchType, subSearchType);
                }

                let selectedSearchType = $('.flex-smart-search-input .flex-search-targets input[type="button"].flex-target.flex-selected')

                if (selectedSearchType.length === 0){
                    debouncedSmartSearchInput().then(()=>{
                        selectedSearchType = $('.flex-smart-search-input .flex-search-targets input[type="button"].flex-target.flex-selected')
                        smartSearchingAndSearchTypeGetting(selectedSearchType);
                    })
                }
                else{
                    smartSearchingAndSearchTypeGetting(selectedSearchType);
                }

            });

            element.find('.flex-smart-search-input input[type="text"]').on('keydown', function (e) {

                var selectedItem = element.find('.flex-smart-search-whisperer .flex-items a.flex-selected');

                if (e.which === 38) {
                    e.preventDefault();

                    if (selectedItem.length > 0) {
                        selectedItem.removeClass('flex-selected');
                        var nextItem = selectedItem.prev();

                        if (!nextItem.is('a'))
                            nextItem = nextItem.prev();

                        if (nextItem.length > 0) {
                            nextItem.addClass('flex-selected');

                        } else {
                            selectedItem = element.find('.flex-smart-search-whisperer .flex-items a').last().addClass('flex-selected');
                        }
                    } else {
                        selectedItem = element.find('.flex-smart-search-whisperer .flex-items a').last().addClass('flex-selected');
                    }

                } else if (e.which === 40) {
                    e.preventDefault();

                    if (selectedItem.length > 0) {
                        selectedItem.removeClass('flex-selected');
                        var nextItem = selectedItem.next();

                        if (!nextItem.is('a'))
                            nextItem = nextItem.next();

                        if (nextItem.length > 0) {
                            nextItem.addClass('flex-selected');

                        } else {
                            selectedItem = element.find('.flex-smart-search-whisperer .flex-items a').eq(0).addClass('flex-selected');
                        }
                    } else {
                        selectedItem = element.find('.flex-smart-search-whisperer .flex-items a').eq(0).addClass('flex-selected');
                    }

                } else if (e.which === 13) {
                    e.preventDefault();

                    selectedItem = element.find('.flex-smart-search-whisperer .flex-items a.flex-selected');

                    if (selectedItem.length > 0) {
                        window.location.href = selectedItem.attr('href');
                    } else {
                        element.find('.flex-smart-search-button').click();
                    }
                }

                if (isKeyPrintable(e.which) && element.find('.flex-hint').is(":hidden")) {
                    if (!isSmallScreen()) {
                        layer++;
                        element.find('.flex-hint').css('z-index', layer);
                        element.find('.flex-hint').fadeIn(600);
                    }
                }
            });

            element.find('.flex-smart-search-input input[type="text"]').on('click', function (e) {
                if (element.find('.flex-hint').is(":hidden")) {
                    if (element.find('.flex-smart-search-whisperer .flex-items a').length > 0) {
                        $(".flex-smart-search").find('.flex-smart-search-whisperer').slideDown({ duration: 600, easing: 'easeOutExpo' });
                    }

                    if (!$('.flex-smart-search-input .flex-search-targets input[type="button"].flex-target').hasClass("flex-selected"))
                        getSmartSearchWhispers('.flex-smart-search-whisperer', $('#SmartSearchInput').val(), 0, true, false, null);

                    if (!isSmallScreen()) {
                        layer++;
                        element.find('.flex-hint').css('z-index', layer);
                        element.find('.flex-hint').fadeIn(600);
                    }
                }
            });

            element.find('input[type="text"]').on('focusin', function (e) {
                if (element.find('.flex-hint').is(":hidden")) {
                    if (element.find('.flex-smart-search-whisperer .flex-items a').length > 0) {
                        $(".flex-smart-search").find('.flex-smart-search-whisperer').slideDown({ duration: 600, easing: 'easeOutExpo' });

                        if (!isSmallScreen()) {
                            layer++;
                            element.find('.flex-hint').css('z-index', layer);
                            element.find('.flex-hint').fadeIn(600);
                        }
                    }
                }

                if (!$('.flex-smart-search-input .flex-search-targets input[type="button"].flex-target').hasClass("flex-selected"))
                    getSmartSearchWhispers('.flex-smart-search-whisperer', $('#SmartSearchInput').val(), 0, true, false, null);
            });

            element.find('input[type="text"]').on('focusout', function (e) {
                //$('.flex-smart-search-input .flex-search-targets input[type="button"].flex-history').removeClass("flex-selected");
                //$(".flex-smart-search").find('.flex-smart-search-whisperer .flex-items a').removeClass('flex-selected');
                //$(".flex-smart-search").find('.flex-hint').fadeOut(400);
            });

            element.find('input[type="text"]').on('input', function (e) {
                debouncedSmartSearchInput();
            });

            element.find('.flex-search-targets input[type="button"].flex-target').on('click', function (e) {

                element.find('.flex-search-targets input[type="button"]').removeClass("flex-selected");
                $(this).addClass("flex-selected");

                let target = 0;

                if ($(this).hasClass('flex-code'))
                    target = 1;

                if ($(this).hasClass('flex-text'))
                    target = 2;

                if ($(this).hasClass('flex-vehicle'))
                    target = 3;

                if ($(this).hasClass('flex-vin'))
                    target = 4;

                if ($(this).hasClass('flex-kba'))
                    target = 5;

                getSmartSearchWhispers('.flex-smart-search-whisperer', $('#SmartSearchInput').val(), target, true, false, null);

                setCaretAtEnd(element.find('input[type="text"]'));
            });

            element.on('mousemove', '.flex-smart-search-whisperer .flex-items a', function () {
                element.find('.flex-smart-search-whisperer .flex-items a').removeClass('flex-selected');
                $(this).addClass('flex-selected');
            });

            element.on('mouseout', '.flex-smart-search-whisperer .flex-items a', function () {
                element.find('.flex-smart-search-whisperer .flex-items a').removeClass('flex-selected');
            });
        });

        $(document).bind('click', function (e) {
            var clicked = $(e.target);
            if (!clicked.parents().hasClass("flex-smart-search-input")) {
                $(".flex-smart-search").find('.flex-smart-search-whisperer').slideUp({
                    duration: 400, easing: 'easeInBack', done: function () {
                        if ($('.flex-smart-search-input .flex-search-targets input[type="button"].flex-history').hasClass('flex-selected')) {
                            getSmartSearchWhispers('.flex-smart-search-whisperer', $('#SmartSearchInput').val(), 0, false, false, null);
                        }

                        $('.flex-smart-search-input .flex-search-targets input[type="button"].flex-history').removeClass("flex-selected");
                        $(".flex-smart-search").find('.flex-smart-search-whisperer .flex-items a').removeClass('flex-selected');
                    }
                });

                $(".flex-smart-search").find('.flex-hint').fadeOut(400);
            }
        });


        $('.flex-smart-search .flex-smart-search-spz-input input').keyup(function (e) {
            if (e.keyCode == 13) {
                getSmartSearchNumberPlate(this.value);
            }
        });


        $('.flex-smart-search .flex-smart-search-spz-input .search_field .fa-search').click(function () {
            var searchPhrase = $(this).parent().find("input").val();
            getSmartSearchNumberPlate(searchPhrase);
        });

    };

    $.fn.FlexLoginForm = function () {
        this.each(function () {
            var element = $(this);

            if ($('.flex-login-form .flex-login-form-box').attr('data-flex-opened') == "true") {
                $('.flex-login-form .flex-login-form-box').show(0);
                element.find('span').first().addClass('flex-selected');
            }

            element.find('span').first().click(function () {

                if ($('.flex-login-form .flex-login-form-box').is(':visible')) {
                    if ($('.flex-login-form-box').scrollLeft() > 0 || $('.flex-login-form .flex-wrapper').scrollLeft() > 0) {
                        $('.flex-login-form-box').animate({ scrollLeft: 0 }, 400);
                        $('.flex-login-form .flex-wrapper').animate({ scrollLeft: 0 }, 400);
                    }

                    $('.flex-login-form .flex-login-form-box').slideUp(400, 'easeInBack', function () {
                        $('.flex-login-form span').removeClass('flex-selected');
                    });
                } else {
                    $('.flex-login-form .flex-login-form-box').hide(0);
                    $(this).addClass('flex-selected');

                    element.find('.flex-login-form-box').slideDown(600, 'easeOutExpo', function () {
                        $('.flex-login-form .flex-login-form-box input').first().focus();

                    });

                    layer++;
                    element.find('.flex-login-form-box').css('z-index', layer);
                    layer++;
                    $(this).css('z-index', layer);
                }
            });

            element.find('span.flex-login-form-lost-password-button').click(function () {
                $('.flex-login-form-box').animate({ scrollLeft: 350 }, 400);
                $('.flex-login-form .flex-wrapper').animate({ scrollLeft: $('.flex-login-form .flex-wrapper .flex-form').outerWidth(true) }, 400);
            });

            element.find('span.flex-back-to-login-button').click(function () {
                $('.flex-login-form-box').animate({ scrollLeft: 0 }, 400);
                $('.flex-login-form .flex-wrapper').animate({ scrollLeft: 0 }, 400);
            });

            element.find('.flex-login-form-box input[type="password"]').on('keypress', function (e) {
                if (e.which == 13) {
                    element.find('.flex-login-form-box .flex-login-button').click();
                }
            });
        });

        var clicked;

        $(document).bind('mousedown', function (e) {
            clicked = $(e.target);
        }).bind('mouseup', function (e) {
            if (clicked.parents == undefined) {
                return;
            }

            if (!clicked.parents().hasClass("flex-login-form")) {
                if ($('.flex-login-form-box').scrollLeft() > 0 || $('.flex-login-form .flex-wrapper').scrollLeft() > 0) {
                    $('.flex-login-form-box').animate({ scrollLeft: 0 }, 400);
                    $('.flex-login-form .flex-wrapper').animate({ scrollLeft: 0 }, 400);
                }

                $('.flex-login-form .flex-login-form-box').slideUp(400, 'easeInBack', function () {
                    $('.flex-login-form span').removeClass('flex-selected');
                });
            }
        });
    };

    $.fn.FlexUserMenu = function () {
        this.each(function () {
            var element = $(this);

            element.find('span').first().click(function () {

                var isOpened = $(this).hasClass('flex-selected');

                $('.flex-user-menu div').first().slideUp(400, 'easeInBack', function () {
                    $('.flex-user-menu span').first().removeClass('flex-selected');
                });

                if (!isOpened) {
                    $(this).addClass('flex-selected');
                    element.find('div').slideDown(600, 'easeOutExpo');

                    layer++;
                    element.find('div').css('z-index', layer);
                    layer++;
                    $(this).css('z-index', layer);
                }
            });
        });

        $(document).bind('mousedown', function (e) {
            var clicked = $(e.target);
            if (!clicked.parents().hasClass("flex-user-menu")) {
                $('.flex-user-menu div').first().slideUp(400, 'easeInBack', function () {
                    $('.flex-user-menu span').first().removeClass('flex-selected');
                });
            }
        });
    };

    $.fn.FlexStocks = function () {
        this.each(function () {
            var element = $(this);

            element.attr('data-flex', 'true');

            element.find('.flex-other-stocks').mouseenter(function () {
                var productID = $(this).attr('data-product-id');
                var otherStocksElement = $('.flex-other-stocks-inner-wrapper[data-product-id="' + productID + '"]');

                if (!otherStocksElement.css('paddingLeft')) {
                    return;
                }

                var topOffset = $(this).offset().top + $(this).outerHeight();
                var leftOffset = $(this).offset().left;
                var width = $(this).outerWidth() - otherStocksElement.css('paddingLeft').replace('px', '') - otherStocksElement.css('paddingRight').replace('px', '') - otherStocksElement.css('borderLeftWidth').replace('px', '') - otherStocksElement.css('borderRightWidth').replace('px', '');

                $('body').append(otherStocksElement);

                otherStocksElement.css('top', topOffset + 'px');
                otherStocksElement.css('left', leftOffset + 'px');
                otherStocksElement.css('width', width + 'px');
                otherStocksElement.show();
            });

            element.find('.flex-other-stocks').mouseleave(function () {
                var productID = $(this).attr('data-product-id');
                $('.flex-other-stocks-inner-wrapper[data-product-id="' + productID + '"]').hide();
            });
        });
    };

    $.fn.FlexBasketSummary = function () {
        this.each(function () {
            var element = $(this);

            element.find('span').first().click(function () {
                if ($('.flex-basket-summary div').is(':visible')) {
                    $('.flex-basket-summary div').first().slideUp(400, 'easeInBack', function () {
                        $('.flex-basket-summary span').first().removeClass('flex-selected');
                    });
                } else {
                    $(this).addClass('flex-selected');
                    element.find('div').first().slideDown(600, 'easeOutExpo');

                    layer++;
                    element.find('div').first().css('z-index', layer);
                    layer++;
                    $(this).css('z-index', layer);
                }
            });
        });

        $(document).bind('mousedown', function (e) {
            var clicked = $(e.target);
            if (!clicked.parents().hasClass("flex-basket-summary") && !clicked.hasClass("flex-delete")) {
                $('.flex-basket-summary div').first().slideUp(400, 'easeInBack', function () {
                    $('.flex-basket-summary span').first().removeClass('flex-selected');
                });
            }
        });
    };

    $.fn.FlexSpinner = function () {
        this.each(function () {
            var element = $(this);

            element.attr('data-flex', 'true');

            var id = element.attr('data-flex-product-id');

            element.find('.flex-spinner .flex-spinner-increment-button').click(function () {
                var spinnerStep = parseFloat(element.attr('data-flex-spinner-step').replace(',', '.'));//'.flex-basket-spinner[data-flex="true"]'
                var inputAmount = parseFloat(element.find('input[type="text"]')[0].value.replace(',', '.'));//parseFloat($('#' + targetInput).val());
                var fixedNo = spinnerStep.toString().slice(spinnerStep.toString().indexOf('.'), spinnerStep.toString().length).length - 1;

                if (inputAmount == 0 || inputAmount == NaN || !inputAmount) {
                    element.find('input[type="text"]')[0].value = spinnerStep;
                    return false;
                }

                let closeCount = inputAmount % spinnerStep;
                if (closeCount != 0) {
                    element.find('input[type="text"]')[0].value = (inputAmount + (spinnerStep - closeCount)).toFixed(fixedNo).toString().replace('.', ',');
                    return false;
                }

                //$('#' + targetInput).val(parseFloat($('#' + targetInput).val()) + parseFloat(element.attr('data-flex-spinner-step')));
                element.find('input[type="text"]')[0].value = (inputAmount + spinnerStep).toFixed(fixedNo).toString().replace('.', ',');
                return false;
            });

            element.find('.flex-spinner .flex-spinner-decrement-button').click(function () {
                var inputAmount = parseFloat(element.find('input[type="text"]')[0].value.replace(',', '.'));//parseFloat($('#' + targetInput).val());
                var spinnerStep = parseFloat(element.attr('data-flex-spinner-step').replace(',', '.'));//$('.flex-basket-spinner[data-flex="true"]'//parseFloat(element.attr('data-flex-spinner-step'));
                var fixedNo = spinnerStep.toString().slice(spinnerStep.toString().indexOf('.'), spinnerStep.toString().length).length - 1;

                if (inputAmount == 0 || inputAmount == NaN || !inputAmount) {
                    element.find('input[type="text"]')[0].value = spinnerStep;
                    return false;
                }

                let closeCount = inputAmount % spinnerStep;

                if ((inputAmount - spinnerStep) >= spinnerStep) {
                    if (closeCount != 0) {
                        element.find('input[type="text"]')[0].value = (inputAmount - closeCount).toFixed(fixedNo).toString().replace('.', ',');
                        return false;
                    }
                    element.find('input[type="text"]')[0].value = (inputAmount - spinnerStep).toFixed(fixedNo).toString().replace('.', ',');
                }
                return false;
            });
        });
    };


    carouselSlideToLeft = function (element) {
        if ((element.find('.flex-inner-wrapper').scrollLeft() + element.find('.flex-inner-wrapper').width() + element.find('.flex-inner-wrapper .flex-item').outerWidth(true)) < element.find('.flex-inner-wrapper').get(0).scrollWidth && !element.find('.flex-inner-wrapper').is(':animated')) {
            element.find('.flex-inner-wrapper').stop().animate({ scrollLeft: element.find('.flex-inner-wrapper').scrollLeft() + element.find('.flex-inner-wrapper .flex-item').outerWidth(true) }, 400);
        }
    }

    carouselSlideToRight = function (element) {
        if (element.find('.flex-inner-wrapper').scrollLeft() > 0 && !element.find('.flex-inner-wrapper').is(':animated')) {
            element.find('.flex-inner-wrapper').stop().animate({ scrollLeft: element.find('.flex-inner-wrapper').scrollLeft() - element.find('.flex-inner-wrapper .flex-item').outerWidth(true) }, 400);
        }
    }

    carouselAutoSlide = function (element) {
        var carouselIntv = setInterval(function () {
            if ((element.find('.flex-inner-wrapper').scrollLeft() + element.find('.flex-inner-wrapper').width() + element.find('.flex-inner-wrapper .flex-item').outerWidth(true)) < element.find('.flex-inner-wrapper').get(0).scrollWidth) {
                carouselSlideToLeft(element);
            } else {
                element.find('.flex-inner-wrapper').stop().animate({ scrollLeft: 0 }, 800);
            }
        }, 3000);

        return carouselIntv;
    }

    $.fn.FlexCarousel = function () {
        this.each(function () {
            var element = $(this);

            element.find('.products-list').FlexSameHeightContainer();

            element.find('.products-list').on('swipeleft', function () {
                carouselSlideToLeft(element);
            });

            element.find('.products-list').on('swiperight', function () {
                carouselSlideToRight(element);
            });

            element.find('.flex-left-button').click(function () {
                carouselSlideToRight(element);
            });

            element.find('.flex-right-button').click(function () {
                carouselSlideToLeft(element);
            });

            var carouselIntv = carouselAutoSlide(element);

            element.on('mouseenter mouseleave', function (e) {
                if (e.type == 'mouseenter') {
                    clearInterval(carouselIntv);
                } else {
                    carouselIntv = carouselAutoSlide(element);
                }
            });
        });
    };

    $.fn.FlexFilterTabs = function () {
        this.each(function () {
            var element = $(this);

            element.find('> .flex-title').click(function () {
                if ($(this).hasClass('flex-expanded')) {
                    element.find('.flex-content').slideUp({ duration: 400, easing: 'easeInBack' });
                    $(this).find('.flex-tags').show(400);
                    $(this).removeClass('flex-expanded');
                    $("#FilterParamsExpanded").val("false");
                } else {
                    element.find('.flex-content').slideDown({ duration: 600, easing: 'easeOutExpo' });
                    $(this).addClass('flex-expanded');
                    $(this).find('.flex-tags').hide(400);
                    if (element.hasClass('flex-parameters')) {
                        var heightPadding = parseInt(element.find('.flex-attribute-values:first-child').css('paddingTop')) + parseInt(element.find('.flex-attribute-values:first-child').css('paddingBottom'));
                        // element.find('.flex-attribute-values:first-child').css('min-height', element.find('.flex-attributes').innerHeight() - heightPadding - 1 + 'px');
                    }
                    $("#FilterParamsExpanded").val("true");
                }
            });

            if (element.hasClass('flex-manufacturers')) {

                element.find('input[type="checkbox"]').on('change', function () {

                    var manufacturersQuery = '';

                    $('.flex-filter .flex-manufacturers').find('input[type="checkbox"]').each(function () {
                        var element = $(this);

                        if (element.is(':checked')) {

                            if (manufacturersQuery == '') {
                                manufacturersQuery += element.attr('value');
                            } else {
                                manufacturersQuery += '~' + element.attr('value');
                            }
                        }
                    });

                    manufacturersQuery = JSON.stringify(manufacturersQuery).substring(1, JSON.stringify(manufacturersQuery).length)
                    manufacturersQuery = manufacturersQuery.substring(0, manufacturersQuery.length - 1);

                    $('.products .flex-filter').find('.flex-extended').attr('data-flex-manufacturers-filters-query', manufacturersQuery);
                });
            }

            if (element.hasClass('flex-parameters')) {
                element.find('.flex-attributes').each(function () {
                    var genericArticleKey = $(this).attr('data-flex-generic-article-key');
                    var target = element.find('.flex-attribute-values-container[data-flex-generic-article-key="' + genericArticleKey + '"]');

                    $(this).find('.flex-attribute-values').appendTo(target);

                    target = $('.flex-attribute-values-container[data-flex-generic-article-key="' + genericArticleKey + '"] .flex-attribute-values:first-child');
                    // let heightPadding = parseInt(target.css('paddingTop')) + parseInt(target.css('paddingBottom'));
                    // target.css('min-height', $(this).innerHeight() - heightPadding - 1 + 'px');
                    target.show();
                });
            }
        });
    };

    buildFilterQuery = function () {
        var container = $('.flex-parameters .flex-content');

        var query = "";

        container.find('.flex-generic-article').each(function () {
            var genericArticle = $(this);

            if (genericArticle.find('.flex-title input.flex-generic-article:checked').length != 0) {
                if (query != '') {
                    query += '~';
                }

                var genericArticleKey = genericArticle.find('.flex-title input.flex-generic-article').attr('data-flex-generic-article-key');
                query += genericArticleKey;

                genericArticle.find('.flex-attributes .flex-title').each(function () {
                    var attribute = $(this);

                    var attributeKey = attribute.attr('data-flex-attribute-key');
                    var attributeType = attribute.attr('data-attribute-type');

                    var values = genericArticle.find('#GenericArticleAttributeFilterValues_' + genericArticleKey + '_' + attributeKey);

                    var isFiltered = false;
                    var selectedValues = '';

                    if (attributeType == 'numeric') {
                        var slider = values.find('.flex-range-slider');
                        var sliderValues = slider.attr('data-flex-values').replace('.', ',');
                        var handleValues = document.getElementById(slider.attr('ID')).noUiSlider.get();
                        var valueArray = sliderValues.split(';');
                        var minValue = parseFloat(valueArray[0].replace(',', '.'));
                        var maxValue = parseFloat(valueArray[valueArray.length - 1].replace(',', '.'));

                        isFiltered = minValue != parseFloat(handleValues[0]) || maxValue != parseFloat(handleValues[1]);

                        if (isFiltered) {
                            for (i = 0; i < valueArray.length; i++) {
                                if (parseFloat(valueArray[i].replace(',', '.')) >= parseFloat(handleValues[0]) && parseFloat(valueArray[i].replace(',', '.')) <= parseFloat(handleValues[1])) {
                                    selectedValues += ';' + valueArray[i];
                                }
                            }
                        }
                    } else {
                        var checkedInputs = values.find('input[type="checkbox"]:checked');
                        isFiltered = checkedInputs.length > 0;

                        if (isFiltered) {
                            checkedInputs.each(function () {
                                selectedValues += ';' + $(this).attr('data-flex-attribute-value');
                            });
                        }
                    }

                    if (isFiltered) {
                        query += '|' + attributeKey + selectedValues;
                    }
                });
            }
        });

        return query;
    }

    $.fn.FlexCategories = function () {
        this.each(function () {
            var element = $(this);
            let shortcuts = element.find('.shortcuts');
            let tree = element.find('.tree');
            var useDynamicLoad = element.find('.tree').attr('data-use-dynamic-load') == 'true';
            var catalogType = parseInt(element.find('.tree').attr('data-catalog-type'));
            var rootCategoryID = parseInt(element.find('.tree').attr('data-root-category-id'));
            var showSubnodesInShortcuts = element.find('.tree').attr('data-show-subnodes-in-shortcuts') == 'true';
            var useJsHistory = element.find('.tree').attr('data-use-js-history') == 'true';
            var expandedIDsPath = getUrlHistoryValue('path');
            var rootID = getUrlHistoryValue('root');
            var expandedIDs = [];

            element.unbind("click");

            element.on('click', '.tree a', function (event, triggeredFromCode) {
                var isSelectedEndNode = $(this).hasClass('selected') && $(this).attr('data-is-end-node') == 'true';
                var fullCategoryIdsPath = $(this).attr('data-full-category-ids-path');

                if (!$(this).hasClass('static') && !isSelectedEndNode) {
                    var link = $(this);

                    var forceToogle = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

                    if (link.data('is-expandable') == true)
                        event.preventDefault();

                    if (catalogType == 2) { // TecDoc
                        var fromShortcut = link.parents('.shortcuts').length >= 1;
                        let isShortcutContentTree = link.parents('.tree.container').length;

                        if (link.data('is-expandable') == true || forceToogle) {
                            getTecDocConstructionGroupsSubcategories(link.attr('data-node-id'), tree.attr('data-manufacturer-name'), tree.attr('data-manufacturer-id'), tree.attr('data-model-name'), tree.attr('data-model-id'), tree.attr('data-engine-name'), tree.attr('data-engine-id'), tree.attr('data-vehicle-type'), link.attr('data-full-category-ids-path'), fromShortcut, showSubnodesInShortcuts).then(function () {
                                toogleCategory(element, link, forceToogle, fromShortcut, useDynamicLoad, showSubnodesInShortcuts, triggeredFromCode, event);

                                if (expandedIDs.length > 0) {
                                    element.find('.tree a[data-node-id="' + expandedIDs.shift() + '"]').trigger('click', [true]);
                                } else {
                                    shortcuts.show();
                                }
                            });

                            let isExpanded = link.hasClass('selected');

                            if (useJsHistory && !triggeredFromCode && !isShortcutContentTree && !isExpanded) {
                                let path = fullCategoryIdsPath.split('~');

                                history.pushState(null, document.title, getUrlPath() + '?path=' + path.join('~'));
                            }
                        } else {
                            toogleCategory(element, link, forceToogle, fromShortcut, useDynamicLoad, showSubnodesInShortcuts, triggeredFromCode, event);

                            if (expandedIDs.length > 0) {
                                element.find('.tree a[data-node-id="' + expandedIDs.shift() + '"]').trigger('click', [true]);
                            } 
                        }
                    } else if (catalogType == 3) { // Universal parts
                        if (link.data('is-expandable') == true || forceToogle) {
                            getUniversalPartsSubcategories(link.attr('data-node-id'), useDynamicLoad, rootCategoryID, showSubnodesInShortcuts).then(function () {
                                toogleCategory(element, link, forceToogle, false, useDynamicLoad, showSubnodesInShortcuts, triggeredFromCode, event);

                                if (expandedIDs.length > 0) {
                                    element.find('.tree a[data-node-id="' + expandedIDs.shift() + '"]').trigger('click', [true]);
                                } else {
                                    shortcuts.show();
                                }
                            });

                            let isExpanded = link.hasClass('selected');

                            if (useJsHistory && !triggeredFromCode && !isExpanded) {
                                let path = fullCategoryIdsPath.split('~');

                                if (rootID !== false && rootID > -1) {
                                    history.pushState(null, document.title, getUrlPath() + '?root=' + rootID + '&path=' + path.join('~'));
                                } else {
                                    history.pushState(null, document.title, getUrlPath() + '?path=' + path.join('~'));
                                }
                            }
                        } else {
                            toogleCategory(element, link, forceToogle, false, useDynamicLoad, showSubnodesInShortcuts, triggeredFromCode, event);

                            if (expandedIDs.length > 0) {
                                element.find('.tree a[data-node-id="' + expandedIDs.shift() + '"]').trigger('click', [true]);
                            } else {
                                if (useJsHistory && !triggeredFromCode) {
                                    let path = fullCategoryIdsPath.split('~');
                                    path.pop();

                                    if (rootID !== false && rootID > -1) {
                                        history.replaceState(null, document.title, getUrlPath() + '?root=' + rootID + '&path=' + path.join('~'));
                                    } else {
                                        history.replaceState(null, document.title, getUrlPath() + '?path=' + path.join('~'));
                                    }
                                }
                            }
                        }
                    } else if (catalogType == 11) { // Reverse TecDoc
                        toogleCategory(element, link, forceToogle, false, useDynamicLoad, showSubnodesInShortcuts, triggeredFromCode, event);

                        if (expandedIDs.length > 0) {
                            element.find('.tree a[data-node-id="' + expandedIDs.shift() + '"]').trigger('click', [true]);
                        }
                    } else if (catalogType == 12) { //TecRMI
                        toogleTest(element, link, forceToogle, false, false, showSubnodesInShortcuts, event);
                        if (expandedIDs.length > 0) {
                            element.find('.tree a[data-node-id="' + expandedIDs.shift() + '"]').trigger('click', [true]);
                        }
                    }
                }
            });

            setTimeout(function ()  {
                expandedIDsPath = getUrlHistoryValue('path');

                let expandedElements = element.find('a.selected');

                expandedElements.each(function () {
                    let link = $(this);

                    link.removeClass('selected');
                    link.parent().find('.node').slideUp(0, function () {
                        if (useDynamicLoad)
                            $(this).remove();
                    });
                });

                if (expandedIDsPath != false) {
                    shortcuts.hide();

                    expandedIDs = expandedIDsPath.split('~');

                    if (rootID !== false && rootID > -1) {
                        var index = expandedIDs.indexOf(rootID);
                        expandedIDs.splice(0, index + 1);
                    }

                    if (element.find('.tree a[data-node-id="' + expandedIDs[0] + '"]').hasClass('static')) {
                        expandedIDs.shift();
                    }

                    element.find('.tree a[data-node-id="' + expandedIDs.shift() + '"]').trigger('click', [true]);
                } else {
                    if (event.type == 'popstate') {
                        if (catalogType == 2) { //TecDoc
                            getConstructionGroupsRoot(tree.attr('data-manufacturer-name'), tree.attr('data-manufacturer-id'), tree.attr('data-model-name'), tree.attr('data-model-id'), tree.attr('data-engine-name'), tree.attr('data-engine-id'), tree.attr('data-vehicle-type'));
                        } else if (catalogType == 3) { //Universal parts
                            getUniversalPartsSubcategories(rootCategoryID, useDynamicLoad, rootCategoryID, showSubnodesInShortcuts);
                        }
                    }
                }
            }, 200);
        });

        $(document).bind('click', function (e) {
            let clicked = $(e.target);
            if (clicked.length === 0) {
                return;
            }

            if (!clicked.parents().hasClass('shortcuts')) {
                $('.tree.container').slideUp(300, function () {
                    $(this).parents('a').removeClass('selected');
                    $(this).remove();
                });
            }
        });
    };

    toogleTest = function (element, link, forceToogle, fromShortcut, useDynamicLoad, showSubnodesInShortcuts, event) {
        let dataNodeId = link.attr('data-node-id');
        let node = link.parent().find("#Node_" + dataNodeId)
        let autoCollapseUnusedNodes = element.find('.tree').attr('data-auto-collapse-unused-nodes') == 'true';

        if (forceToogle || (node.length && (link.data('is-expandable') == true || link.hasClass('selected')))) {
            event.preventDefault();

            if (autoCollapseUnusedNodes) {
                let parents = link.parents();
                element.find('.tree a.selected').not(parents.children('a')).removeClass('selected').parent().children('.node').slideUp(300, function () {
                    if (useDynamicLoad)
                        $(this).empty();
                });
            }

            if (link.hasClass('selected')) {
                node.slideUp(300, function () {
                    link.removeClass('selected');
                    if (useDynamicLoad)
                        node.remove();
                });
            } else {
                link.addClass('selected');
                node.slideDown(300, function () {
                    if (!showSubnodesInShortcuts) {
                        let nodeOffset = node.offset().top;
                        let nodeHeight = node.height();
                        let viewportOffset = $(document).scrollTop();
                        let viewportHeight = $(window).height();

                        if ($(".flex-product-wrapper").length == 0 && $(".products-list").length == 0) {
                            if ((nodeOffset + nodeHeight) > (viewportOffset + viewportHeight)) {
                                let newOffset = (nodeOffset + nodeHeight) - (viewportOffset + viewportHeight) + viewportOffset;
                                $(document).scrollTop(newOffset);
                            }
                        }
                    }
                })
            }
        }
    }

    toogleCategory = function (element, link, forceToogle, fromShortcut, useDynamicLoad, showSubnodesInShortcuts, triggeredFromCode, event) {
        let node;
        if (fromShortcut)
            node = $('.shortcuts #Node_' + link.attr('data-node-id'));
        else
            node = $('.tree.main #Node_' + link.attr('data-node-id'));

        let autoCollapseUnusedNodes = element.find('.tree').attr('data-auto-collapse-unused-nodes') == 'true';

        if (forceToogle || (node.length && (link.data('is-expandable') == true || link.hasClass('selected')))) {
            event.preventDefault();

            if (autoCollapseUnusedNodes) {
                let parents = link.parents();

                element.find('.tree a.selected').not(parents.children('a')).removeClass('selected').parent().children('.node').slideUp(300, function () {
                    if (useDynamicLoad)
                        $(this).empty();
                });
            }

            if (link.hasClass('selected')) {
                node.slideUp(300, function () {
                    link.removeClass('selected');
                    if (useDynamicLoad)
                        node.remove();
                });
            } else {
                let slideDuration = triggeredFromCode ? 0 : 300;

                link.addClass('selected');
                node.slideDown(slideDuration, function () {
                    if (!showSubnodesInShortcuts) {
                        let nodeOffset = node.offset().top;
                        let nodeHeight = node.height();
                        let viewportOffset = $(document).scrollTop();
                        let viewportHeight = $(window).height();

                        if ($(".flex-product-wrapper").length == 0 && $(".products-list").length == 0) {
                            if ((nodeOffset + nodeHeight) > (viewportOffset + viewportHeight)) {
                                var newOffset = (nodeOffset + nodeHeight) - (viewportOffset + viewportHeight) + viewportOffset;
                                $(document).scrollTop(newOffset);
                            }
                        }
                    }
                })
            }
        }
    }

    $.fn.FlexTree = function () {
        this.each(function () {
            var element = $(this);

            element.unbind('click');

            element.on('click', '.flex-node', function (event) {
                if (!$(this).hasClass('flex-selected') && !$(this).is('a')) {
                    if (element.attr('data-flex-collapse-unused-nodes') || element.attr('data-flex-collapse-unused-nodes').toLowerCase() == "true") {
                        $(this).parent('div').find('.flex-selected').not($(this)).children().not('span:first').not('span.flex-folders-count').not('span.flex-items-count').slideUp(300, function () {
                            $(this).parent().removeClass('flex-selected');
                        });
                    }

                    $(this).addClass('flex-selected');

                    $(this).children().css("display", "block");
                    $(this).children().not('span:first').hide();

                    $(this).children().not('span:first').slideDown(300);
                } else {
                    $(this).removeClass('flex-selected');
                    $(this).children().not('span:first').not('span.flex-folders-count').not('span.flex-items-count').slideUp(300);
                }

                return false;
            });

            if (element.attr('data-flex-history') == 'true') {
                var expandedIDsPath = getUrlHistoryValue('path');

                if (expandedIDsPath != '') {
                    expandedIDsPath.replace("%7e", "~");
                    var expandedIDsPathSplitted = expandedIDsPath.split('~');

                    if ($('#TreeNode_' + expandedIDsPathSplitted[0]).is('a')) {
                        $('#TreeNode_' + expandedIDsPathSplitted[0]).addClass("flex-selected");
                    } else {
                        $('#TreeNode_' + expandedIDsPathSplitted[0]).attr('data-flex-show-products-direct', 'false');
                        $('#TreeNode_' + expandedIDsPathSplitted[0]).click();
                    }
                } else {
                    element.attr('data-flex-expanded', 'true');
                }
            }
        });

        $(document).bind('click', function (e) {
            var clicked = $(e.target);
            if (!clicked.parents().hasClass("flex-tree-container")) {
                $('.flex-tree-container').each(function () {
                    $(this).parent().removeClass('flex-selected');
                    $(this).parent().children().not('span:first').not('span.flex-folders-count').not('span.flex-items-count').remove();
                });
            }
        });
    };

    $.fn.FlexDynamicTree = function () {
        this.each(function () {
            var element = $(this);

            element.unbind('click');

            element.on('click', '.flex-node', function (event) {
                if (!$(this).attr('data-flex-show-products-direct') || $(this).attr('data-flex-show-products-direct').toLowerCase() != 'true') {
                    if (!$(this).parents().hasClass("flex-tree-container")) {
                        $('.flex-tree-container').parent().removeClass('flex-selected');
                        $('.flex-tree-container').parent().children().not('span:first').not('span.flex-folders-count').not('span.flex-items-count').remove();
                    }

                    if (!$(this).hasClass('flex-selected') && !$(this).is('a')) {

                        if (element.attr('data-flex-collapse-unused-nodes') || element.attr('data-flex-collapse-unused-nodes').toLowerCase() == "true") {
                            $(this).parent('div').find('.flex-selected').not($(this)).children().not('span:first').not('span.flex-folders-count').not('span.flex-items-count').slideUp(300, function () {
                                $(this).parent().removeClass('flex-selected');
                                $(this).not('span:first').not('span.flex-folders-count').not('span.flex-items-count').remove();
                            });
                        }

                        if (!$(this).hasClass('flex-big-node')) {
                            $(this).addClass('flex-selected');
                        } else {
                            var id = $(this).attr('data-flex-node-id');
                            $('#TreeNode_' + id).addClass('flex-selected');
                        }
                    } else {
                        $(this).removeClass('flex-selected');

                        $(this).children().not('span:first').not('span.flex-folders-count').not('span.flex-items-count').slideUp(300, function () {
                            $(this).remove();
                        });
                    }
                }

                return false;
            });

            if (element.attr('data-flex-history') == 'true') {
                var expandedIDsPath = getUrlHistoryValue('path');

                if (expandedIDsPath != '') {
                    expandedIDsPath.replace("%7e", "~");
                    var expandedIDsPathSplitted = expandedIDsPath.split('~');

                    if ($('#TreeNode_' + expandedIDsPathSplitted[0]).is('a')) {
                        $('#TreeNode_' + expandedIDsPathSplitted[0]).addClass("flex-selected");
                    } else {
                        $('#TreeNode_' + expandedIDsPathSplitted[0]).attr('data-flex-show-products-direct', 'false');
                        $('#TreeNode_' + expandedIDsPathSplitted[0]).click();
                    }
                } else {
                    element.attr('data-flex-expanded', 'true');
                }
            }
        });

        $(document).bind('click', function (e) {
            var clicked = $(e.target);
            if (!clicked.parents().hasClass("flex-tree-container")) {
                $('.flex-tree-container').each(function () {
                    $(this).parent().removeClass('flex-selected');
                    $(this).parent().children().not('span:first').not('span.flex-folders-count').not('span.flex-items-count').remove();
                });
            }
        });
    };

    $.fn.FlexProductGroupsTree = function () {
        this.each(function () {
            var element = $(this);

            element.unbind('click');

            element.on('click', '.flex-node', function (event) {
                if ($(this).attr('data-flex-has-children') == 'true') {
                    if (!$(this).hasClass('flex-selected')) {
                        $(this).addClass('flex-selected');
                    } else {
                        $(this).removeClass('flex-selected');

                        $(this).children().not('span:first').not('span.flex-folders-count').not('span.flex-controls').slideUp(300, function () {
                            $(this).remove();
                        });
                    }
                }

                return false;
            });
        });
    };

    //$.fn.FlexTecDocDynamicCross = function () {
    //    this.each(function () {
    //        var element = $(this);

    //        var products = [];

    //        element.find('.flex-item[data-flex-tecdoc-dynamic-cross="true"]').each(function () {
    //            $(this).attr('data-flex-tecdoc-dynamic-cross', 'false');

    //            if ($(this).attr('data-flex-tecdoc-brand-id') > -1)
    //                products.push($(this).attr('id') + ';' + $(this).attr('data-flex-tecdoc-code-pair') + ';' + $(this).attr('data-flex-group-id') + ';' + $(this).attr('data-flex-tecdoc-brand-id') + ';' + $(this).attr('data-flex-tecdoc-generic-article-id') + ';' + $(this).attr('data-flex-tecdoc-article-linkid') + ';' + $(this).attr('data-flex-tecdoc-generic-manufacturer-id') + ';' + $(this).attr('data-flex-tecdoc-generic-model-id') + ';' + $(this).attr('data-flex-tecdoc-generic-engine-id'));
    //        });

    //        if (products.length > 0)
    //            getTecDocCrossData(products);
    //    });
    //};

    $.fn.FlexAsyncImageLoader = function () {
        this.each(function () {
            var element = $(this);

            if (element.attr('src') != element.attr('data-flex-async-image-src')) {
                element.hide();
                var imageToDownload = new Image();
                imageToDownload.onload = function () {
                    element.attr('src', element.attr('data-flex-async-image-src'));
                    element.fadeIn(1000);
                    element.parent().parent('.flex-image-wrapper').css('background-image', 'none');
                    //element.parent('.flex-image-wrapper').css('background-image', 'none');
                    if (element.parents().hasClass("flex-carousel")) {
                        element.parents('.products-list').FlexSameHeightContainer();
                    }
                };

                imageToDownload.src = element.attr('data-flex-async-image-src');
            }
        });
    };

    $.fn.FlexTooltip = function () {
        this.each(function () {
            var element = $(this);

            element.mousemove(function (event) {
                if (isSmallScreen) {
                    if ($(window).width() < (event.pageX + 10 + $('.flex-tooltip').outerWidth())) {

                        if ((event.pageX - ($('.flex-tooltip').outerWidth())) < 0) {
                            $('.flex-tooltip').css('left', 5);
                        }
                        else {
                            $('.flex-tooltip').css('left', event.pageX - $('.flex-tooltip').outerWidth());
                        }

                    } else {
                        $('.flex-tooltip').css('left', event.pageX + 10);
                    }
                }
                else {
                    if ($(window).width() < (event.pageX + 10 + $('.flex-tooltip').outerWidth())) {
                        $('.flex-tooltip').css('left', event.pageX - $('.flex-tooltip').outerWidth());
                    } else {
                        $('.flex-tooltip').css('left', event.pageX + 10);
                    }
                }
                $('.flex-tooltip').css('top', event.pageY + 21);
            });

            element.mouseenter(function (event) {
                $('body').append('<div class="flex-tooltip">' + $(this).attr('data-flex-tooltip') + '</div>');
                $('.flex-tooltip').hide();
                $('.flex-tooltip').fadeIn(300);
            });

            element.mouseleave(function (event) {
                $('.flex-tooltip').remove();
            });
        });
    };

    $.fn.FlexHtmlTooltip = function () {
        this.each(function () {
            var element = $(this);
            if (!isSmallScreen() && $('#' + $(this).attr('data-flex-html-tooltip')).length) {
                element.mousemove(function (event) {

                    if ($(window).width() < (event.pageX + 10 + $('.flex-tooltip').outerWidth())) {


                        $('.flex-tooltip').css('left', event.pageX + 10 + $(window).width() - (event.pageX + 10 + $('.flex-tooltip').outerWidth()));
                    } else {
                        $('.flex-tooltip').css('left', event.pageX + 10);
                    }

                    if ($(window).height() < (event.pageY - $(window).scrollTop() + 21 + $('.flex-tooltip').outerHeight() + 10)) {
                        var overflowHeight = event.pageY - $(window).scrollTop() + 21 + $('.flex-tooltip').outerHeight() - $(window).height() + 10;
                        $('.flex-tooltip').css('top', event.pageY + 21 - overflowHeight);
                    } else {
                        $('.flex-tooltip').css('top', event.pageY + 21);
                    }
                });

                element.mouseenter(function (event) {
                    if ($('#' + $(this).attr('data-flex-html-tooltip')).length) {
                        var additionalClass = $('#' + $(this).attr('data-flex-html-tooltip')).attr('data-additional-css-class');
                        var htmlText = $('#' + $(this).attr('data-flex-html-tooltip')).html();
                    } else if ($('#' + $(this).attr('data-flex-html-tooltip-desktop-only')).length) {

                        var additionalClass = $('#' + $(this).attr('data-flex-html-tooltip-desktop-only')).attr('data-additional-css-class');
                        var htmlText = $('#' + $(this).attr('data-flex-html-tooltip-desktop-only')).html();
                    }

                    if (additionalClass != null) {
                        $('body').append('<div class="flex-tooltip ' + additionalClass + '">' + htmlText + '</div>');
                    } else {
                        $('body').append('<div class="flex-tooltip">' + htmlText + '</div>');
                    }

                    $('.flex-tooltip').hide();
                    $('.flex-tooltip').fadeIn(300);
                });

                element.mouseleave(function (event) {
                    $('.flex-tooltip').remove();
                });
            }

            if (isSmallScreen() && $('#' + $(this).attr('data-flex-html-tooltip-desktop-only')).length === 0 && $('#' + $(this).attr('data-flex-html-tooltip')).length) {
                element.click(function (t) {
                    $('.tool-tip-close-button').remove();
                    $('.flex-tooltip').remove();

                    if ($('#' + $(this).attr('data-flex-html-tooltip')).length) {
                        var additionalClass = $('#' + $(this).attr('data-flex-html-tooltip')).attr('data-additional-css-class');
                        var htmlText = $('#' + $(this).attr('data-flex-html-tooltip')).html();
                    } else if ($('#' + $(this).attr('data-flex-html-tooltip-desktop-only')).length) {
                        var additionalClass = $('#' + $(this).attr('data-flex-html-tooltip-desktop-only')).attr('data-additional-css-class');
                        var htmlText = $('#' + $(this).attr('data-flex-html-tooltip-desktop-only')).html();
                    }

                    if (additionalClass != null) {
                        $('body').append('<div class="flex-tooltip ' + additionalClass + '">' + htmlText + '</div>');
                    } else {
                        $('body').append('<div class="flex-tooltip">' + htmlText + '</div>');
                    }

                    $('.flex-tooltip').hide();
                    $('.flex-tooltip').fadeIn(300);

                    if ($(window).width() < (t.pageX + 10 + $('.flex-tooltip').outerWidth())) {
                        if ((t.pageX - ($('.flex-tooltip').outerWidth())) < 0) {
                            $('.flex-tooltip').css('left', 5);
                        } else {
                            $('.flex-tooltip').css('left', t.pageX - $('.flex-tooltip').outerWidth());
                        }
                    } else {
                        $('.flex-tooltip').css('left', t.pageX + 10);
                    }

                    if ($('.flex-tooltip').outerWidth() > 350) {
                        $('.flex-tooltip').css("width", $(window).width() - 30);
                    }

                    $('.flex-price-tooltip-table').before('<div class="tool-tip-close-button"></div>');
                    $('.order-time-current').before('<div class="tool-tip-close-button"></div>');
                    $('.flex-delivery-on-time').before('<div class="tool-tip-close-button"></div>');

                    $('.tool-tip-close-button').click(function () {
                        $('.flex-tooltip').remove();
                    });

                    if ($(window).height() < (t.pageY - $(window).scrollTop() + 21 + $('.flex-tooltip').outerHeight() + 10)) {
                        var overflowHeight = t.pageY - $(window).scrollTop() + 21 + $('.flex-tooltip').outerHeight() - $(window).height() + 10;
                        $('.flex-tooltip').css('top', t.pageY + 21 - overflowHeight);
                    } else {
                        $('.flex-tooltip').css('top', t.pageY + 21);
                    }

                    $(window).on('mouseenter touchend', function (e) {
                        var clicked = $(e.target);
                        let parents = clicked.parents();
                        let shouldBeRemoved = false;
                        for (let i = 0; i < parents.length; i++) {
                            shouldBeRemoved = !parents[i].classList.contains("flex-tooltip");
                            if (!shouldBeRemoved) {
                                break;
                            }
                        }

                        if (shouldBeRemoved) {
                            $('.flex-tooltip').remove();
                        }
                    });
                });
            }
        });
    };

    $.fn.FlexShowLoading = function () {
        this.each(function () {
            var element = $(this);

            var outerWidth = element.width();
            var outerHeight = element.height();

            element.html('<div class="flex-loading" style="width: ' + outerWidth + 'px; height: ' + outerHeight + 'px;"><div class="flex-loading-spinner"></div></div>');
        });
    };

    $.fn.FlexShowLoadingOverlay = function () {
        this.each(function () {
            var element = $(this);

            if (element.css('position') != 'absolute' && element.css('position') != 'fixed')
                element.css('position', 'relative');

            var topBorderThickness = element.css("border-top-width").replace('px', '');
            var leftBorderThickness = element.css("border-left-width").replace('px', '');

            element.append('<div class="flex-loading-overlay" style="width: ' + element.outerWidth() + 'px; height: ' + element.outerHeight() + 'px; top: ' + (topBorderThickness * -1) + 'px; left: ' + (leftBorderThickness * -1) + 'px;"><div class="flex-loading-spinner" style="margin-top: ' + (element.outerHeight() - 32) / 2 + 'px;"></div></div>');
        });
    };

    $.fn.FlexShowInlineLoadingOverlay = function () {
        this.each(function () {
            var element = $(this);

            if (element.css('position') != 'absolute' && element.css('position') != 'fixed')
                element.css('position', 'relative');

            var topBorderThickness = element.css("border-top-width").replace('px', '');
            var leftBorderThickness = element.css("border-left-width").replace('px', '');

            element.append('<div class="flex-inline-loading-overlay" style="width: ' + element.outerWidth() + 'px; height: ' + element.outerHeight() + 'px; top: ' + (topBorderThickness * -1) + 'px; left: ' + (leftBorderThickness * -1) + 'px;"><div class="flex-inline-loading-spinner" style="margin-top: ' + (element.outerHeight() - 16) / 2 + 'px; margin-right: ' + (element.outerHeight() - 16) / 2 + 'px;"></div></div>');
        });
    };

    $.fn.FlexHideLoadingOverlay = function () {
        this.each(function () {
            var element = $(this);

            element.find('.flex-loading-overlay').remove();
        });
    };

    $.fn.FlexHideInlineLoadingOverlay = function () {
        this.each(function () {
            var element = $(this);

            element.find('.flex-inline-loading-overlay').remove();
        });
    };

    $.fn.FlexHideEmptyElement = function () {
        this.each(function () {
            var element = $(this);
            var hasNonHideableElement = element.find('img').length || element.find('iframe').length || element.find('script').length;

            var innerHtml = element.text().trim();

            if ((innerHtml.length < 1 && !hasNonHideableElement) || (element.height() < 1 && !hasNonHideableElement)) {
                element.remove();
            }
        });
    };

    $.fn.FlexShowNextPageLoading = function () {
        this.each(function () {
            var element = $(this);

            element.append('<div class="flex-next-page-loading"><div class="flex-next-page-loading-spinner"></div></div>');
        });
    };

    $.fn.FlexHideNextPageLoading = function () {
        this.each(function () {
            var element = $(this);

            element.find('.flex-next-page-loading').remove();
        });
    };

    $.fn.SearchByNumberScrollPager = function () {
        this.each(function () {
            var element = $(this);

            $(window).unbind('scroll', getNextSearchByNumberPageEvent);
            $(window).on('scroll', { element: element }, getNextSearchByNumberPageEvent);
        });
    };

    $.fn.TecDocScrollPager = function () {
        this.each(function () {
            var element = $(this);

            $(window).unbind('scroll', getNextTecDocPageEvent);
            $(window).on('scroll', { element: element }, getNextTecDocPageEvent);
        });
    };

    $.fn.UniversalPartsScrollPager = function () {
        this.each(function () {
            var element = $(this);

            $(window).unbind('scroll', getNextUniversalPartsPageEvent);
            $(window).on('scroll', { element: element }, getNextUniversalPartsPageEvent);
        });
    };

    $.fn.SaleScrollPager = function () {
        this.each(function () {
            var element = $(this);

            $(window).unbind('scroll', getNextSalePageEvent);
            $(window).on('scroll', { element: element }, getNextSalePageEvent);
        });
    };

    $.fn.LaximoScrollPager = function () {
        this.each(function () {
            var element = $(this);

            $(window).unbind('scroll', getNextLaximoPageEvent);
            $(window).on('scroll', { element: element }, getNextLaximoPageEvent);
        });
    };

    $.fn.DeliveryBranchSelectorScrollPager = function (transportMethodID) {
        this.each(function () {
            var element = $(this);

            $(element).unbind('scroll', pagingLoadDeliveryBranchItemsResolver);

            if (element.attr('data-is-last-page') == 'false')
                $(element).on('scroll', { element: element, transportMethodID: transportMethodID }, pagingLoadDeliveryBranchItemsResolver);
        });
    };


    getDeliveryBranchSelectorBatchEvent = function (e) {
        var content = e.data.element.find('.table');
        var contentHeight = content.height();
        var contentOffset = e.data.element.scrollTop();
        var transportMethodID = e.data.transportMethodID;

        if (contentOffset > contentHeight - contentHeight / 3) {
            e.data.element.unbind('scroll', getDeliveryBranchSelectorBatchEvent);

            //var articleID = e.data.element.parent().attr('data-flex-article-id');

            var startIndex = content.find('a.row').length - 1;

            getDeliveryBranchSelectorItems(content, transportMethodID, startIndex);
        }
    }

    getNextApplicationsPageEvent = function (e) {
        if ((e.data.element.offset().top + e.data.element.height()) < ($(window).height() + $(window).scrollTop()) + 200) {
            $(window).unbind('scroll', getNextApplicationsPageEvent);

            var articleID = e.data.element.parent().attr('data-flex-article-id');

            var startIndex = e.data.element.find('a.flex-item').length - 1;

            getProductDetailApplicationsPerPage(e.data.element, articleID, startIndex)
        }
    }

    $.fn.ApplicationsScrollPager = function () {
        this.each(function () {
            var element = $(this);

            $(window).unbind('scroll', getNextApplicationsPageEvent);
            $(window).on('scroll', { element: element }, getNextApplicationsPageEvent);
        });
    };

    $.fn.FlexPinnableBox = function () {
        this.each(function () {
            var element = $(this);

            var height = element.find('.flex-items').css('max-height').replace('px', '');

            var i = 1;
            element.find('.flex-item').each(function () {
                $(this).attr('data-flex-sort-number', i);

                i++;
            });

            element.find('.flex-items').before('<div class="flex-pinned-items"></div>');

            element.find('div.flex-item').mouseenter(function () {
                if ($(this).parent('.flex-items').length) {
                    $('.flex-oe-part .flex-items .flex-item[data-flex-image-code=' + $(this).attr('data-flex-image-code') + ']').addClass('highlighted');
                } else {
                    $('.flex-oe-part .flex-pinned-items .flex-item[data-flex-image-code=' + $(this).attr('data-flex-image-code') + ']').addClass('highlighted');
                }

                $('.image-wrapper .coord[data-number=' + $(this).attr('data-flex-image-code') + ']').addClass('highlighted');
            });

            element.find('div.flex-item').mouseleave(function () {
                if ($(this).parent('.flex-items').length) {
                    $('.flex-oe-part .flex-items .flex-item').removeClass('highlighted');
                } else {
                    $('.flex-oe-part .flex-pinned-items .flex-item').removeClass('highlighted');
                }

                $('.image-wrapper .coord').removeClass('highlighted');
            });

            element.find('div.flex-item').click(function () {
                if ($(this).parent('.flex-items').length) {
                    var elementsOuterHeight = 0;

                    $('.flex-oe-part .flex-items .flex-item[data-flex-image-code=' + $(this).attr('data-flex-image-code') + ']').each(function () {
                        elementsOuterHeight += $(this).outerHeight();
                    });

                    $('.flex-oe-part .flex-items .flex-item[data-flex-image-code=' + $(this).attr('data-flex-image-code') + ']').appendTo('.flex-pinned-items');
                    $('.image-wrapper .coord[data-number=' + $(this).attr('data-flex-image-code') + ']').addClass('selected');

                    var maxHeight = parseInt(element.find('.flex-items').css('max-height').replace('px', '')) - elementsOuterHeight;

                    if (maxHeight > (height / 2)) {
                        element.find('.flex-items').css('max-height', maxHeight + 'px');
                    } else {
                        element.find('.flex-pinned-items').css('max-height', (height / 2) + 'px');
                        element.find('.flex-items').css('max-height', (height / 2) + 'px');
                    }

                } else {
                    var elementsOuterHeight = 0;

                    $('.flex-oe-part .flex-pinned-items .flex-item[data-flex-image-code=' + $(this).attr('data-flex-image-code') + ']').each(function () {
                        elementsOuterHeight += $(this).outerHeight();
                    });

                    $('.flex-oe-part .flex-pinned-items .flex-item[data-flex-image-code=' + $(this).attr('data-flex-image-code') + ']').appendTo('.flex-items');
                    $('.image-wrapper .coord[data-number=' + $(this).attr('data-flex-image-code') + ']').removeClass('selected');

                    element.find('.flex-items .flex-item').sort(function (a, b) {
                        return +a.getAttribute('data-flex-sort-number') - +b.getAttribute('data-flex-sort-number');
                    }).appendTo('.flex-items');

                    var maxHeight = parseInt(element.find('.flex-items').css('max-height').replace('px', '')) + elementsOuterHeight;
                    var pinnedItemsHeight = 0;

                    element.find('.flex-pinned-items .flex-item').each(function () {
                        pinnedItemsHeight += $(this).outerHeight();
                    });

                    if (pinnedItemsHeight < (height / 2)) {
                        element.find('.flex-pinned-items').css('max-height', 'none');
                        element.find('.flex-items').css('max-height', height - element.find('.flex-pinned-items').outerHeight() + 'px');
                    }
                }

                $('.flex-selected-items-count').html(element.find('.flex-pinned-items .flex-item').length);

                $('.flex-selected-items-oes').html('');

                $(".flex-pinned-items .flex-item").each(function () {
                    if ($('.flex-selected-items-oes').html().length > 0) {
                        $('.flex-selected-items-oes').html($('.flex-selected-items-oes').html() + ", ");
                    }
                    $('.flex-selected-items-oes').html($('.flex-selected-items-oes').html() + $(this).find('.flex-oe .code').text());
                });
            });
        });
    };



    $.fn.FlexLevamPinnableBox = function () {
        this.each(function () {
            var element = $(this);

            var height = element.find('.flex-items').css('max-height').replace('px', '');

            var i = 1;
            element.find('.flex-item').each(function () {
                $(this).attr('data-flex-sort-number', i);

                i++;
            });

            element.find('.flex-items').before('<div class="flex-pinned-items"></div>');

            element.find('div.flex-item').mouseenter(function () {
                if ($(this).parent('.flex-items').length) {
                    $('.flex-oe-part .flex-items .flex-item[data-flex-image-code=' + $(this).attr('data-flex-image-code') + ']').addClass('highlighted');
                } else {
                    $('.flex-oe-part .flex-pinned-items .flex-item[data-flex-image-code=' + $(this).attr('data-flex-image-code') + ']').addClass('highlighted');
                }

                $('.image-wrapper .coord[data-number=' + $(this).attr('data-flex-image-code') + ']').addClass('highlighted');
            });

            element.find('div.flex-item').mouseleave(function () {
                if ($(this).parent('.flex-items').length) {
                    $('.flex-oe-part .flex-items .flex-item').removeClass('highlighted');
                } else {
                    $('.flex-oe-part .flex-pinned-items .flex-item').removeClass('highlighted');
                }

                $('.image-wrapper .coord').removeClass('highlighted');
            });

            element.find('div.flex-item').click(function () {
                if ($(this).parent('.flex-items').length) {
                    var elementsOuterHeight = 0;

                    $('.flex-oe-part .flex-items .flex-item[data-flex-image-code=' + $(this).attr('data-flex-image-code') + ']').each(function () {
                        elementsOuterHeight += $(this).outerHeight();
                    });

                    $('.flex-oe-part .flex-items .flex-item[data-flex-image-code=' + $(this).attr('data-flex-image-code') + ']').appendTo('.flex-pinned-items');
                    $('.image-wrapper .coord[data-number=' + $(this).attr('data-flex-image-code') + ']').addClass('selected');

                    var maxHeight = parseInt(element.find('.flex-items').css('max-height').replace('px', '')) - elementsOuterHeight;

                    if (maxHeight > (height / 2)) {
                        element.find('.flex-items').css('max-height', maxHeight + 'px');
                    } else {
                        element.find('.flex-pinned-items').css('max-height', (height / 2) + 'px');
                        element.find('.flex-items').css('max-height', (height / 2) + 'px');
                    }

                } else {
                    var elementsOuterHeight = 0;

                    $('.flex-oe-part .flex-pinned-items .flex-item[data-flex-image-code=' + $(this).attr('data-flex-image-code') + ']').each(function () {
                        elementsOuterHeight += $(this).outerHeight();
                    });

                    $('.flex-oe-part .flex-pinned-items .flex-item[data-flex-image-code=' + $(this).attr('data-flex-image-code') + ']').appendTo('.flex-items');
                    $('.image-wrapper .coord[data-number=' + $(this).attr('data-flex-image-code') + ']').removeClass('selected');

                    element.find('.flex-items .flex-item').sort(function (a, b) {
                        return +a.getAttribute('data-flex-sort-number') - +b.getAttribute('data-flex-sort-number');
                    }).appendTo('.flex-items');

                    var maxHeight = parseInt(element.find('.flex-items').css('max-height').replace('px', '')) + elementsOuterHeight;
                    var pinnedItemsHeight = 0;

                    element.find('.flex-pinned-items .flex-item').each(function () {
                        pinnedItemsHeight += $(this).outerHeight();
                    });

                    if (pinnedItemsHeight < (height / 2)) {
                        element.find('.flex-pinned-items').css('max-height', 'none');
                        element.find('.flex-items').css('max-height', height - element.find('.flex-pinned-items').outerHeight() + 'px');
                    }
                }

                $('.flex-selected-items-count').html(element.find('.flex-pinned-items .flex-item').length);

                $('.flex-selected-items-oes').html('');

                $(".flex-pinned-items .flex-item").each(function () {
                    if ($('.flex-selected-items-oes').html().length > 0) {
                        $('.flex-selected-items-oes').html($('.flex-selected-items-oes').html() + ", ");
                    }
                    $('.flex-selected-items-oes').html($('.flex-selected-items-oes').html() + $(this).find('.flex-oe .code').text());
                });
            });
        });
    };



    $.fn.FlexSameHeightContainer = function () {
        this.each(function () {
            var element = $(this);

            var highestBox = 0;

            element.find('.flex-item').each(function () {
                $(this).css('height', 'auto');
                if ($(this).outerHeight() > highestBox) {
                    highestBox = $(this).outerHeight();
                }
            });

            element.find('.flex-item').each(function () {
                $(this).css('height', highestBox + 'px');
            });
        });
    };

    $.fn.FlexAddToLicensePlate = function () {
        this.each(function () {
            var element = $(this);

            element.find('.flex-add-to-license-plate-form-container').each(function () {
                $(this).css('width', $(window).width() + 'px');
                $(this).css('height', $(window).height() + 'px');
            });

            element.find('.flex-add-to-license-plate-form').each(function () {
                $(this).css('top', ($(window).height() - $(this).outerHeight()) / 2 + 'px');
                $(this).css('left', ($(window).width() - $(this).outerWidth()) / 2 + 'px');
            });
        });
    };

    /*$.fn.FlexShare = function () {
        this.each(function () {
            var element = $(this);

            element.find('.flex-share-form-container').each(function () {
                $(this).css('width', $(window).width() + 'px');
                $(this).css('height', $(window).height() + 'px');
            });

            element.find('.flex-share-form').each(function () {
                $(this).css('top', ($(window).height() - $(this).outerHeight()) / 2 + 'px');
                $(this).css('left', ($(window).width() - $(this).outerWidth()) / 2 + 'px');
            });
        });
    };*/

    $.fn.FlexOverdueInvoicesModalPopup = function () {
        this.each(function () {
            var element = $(this);

            if ($.cookie('OverdueInvoicesAlertHiddenConfirmed') != 'true') {
                $('.flex-overdue-invoices-container').fadeIn(600);
                $('.flex-overdue-invoices').fadeIn(600);

                element.find('.flex-overdue-invoices-container').each(function () {
                    $(this).css('width', $(window).width() + 'px');
                    $(this).css('height', $(window).height() + 'px');
                });

                element.find('.flex-overdue-invoices').each(function () {
                    $(this).css('top', ($(window).height() - $(this).outerHeight()) / 2 + 'px');
                    $(this).css('left', ($(window).width() - $(this).outerWidth()) / 2 + 'px');
                });

                element.find('input[type="button"]').on('click', function (e) {
                    $.cookie('OverdueInvoicesAlertHiddenConfirmed', 'true', { expires: 1 });
                });
            }
        });
    };

    $.fn.FlexModalPopup = function () {
        this.each(function () {
            var element = $(this);

            if ($.cookie(element.attr('id') + '_Confirmed') != 'true') {
                var overlay = element.find('.overlay');
                var container = element.find('.container');

                overlay.css('width', $(window).width() + 'px');
                overlay.css('height', $(window).height() + 'px');
                overlay.fadeIn(600);

                container.css('top', ($(window).height() - container.outerHeight()) / 2 + 'px');
                container.css('left', ($(window).width() - container.outerWidth()) / 2 + 'px');
                container.fadeIn(600);

                element.find('.close').on('click', function (e) {
                    $.cookie(element.attr('id') + '_Confirmed', 'true', { expires: 1 });

                    overlay.fadeOut(600);
                    container.fadeOut(600);
                });

                element.find('.confirm').on('click', function (e) {
                    $.cookie(element.attr('id') + '_Confirmed', 'true', { expires: 1 });
                });
            }
        });
    };

    $.fn.FlexCustomModalPopup = function () {
        this.each(function () {
            var element = $(this);

            if ($.cookie('IsCustomModalPopupHidden') != 'true') {
                $('.flex-custom-popup-container').fadeIn(600);
                $('.flex-custom-popup').fadeIn(600);

                element.find('.flex-custom-popup-container').each(function () {
                    $(this).css('width', $(window).width() + 'px');
                    $(this).css('height', $(window).height() + 'px');
                });

                element.find('.flex-custom-popup').each(function () {

                    var windowHeight = $(window).height();
                    var windowWidth = $(window).width();

                    var popupOuterHeight = $(this).outerHeight(true);
                    var popupOuterWidth = $(this).outerWidth(true);

                    var popupBorders = (parseInt($(this).css('paddingLeft')) * 2) + (parseInt($(this).css('marginLeft')) * 2) + (parseInt($(this).css('borderLeftWidth')) * 2) + 20;
                    //var popupBorders = (parseInt($(this).css('padding')) * 2) + (parseInt($(this).css('margin')) * 2) + (parseInt($(this).css('border-width')) * 2) + 20;

                    var top = (windowHeight - popupBorders - popupOuterHeight) / 2;
                    var left = (windowWidth - popupBorders - popupOuterWidth) / 2;

                    if (top < 0)
                        top = 10;
                    if (left < 0)
                        left = 10;

                    $(this).css('top', top + 'px');
                    $(this).css('left', left + 'px');


                    if ((windowHeight - popupBorders) < popupOuterHeight) {

                        $(this).css('height', (windowHeight - popupBorders) + 'px');
                        $(this).find(".custom-popup-wrapper").css('height', (windowHeight - popupBorders) + 'px');
                        $(this).find(".custom-popup-wrapper").css('overflow-x', 'auto');
                    }
                    if ((windowWidth - popupBorders) < popupOuterWidth) {

                        $(this).css('width', (windowWidth - popupBorders) + 'px');
                        $(this).find(".custom-popup-wrapper").css('width', (windowWidth - popupBorders - 15) + 'px');
                        $(this).find(".custom-popup-wrapper").css('overflow', 'auto');
                    }

                });

                element.find('input[type="button"]').on('click', function (e) {
                    $.cookie('IsCustomModalPopupHidden', 'true', { expires: 7 });
                });
            }
        });
    };

    $.fn.FlexProgressBar = function () {
        this.each(function () {
            var element = $(this);

            var totalNumber = parseFloat($(this).attr('data-flex-total-number'));
            var partNumber = parseFloat($(this).attr('data-flex-part-number'));

            var highlightWidth = Math.round((partNumber / (totalNumber / 100)) * (element.width() / 100));

            element.append('<div class="flex-highlight"></div>');

            element.find('.flex-highlight').animate({
                width: highlightWidth
            }, 1000, 'easeOutBounce');

            $(window).on('resize', function () {
                var totalNumber = parseFloat(element.attr('data-flex-total-number'));
                var partNumber = parseFloat(element.attr('data-flex-part-number'));

                var highlightWidth = Math.round((partNumber / (totalNumber / 100)) * (element.width() / 100));

                element.find('.flex-highlight').css('width', highlightWidth);
            });
        });

    };






    $.fn.FlexGauge = function () {
        this.each(function () {
            var element = $(this);

            var circleDiameter = $(this).attr('data-flex-circle-diameter');
            var lineStroke = 9;
            var backgroundColor = '#50c14e';
            var hightlightColor = '#5093e1';
            var totalNumber = $(this).attr('data-flex-total-number');
            var partNumber = $(this).attr('data-flex-part-number');

            element.append('<canvas width=\"' + circleDiameter + '\" height=\"' + circleDiameter + '\"></canvas>');

            var canvas = element.find("canvas");
            var ctx = canvas.get(0).getContext("2d");

            // Background 360 degree arc.
            ctx.beginPath();
            ctx.strokeStyle = backgroundColor;
            ctx.lineWidth = lineStroke;
            ctx.arc(canvas.width() / 2, canvas.height() / 2, (circleDiameter / 2) - (lineStroke / 2), 0, Math.PI * 2, false);
            ctx.stroke();

            // Angle in radians = angle in degrees * PI / 180.
            var radians = (partNumber / (totalNumber / 100) * 3.6) * Math.PI / 180;
            ctx.beginPath();
            ctx.strokeStyle = hightlightColor;
            ctx.lineWidth = lineStroke;

            ctx.arc(canvas.width() / 2, canvas.height() / 2, (circleDiameter / 2) - (lineStroke / 2), 0 - 90 * Math.PI / 180, radians - 90 * Math.PI / 180, false);

            ctx.stroke();
        });
    };

    $.fn.scrollTo = function () {
        var elementPosition = this.offset().top;
        var screenScrollPosition = $(window).scrollTop();
        if (elementPosition < screenScrollPosition) {
            $('html, body').animate({
                scrollTop: this.offset().top
            }, 250);
        }
    };

    $.fn.scrollTo = function (speed) {
        var elementPosition = this.offset().top;
        var screenScrollPosition = $(window).scrollTop();
        if (elementPosition < screenScrollPosition) {
            $('html, body').animate({
                scrollTop: this.offset().top
            }, speed);
        }
    };

    $.fn.FlexLevamModelSelectionHistory = function () {
        this.each(function () {
            $(window).on('popstate load', function () {
                var ssd = getUrlHistoryValue('ssd');

                if (ssd) {
                    getLevamVehiclesByModel('.vehicles-list', ssd, null);
                } else {
                    $('.flex-laximo .vehicles-list').html('');
                }
            });
        });
    };

    $.fn.FlexLevamVehicleDetailHistory = function () {
        this.each(function () {
            $(window).on('popstate load', function () {

                var defaultTab = $('.flex-tabs').attr('data-default-tab-id');
                var selectedTab = getUrlHistoryValue('selected-tab');
                var nodesPath = getUrlHistoryValue('nodes-path');

                $('.flex-tabs a').attr('data-store-history', 'false');

                if (selectedTab && selectedTab != $('.flex-tabs a.flex-selected').attr('id')) {
                    $('#' + selectedTab).click();
                } else if (!selectedTab && !nodesPath) {
                    $('#' + defaultTab).click();
                }
            });

            //$(window).on('load', function () {
            //    var defaultTab = $('.flex-tabs').attr('data-default-tab-id');
            //    var selectedTab = getUrlHistoryValue('selected-tab');
            //    var nodesPath = getUrlHistoryValue('nodes-path');

            //    $('.flex-tabs a').attr('data-store-history', 'false');

            //    if (selectedTab && selectedTab !== $('.flex-tabs a.flex-selected').attr('id')) {
            //        $('#' + selectedTab).click();
            //    }
            //});
        });
    };

    $.fn.FlexConditionalItems = function () {
        this.each(function () {
            var element = $(this);
            element.find('.title').click(function (e) {
                e.stopImmediatePropagation();
                if (!$(e.target).hasClass('flex-checkbox') && !$(e.target).hasClass('flex-checkbox-toogle-text')) {
                    if ($(this).hasClass('selected')) {
                        var title = $(this);
                        $(this).parents('.item').find('.details').slideUp(400, 'easeInBack', function () {
                            title.removeClass('selected');
                        });
                    } else {
                        $(this).parents('.item').find('.details').slideDown({ duration: 600, easing: 'easeOutExpo' });
                        $(this).addClass('selected');
                    }
                }
            });
        });
    };

    $.fn.FlexTransportMethods = function () {
        this.each(function () {
            var element = $(this);
            var inputID = $('input[name=TransportMethod]:checked').attr("value");
            $('li[data-target-input-id="TranportMethod' + inputID + '"] .flex-text-wrapper').after($('#TransportMethodDescription' + inputID));

            $('#TransportMethodDescription' + inputID).show(0);

            if ($('input[name=TransportMethod]:checked').attr("data-flex-is-zasilkovna") === "true") {
                $('#FormZasilkovna').slideDown({ duration: 600, easing: 'easeOutExpo' });
            }
            else {
                $('#FormZasilkovna').slideUp({ duration: 400, easing: 'easeInBack' });
            }

            if ($('input[name=TransportMethod]:checked').attr("data-flex-is-personal-pick") === "true") {
                $('#FormPersonalPick').slideDown({ duration: 600, easing: 'easeOutExpo' });
            }
            else {
                $('#FormPersonalPick').slideUp({ duration: 400, easing: 'easeInBack' });
            }

            if ($('input[name=TransportMethod]:checked').attr("data-flex-is-balikovna") === "true") {
                $('#FormBalikovna').slideDown({ duration: 600, easing: 'easeOutExpo' });
            }
            else {
                $('#FormBalikovna').slideUp({ duration: 400, easing: 'easeInBack' });
            }

            if ($('input[name=TransportMethod]:checked').attr("data-flex-is-dpd") === "true") {
                $('#FormDpd').slideDown({ duration: 600, easing: 'easeOutExpo' });
            }
            else {
                $('#FormDpd').slideUp({ duration: 400, easing: 'easeInBack' });
            }

            if ($('input[name=TransportMethod]:checked').attr("data-flex-is-ppl") === "true") {
                $('#FormPpl').slideDown({ duration: 600, easing: 'easeOutExpo' });
            }
            else {
                $('#FormPpl').slideUp({ duration: 400, easing: 'easeInBack' });
            }

            if ($('input[name=TransportMethod]:checked').attr("data-flex-is-gls") === "true") {
                $('#FormGls').slideDown({ duration: 600, easing: 'easeOutExpo' });
            }
            else {
                $('#FormGls').slideUp({ duration: 400, easing: 'easeInBack' });
            }

            if ($('input[name=TransportMethod]:checked').attr("data-flex-is-wedo") === "true") {
                $('#FormWeDo').slideDown({ duration: 600, easing: 'easeOutExpo' });
            }
            else {
                $('#FormWeDo').slideUp({ duration: 400, easing: 'easeInBack' });
            }

            if ($('input[name=TransportMethod]:checked').attr("data-flex-is-package-to-post") === "true") {
                $('#FormPackageToPost').slideDown({ duration: 600, easing: 'easeOutExpo' });
            }
            else {
                $('#FormPackageToPost').slideUp({ duration: 400, easing: 'easeInBack' });
            }

            if ($('input[name=TransportMethod]:checked').attr("data-flex-is-paczkomat") === "true") {
                $('#FormPaczkomatInPost').slideDown({ duration: 600, easing: 'easeOutExpo' });
            }
            else {
                $('#FormPaczkomatInPost').slideUp({ duration: 400, easing: 'easeInBack' });
            }

            element.find('input[name=TransportMethod]').change(function (e) {
                var inputID = $(this).attr("value");
                $('li[data-target-input-id="TranportMethod' + inputID + '"] .flex-text-wrapper').append($('#TransportMethodDescription' + inputID));

                $('.transport-method-description').slideUp({ duration: 400, easing: 'easeInBack' });

                $('#TransportMethodDescription' + inputID).slideDown({ duration: 600, easing: 'easeOutExpo' });

                if ($(this).attr("data-flex-is-zasilkovna") === "true") {
                    $('#FormZasilkovna').slideDown({ duration: 600, easing: 'easeOutExpo' });
                }
                else {
                    $('#FormZasilkovna').slideUp({ duration: 400, easing: 'easeInBack' });
                }

                if ($(this).attr("data-flex-is-personal-pick") === "true") {
                    $('#FormPersonalPick').slideDown({ duration: 600, easing: 'easeOutExpo' });
                }
                else {
                    $('#FormPersonalPick').slideUp({ duration: 400, easing: 'easeInBack' });
                }

                if ($(this).attr("data-flex-is-balikovna") === "true") {
                    $('#FormBalikovna').slideDown({ duration: 600, easing: 'easeOutExpo' });
                }
                else {
                    $('#FormBalikovna').slideUp({ duration: 400, easing: 'easeInBack' });
                }

                if ($(this).attr("data-flex-is-dpd") === "true") {
                    $('#FormDpd').slideDown({ duration: 600, easing: 'easeOutExpo' });
                }
                else {
                    $('#FormDpd').slideUp({ duration: 400, easing: 'easeInBack' });
                }

                if ($(this).attr("data-flex-is-ppl") === "true") {
                    $('#FormPpl').slideDown({ duration: 600, easing: 'easeOutExpo' });
                }
                else {
                    $('#FormPpl').slideUp({ duration: 400, easing: 'easeInBack' });
                }

                if ($(this).attr("data-flex-is-gls") === "true") {
                    $('#FormGls').slideDown({ duration: 600, easing: 'easeOutExpo' });
                }
                else {
                    $('#FormGls').slideUp({ duration: 400, easing: 'easeInBack' });
                }

                if ($(this).attr("data-flex-is-wedo") === "true") {
                    $('#FormWeDo').slideDown({ duration: 600, easing: 'easeOutExpo' });
                }
                else {
                    $('#FormWeDo').slideUp({ duration: 400, easing: 'easeInBack' });
                }

                if ($(this).attr("data-flex-is-package-to-post") === "true") {
                    $('#FormPackageToPost').slideDown({ duration: 600, easing: 'easeOutExpo' });
                }
                else {
                    $('#FormPackageToPost').slideUp({ duration: 400, easing: 'easeInBack' });
                }

                if ($(this).attr("data-flex-is-paczkomat") === "true") {
                    $('#FormPaczkomatInPost').slideDown({ duration: 600, easing: 'easeOutExpo' });
                }
                else {
                    $('#FormPaczkomatInPost').slideUp({ duration: 400, easing: 'easeInBack' });
                }
            });

            element.find('.transport-method-description').click(function (e) {
                e.stopPropagation();
            });
        });

        var transportMethods = $('#TransportMethods_FlexRadioButtons');
        if (transportMethods) {
            $('#TransportMethods_FlexRadioButtons li.flex-selected').click();
        }
    };

    $.fn.FlexProducts = function () {
        $(window).on('popstate', function (event) {
            var executableFunction = new Function($('.products-list').attr('data-flex-refresh-event'));
            executableFunction();
        });

        $(window).scroll(function () {
            if ($('#PageScrollTop')) {
                //$('#PageScrollTop').val($(this).scrollTop());
            }
        });
    };

    $.fn.FlexZasilkovnaBranchPosition = function () {
        this.each(function () {
            let elements = $('input[name=TransportMethod][data-flex-is-zasilkovna=true]');

            if (elements.length === 0) {
                return;
            }

            for (let i = 0; i < elements.length; i++) {
                let inputID = $(elements[i]).attr("id");
                if (inputID !== undefined) {
                    $('li[data-target-input-id="' + inputID + '"]').append($("#FormZasilkovna_" + $(elements[i]).attr("value")));
                }
            }
        });
    };

    $.fn.FlexBalikovnaBranchPosition = function () {
        this.each(function () {
            let elements = $('input[name=TransportMethod][data-flex-is-balikovna=true]');

            if (elements.length === 0) {
                return;
            }

            for (let i = 0; i < elements.length; i++) {
                let inputID = $(elements[i]).attr("id");
                if (inputID !== undefined) {
                    $('li[data-target-input-id="' + inputID + '"]').append($("#FormBalikovna_" + $(elements[i]).attr("value")));
                }
            }
        });
    };

    $.fn.FlexDpdBranchPosition = function () {
        this.each(function () {
            let elements = $('input[name=TransportMethod][data-flex-is-dpd=true]');

            if (elements.length === 0) {
                return;
            }

            for (let i = 0; i < elements.length; i++) {
                let inputID = $(elements[i]).attr("id");
                if (inputID !== undefined) {
                    $('li[data-target-input-id="' + inputID + '"]').append($("#FormDpd_" + $(elements[i]).attr("value")));
                }
            }
        });
    };

    $.fn.FlexPplBranchPosition = function () {
        this.each(function () {
            let elements = $('input[name=TransportMethod][data-flex-is-ppl=true]');

            if (elements.length === 0) {
                return;
            }

            for (let i = 0; i < elements.length; i++) {
                let inputID = $(elements[i]).attr("id");
                if (inputID !== undefined) {
                    $('li[data-target-input-id="' + inputID + '"]').append($("#FormPpl_" + $(elements[i]).attr("value")));
                }
            }
        });
    };

    $.fn.FlexGlsBranchPosition = function () {
        this.each(function () {
            let elements = $('input[name=TransportMethod][data-flex-is-gls=true]');

            if (elements.length === 0) {
                return;
            }

            for (let i = 0; i < elements.length; i++) {
                let inputID = $(elements[i]).attr("id");
                if (inputID !== undefined) {
                    $('li[data-target-input-id="' + inputID + '"]').append($("#FormGls_" + $(elements[i]).attr("value")));
                }
            }
        });
    };

    $.fn.FlexWeDoBranchPosition = function () {
        this.each(function () {
            let elements = $('input[name=TransportMethod][data-flex-is-wedo=true]');

            if (elements.length === 0) {
                return;
            }

            for (let i = 0; i < elements.length; i++) {
                let inputID = $(elements[i]).attr("id");
                if (inputID !== undefined) {
                    $('li[data-target-input-id="' + inputID + '"]').append($("#FormWeDo_" + $(elements[i]).attr("value")));
                }
            }
        });
    };

    $.fn.FlexPackageToPostBranchPosition = function () {
        this.each(function () {
            let elements = $('input[name=TransportMethod][data-flex-is-package-to-post=true]');

            if (elements.length === 0) {
                return;
            }

            for (let i = 0; i < elements.length; i++) {
                let inputID = $(elements[i]).attr("id");
                if (inputID !== undefined) {
                    $('li[data-target-input-id="' + inputID + '"]').append($("#FormPackageToPost_" + $(elements[i]).attr("value")));
                }
            }
        });
    };

    $.fn.FlexPaczkomatBranchPosition = function () {
        this.each(function () {
            let elements = $('input[name=TransportMethod][data-flex-is-paczkomat=true]');

            if (elements.length === 0) {
                return;
            }

            for (let i = 0; i < elements.length; i++) {
                let inputID = $(elements[i]).attr("id");
                if (inputID !== undefined) {
                    $('li[data-target-input-id="' + inputID + '"]').append($("#FormPaczkomatInPost_" + $(elements[i]).attr("value")));
                }
            }
        });
    };

    $.fn.FlexPersonalPickBranchPosition = function () {
        this.each(function () {
            let elements = $('input[name=TransportMethod][data-flex-is-personal-pick=true]');

            if (elements.length === 0) {
                return;
            }

            for (let i = 0; i < elements.length; i++) {
                let inputID = $(elements[i]).attr("id");
                if (inputID !== undefined) {
                    $('li[data-target-input-id="' + inputID + '"]').append($("#FormPersonalPick_" + $(elements[i]).attr("value")));
                }
            }
        });
    };

    $.fn.SelectUniversalPartsCategoryWizard = function () {
        this.each(function () {
            var element = $(this);

            var rootCategoryID = element.find('.root-category').attr("data-root-category-id");

            element.on('change', '.flex-drop-down', function (e) {
                var categoryID = $(this).attr("data-category-id");

                var arg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1;

                var autoFill = arg == true;

                if (categoryID != undefined)
                    getSelectUniversalPartsCategoryWizardStep('.select-universal-parts-category-wizard #RootCategory_' + rootCategoryID, categoryID, rootCategoryID, autoFill);
            });

            var idsPath = getUrlHistoryValue('path');
            var expandWizardCategoryIds = getUrlHistoryValue('expand-wizard');

            if (idsPath != false) {
                var idsPathSplitted = idsPath.split('~');

                $('#Category_' + idsPathSplitted[0] + '_FlexDropDown dd .flex-drop-down-link[data-value="' + idsPathSplitted[1] + '"]').trigger('click', true);
            }

            if (expandWizardCategoryIds != false) {
                var expandWizardCategoryIdsSplitted = expandWizardCategoryIds.split('~');

                $('#Category_' + expandWizardCategoryIdsSplitted[0] + '_FlexDropDown dd .flex-drop-down-link[data-value="' + expandWizardCategoryIdsSplitted[1] + '"]').trigger('click');
            }
        });
    };

    //Existuje stejna funkce ve FlexViewOther.js
    //getUrlHistoryValue = function (name) {
    //    var startIndex = window.location.href.indexOf(name) + name.length;
    //    var value = window.location.href.substring(startIndex, window.location.href.length);

    //    return decodeURIComponent(value.split('&')[0]);
    //}

    flexMandatoryField = function () {
        var element = $(this);

        $(document).on('change', '*[data-flex-mandatory="true"]', function () {
            if ($(this).val() != '') {
                $(this).attr('data-flex-empty', false);
            }
        });

        $(document).on('input', '*[data-flex-mandatory="true"]', function () {
            if ($(this).val() != '') {
                $(this).attr('data-flex-empty', false);
            }
        });

        $(document).on('focus', '*[data-flex-mandatory="true"]', function () {
            if ($(this).val() != '') {
                $(this).attr('data-flex-empty', false);
            }
        });

        $(document).on('click', '*[data-flex-mandatory="true"] + dl.flex-drop-down', function () {
            var select = $('select[for=\"' + $(this).attr('id') + '\"]');
            if (select.val() > -1) {
                select.attr('data-flex-empty', false);
            }
        });
    };

    changeCheckOnEmpty = function (inputID, checkBoxID) {
        var input = $(inputID);
        var checkBox = $(checkBoxID);
        var value = input.val();
        if (value === "") {
            checkBox.prop('checked', false).change();
        } else {
            checkBox.prop('checked', true).change();
        }
    }

    flexInvoiceSearchBar = function () {
        var enableCollapse = true;

        var edited = false;

        $(document).on('focusin', '.flex-invoice-search', function () {
            $(this).find('.flex-invoice-search-whisperer').slideDown({ duration: 600, easing: 'easeOutExpo' });
            $(this).find('.flex-invoice-search-whisperer .flex-invoice-items').show(0);
            //element.find('.flex-invoice-search-whisperer .flex-filters').show(0);

            //if (element.find('.flex-invoice-search-whisperer').attr('data-search-type') === 1) {
            //    element.find('.flex-invoice-search-whisperer').slideDown({ duration: 600, easing: 'easeOutBounce' });
            //} else if (element.find('.flex-invoice-search-whisperer').attr('data-search-type') === 4) {
            //    element.find('.flex-invoice-search-whisperer .flex-filters').hide(0);
            //    element.find('.flex-invoice-search-whisperer').slideDown({ duration: 600, easing: 'easeOutBounce' });
            //} else if (element.find('.flex-invoice-search-whisperer').attr('data-search-type') === 5) {
            //    element.find('.flex-invoice-search-whisperer .flex-filters').hide(0);
            //} else {
            //    element.find('.flex-invoice-search-whisperer').slideUp({ duration: 400, easing: 'easeInBack' });
            //}
        });

        //  element.find('input[type="text"]').on('focusout', function () {
        //      if (element.find('.flex-invoice-search-input input:text').val() === '')
        //          edited = false;
        //  });

        $(document).bind('click', function (e) {
            var clicked = $(e.target);

            if (enableCollapse) {
                if (!clicked.parents().hasClass("flex-invoice-search-input")) {
                    $(".flex-invoice-search").find('.flex-invoice-search-whisperer').slideUp({ duration: 400, easing: 'easeInBack' });
                }

                if (!clicked.parents().hasClass("flex-invoice-history-wrapper") && !clicked.hasClass("flex-invoice-history-wrapper") && !clicked.hasClass("flex-show-all-button")) {
                    $(".flex-invoice-search").find('.flex-invoice-history-wrapper').slideUp({ duration: 400, easing: 'easeInBack' });
                }
            }

            enableCollapse = true;
        });
    };

    flexDeliveryNoteSearchBar = function () {
        var enableCollapse = true;

        var edited = false;

        $(document).on('focusin', '.flex-delivery-note-search', function () {
            $(this).find('.flex-delivery-note-search-whisperer').slideDown({ duration: 600, easing: 'easeOutExpo' });
            $(this).find('.flex-delivery-note-search-whisperer .flex-delivery-note-items').show(0);
            //element.find('.flex-invoice-search-whisperer .flex-filters').show(0);

            //if (element.find('.flex-invoice-search-whisperer').attr('data-search-type') === 1) {
            //    element.find('.flex-invoice-search-whisperer').slideDown({ duration: 600, easing: 'easeOutBounce' });
            //} else if (element.find('.flex-invoice-search-whisperer').attr('data-search-type') === 4) {
            //    element.find('.flex-invoice-search-whisperer .flex-filters').hide(0);
            //    element.find('.flex-invoice-search-whisperer').slideDown({ duration: 600, easing: 'easeOutBounce' });
            //} else if (element.find('.flex-invoice-search-whisperer').attr('data-search-type') === 5) {
            //    element.find('.flex-invoice-search-whisperer .flex-filters').hide(0);
            //} else {
            //    element.find('.flex-invoice-search-whisperer').slideUp({ duration: 400, easing: 'easeInBack' });
            //}
        });

        //  element.find('input[type="text"]').on('focusout', function () {
        //      if (element.find('.flex-invoice-search-input input:text').val() === '')
        //          edited = false;
        //  });

        // element.find('.flex-invoice-search-input input[type="text"]').on('keypress', function (e) {
        //     edited = true;
        //
        //     if (e.which === 13) {
        //         element.find('.flex-invoice-search-input input[type="button"]').click();
        //         return false;
        //     }
        // });

        $(document).bind('click', function (e) {
            var clicked = $(e.target);

            if (enableCollapse) {
                if (!clicked.parents().hasClass("flex-delivery-note-search-input")) {
                    $(".flex-delivery-note-search").find('.flex-delivery-note-search-whisperer').slideUp({ duration: 400, easing: 'easeInBack' });
                }

                if (!clicked.parents().hasClass("flex-delivery-note-history-wrapper") && !clicked.hasClass("flex-delivery-note-history-wrapper") && !clicked.hasClass("flex-show-all-button")) {
                    $(".flex-delivery-note-search").find('.flex-delivery-note-history-wrapper').slideUp({ duration: 400, easing: 'easeInBack' });
                }
            }

            enableCollapse = true;
        });
    };

    getGuid = function () {
        var guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });

        return guid;
    }

    safeUrlEncode = function (text) {
        if (text == undefined)
            text = "";
        text = text.replace(new RegExp("/", "g"), "-c47-").replace(new RegExp("\\\\", "g"), "-c92-").replace(new RegExp("\\.", "g"), "-c46-").replace(new RegExp("#", "g"), "-c35-").replace(new RegExp("\\*", "g"), "-c42-").replace(new RegExp("\\?", "g"), "-c63-").replace(new RegExp(":", "g"), "-c58-").replace(new RegExp("&", "g"), "-c38-").replace(new RegExp("<", "g"), "-c60-").replace(new RegExp(">", "g"), "-c62-").replace(new RegExp("\\+", "g"), "-c43-").replace(new RegExp("\"", "g"), "-c34-").replace(new RegExp("%", "g"), "-c37-").replace(new RegExp("	", "g"), "-c9-").replace(new RegExp("\\(", "g"), "-c40-").replace(new RegExp("\\)", "g"), "-c41-").replace(new RegExp("\\$", "g"), "-c36-").replace(new RegExp("¦", "g"), "-c166-").replace(new RegExp("'", "g"), "-c39-");
        return encodeURIComponent(text);
    }

    safeUrlDecode = function (text, isHtmlSave) {
        text = decodeURIComponent(text);

        isHtmlSave = isHtmlSave || false;
        if (isHtmlSave)
            text = text.replace(new RegExp("-c60-", "g"), "&lt;").replace(new RegExp("-c62-", "g"), "&gt;").Replace(new RegExp("-c34-", "g"), "&quot;");

        return text.replace(new RegExp("-c47-", "g"), "/").replace(new RegExp("-c92-", "g"), "\\\\").replace(new RegExp("-c46-", "g"), ".").replace(new RegExp("-c35-", "g"), "#").replace(new RegExp("-c42-", "g"), "*").replace(new RegExp("-c63-", "g"), "?").replace(new RegExp("-c58-", "g"), ":").replace(new RegExp("-c38-", "g"), "&").replace(new RegExp("-c60-", "g"), "<").replace(new RegExp("-c62-", "g"), ">").replace(new RegExp("-c43-", "g"), "+").replace(new RegExp("-c34-", "g"), "\"").replace(new RegExp("-c37-", "g"), "%").replace(new RegExp("-c9-", "g"), "	").replace(new RegExp("-c40-", "g"), "(").replace(new RegExp("-c41-", "g"), ")").replace(new RegExp("-c36-", "g"), "\\$").replace(new RegExp("-c166-", "g"), "¦").replace(new RegExp("-c39-", "g"), "'");
    }

    flexShowToastInfo = function (text, isLinkEnabled, link, linkText) {
        var timeout = $('body').attr('data-flex-toast-timeout');

        var guid = getGuid();

        $('.flex-toast-info').remove();

        if (timeout > -1) {

            if (link != null && link.length > 0) {
                //if (Array.isArray(link)) {
                var element = '<div id="' + guid + '" class="flex-toast-info"><div class="flex-toast-info-content">' + text;

                for (var i = 0; i < link.length; i++) {
                    element += '<a class="flex-go-to-link-' + i + '" onclick="goToOrder(\'' + link[i] + '\')" style="cursor: pointer">' + linkText[i] + '</a>';
                }

                element += '</div>';
                $('body').append(element);

                /*else {
                    $('body').append('<div id="' + guid + '" class="flex-toast-info"><div class="flex-toast-info-content">' + text + '<a href="' + link + '" class=\"flex-go-to-basket\">' + (linkText === null ? '' : linkText) + '</a></div></div>');
                }*/
            }
            else
                $('body').append('<div id="' + guid + '" class="flex-toast-info">' + text + '</div>');

            setTimeout(function () {
                $('#' + guid).fadeOut(600, function () {
                    $('#' + guid).remove();
                });
            }, timeout);
        }
        else {

            if (link.length > 0) {
                if (Array.isArray(link)) {
                    var element = '<div id="' + guid + '" class="flex-toast-info"><div class="flex-toast-info-content">' + text;

                    for (var i = 0; i < link.length; i++) {
                        element += '<a href="' + link[i] + '" class=\"flex-go-to-link-' + i + '\">' + (linkText[i] == null ? '' : linkText[i]) + '</a>';

                    }
                    element += '</div>';
                    $('body').append(element);
                }
                /* }
                 else {
                     $('body').append('<div id="' + guid + '" class="flex-toast-info"><div class="flex-toast-info-content">' + text + '<a href="' + link + '" class=\"flex-go-to-basket\">' + (linkText === null ? '' : linkText) + '</a></div></div>');
                 }*/

                else {
                    $('body').append('<div id="' + guid + '" class="flex-toast-info">' + text + '<input type="button" class="flex-close-toast-button" value="" /></div>');
                }
            }
            else
                $('body').append('<div id="' + guid + '" class="flex-toast-info">' + text + '</div>');

            $('#' + guid + ' .flex-close-toast-button').on('click', function () {
                $('#' + guid).fadeOut(600, function () {
                    $('#' + guid).remove();
                });
            });
        }
    }

    flexShowToastError = function (text) {
        var timeout = $('body').attr('data-flex-toast-timeout');

        var guid = getGuid();

        $('.flex-toast-error').remove();

        if (timeout > -1) {
            $('body').append('<div id="' + guid + '" class="flex-toast-error">' + text + '</div>');

            setTimeout(function () {
                $('#' + guid).fadeOut(600, function () {
                    $('#' + guid).remove();
                });
            }, 4000);
        } else {
            $('body').append('<div id="' + guid + '" class="flex-toast-error">' + text + '<input type="button" class="flex-close-toast-button" value="" /></div>');

            $('#' + guid + ' .flex-close-toast-button').on('click', function () {
                $('#' + guid).fadeOut(600, function () {
                    $('#' + guid).remove();
                });
            });
        }
    }

    /*
     * Validates elements provided and scrolls to the highest one. Only enabled and visible elements are checked
     */
    validateForm = function (elements, scrollToElements) {
        //default values
        scrollToElements = scrollToElements || true;

        var formValid = true;
        var controlToScroll = null;
        var peak = Number.MAX_VALUE;

        $.each(elements, function () {
            this.attr('data-flex-empty', false);
            if (!this.prop('disabled') && this.data('flex-mandatory')) {
                if (this.isEmpty(scrollToElements)) {
                    formValid = false;
                    var element = this;
                    if (this.is('select')) {
                        element = $('#' + this.attr('for'));
                    }
                    if (element.offset().top < peak) {
                        peak = element.offset().top;
                        controlToScroll = element;
                    }
                }
            }
        });

        if (controlToScroll != null) {
            controlToScroll.scrollTo();
        }

        return formValid;
    }

    invoiceSearchSetSelectedInvoice = function (inputElement, hiddenInputElement, invoiceNumber, invoiceID) {
        $(inputElement).changeVal(invoiceNumber);
        $(hiddenInputElement).changeVal(invoiceID);
        $('.flex-invoice-search-whisperer').hide();
    }

    getInvoiceSearchWhispers = function (loadOverlayPlaceholder, inputElement) {
        var parent = $(inputElement).parent('.flex-invoice-search-input');
        var searchPhrase = $(inputElement).val().toLowerCase();
        var found = false;
        parent.find('.flex-invoice-items a').each(function () {
            var value = $(this).find('span.flex-invoice-number').text().toLowerCase();
            if (value.indexOf(searchPhrase) > -1) {
                $(this).show();
                found = true;
            } else {
                $(this).hide();
            }
        });
        if (found) {
            parent.find('.flex-invoice-items span.flex-invoice-no-items').hide();
        } else {
            parent.find('.flex-invoice-items span.flex-invoice-no-items').show();
        }
    }

    deliveryNoteSearchSetSelectedDeliveryNote = function (inputElement, hiddenInputElement, deliveryNoteNumber, deliveryNoteID) {
        $(inputElement).changeVal(deliveryNoteNumber);
        $(hiddenInputElement).changeVal(deliveryNoteID);
        $('.flex-delivery-note-search-whisperer').hide();
    }

    getDeliveryNoteSearchWhispers = function (loadOverlayPlaceholder, inputElement) {
        var parent = $(inputElement).parent('.flex-delivery-note-search-input');
        var searchPhrase = $(inputElement).val().toLowerCase();
        var found = false;
        parent.find('.flex-delivery-note-items a').each(function () {
            var value = $(this).find('span.flex-delivery-note-number').text().toLowerCase();
            if (value.indexOf(searchPhrase) > -1) {
                $(this).show();
                found = true;
            } else {
                $(this).hide();
            }
        });
        if (found) {
            parent.find('.flex-delivery-note-items span.flex-delivery-note-no-items').hide();
        } else {
            parent.find('.flex-delivery-note-items span.flex-delivery-note-no-items').show();
        }
    }

    changePhoneNumber = function (sourceInputID, sourcePrefixID) {


    }

    mirrorInputValue = function (sourceInputID, targetInputIDs, checkIfEmpty = false) {
        var sourceInput = $(sourceInputID);
        var sourceValue = sourceInput.val();

        // Ensures that targetInputIDs is always an array
        if (!Array.isArray(targetInputIDs)) {
            targetInputIDs = [targetInputIDs];
        }

        // Iterates over all target selectors
        targetInputIDs.forEach(function (targetInputID) {
            var targetInput = $(targetInputID);
            if (!checkIfEmpty || !targetInput.val().trim()) {
                targetInput.val(sourceValue);
            }
        });
    }

    /*
     * Changes value and triggers change event. Sets value for inputs, textareas, spans...
     */
    $.fn.changeVal = function (value) {
        if (this.is('span')) {
            $(this).text(value).trigger('change');
        } else {
            $(this).val(value).trigger('change');
        }
    }

    showParameterAttributeValues = function (genericArticleID, attributeID) {
        if (!$('#GenericArticleAttributeFilter_' + genericArticleID + '_' + attributeID).hasClass('flex-selected')) {
            $('.flex-parameters .flex-attributes[data-flex-generic-article-key="' + genericArticleID + '"]').find('.flex-title').removeClass('flex-selected');
            $('#GenericArticleAttributeFilter_' + genericArticleID + '_' + attributeID).addClass('flex-selected');
            $('.flex-parameters .flex-attribute-values-container[data-flex-generic-article-key="' + genericArticleID + '"]').find('.flex-attribute-values').hide();
            $('#GenericArticleAttributeFilterValues_' + genericArticleID + '_' + attributeID).show();

            var heightPadding = parseInt($('#GenericArticleAttributeFilterValues_' + genericArticleID + '_' + attributeID).css('paddingTop')) + parseInt($('#GenericArticleAttributeFilterValues_' + genericArticleID + '_' + attributeID).css('paddingBottom'));
            $('#GenericArticleAttributeFilterValues_' + genericArticleID + '_' + attributeID).css('min-height', $('.flex-parameters .flex-attributes[data-flex-generic-article-key="' + genericArticleID + '"]').innerHeight() - heightPadding - 1 + 'px');
        }
        updateSelectedAttributes();
    }

    updateSelectedAttributes = function () {
        $('.products .flex-filter .flex-extended .flex-parameters .flex-content > div > .flex-attributes-wrapper > .flex-attributes > span.flex-title').FlexAttributeLoad();
    }


    $.fn.FlexLevamUnitViewer = function () {
        var element = $(this);

        var fullWidth = $('.unit-image').width();
        var fullHeight = $('.unit-image').height();

        var aspectRatio = (fullWidth / fullHeight);

        var visibleViewportWidth = $('.scroll-wrapper').width();
        var visibleViewportHeight = $('.scroll-wrapper').height() - $('.help-bar').height();

        var clicked = false, clickable = true,
            clickY, clickX, scrollTop, srollLeft;

        $('.unit-image').width(visibleViewportWidth);
        $('.unit-image').height(visibleViewportWidth / aspectRatio);

        $('.image-wrapper').width(visibleViewportWidth);
        $('.image-wrapper').height(visibleViewportWidth / aspectRatio);

        var updateScrollPos = function (event) {
            $('.scroll-wrapper').scrollTop(scrollTop + (clickY - event.pageY));
            $('.scroll-wrapper').scrollLeft(scrollLeft + (clickX - event.pageX));
        }

        $('.scroll-wrapper').on({
            'mousedown': function (event) {
                event.preventDefault();
                clicked = true;
                scrollTop = $('.scroll-wrapper').scrollTop();
                scrollLeft = $('.scroll-wrapper').scrollLeft()
                clickY = event.pageY;
                clickX = event.pageX;
                clickable = true;
            }
        });

        $(window).on({
            'mousemove': function (event) {
                clicked && updateScrollPos(event);
                clickable = false;
            },
            'mouseup': function () {
                clicked = false;
            }
        });

        $('.maximize').click(function () {
            $('.unit-image').width(fullHeight * aspectRatio);
            $('.unit-image').height(fullHeight);

            $('.image-wrapper').width(fullHeight * aspectRatio);
            $('.image-wrapper').height(fullHeight);
        });

        $('.minimize').click(function () {
            $('.unit-image').width(visibleViewportHeight * aspectRatio);
            $('.unit-image').height(visibleViewportHeight);

            $('.image-wrapper').width(visibleViewportHeight * aspectRatio);
            $('.image-wrapper').height(visibleViewportHeight);
        });

        $('.zoom-in').click(function () {
            var newWidth = $('.unit-image').width() + (fullWidth / 10);
            var newHeight = newWidth / aspectRatio;

            if (newHeight > fullHeight) {
                $('.unit-image').width(fullHeight * aspectRatio);
                $('.unit-image').height(fullHeight);

                $('.image-wrapper').width(fullHeight * aspectRatio);
                $('.image-wrapper').height(fullHeight);
            } else {
                $('.unit-image').width(newWidth);
                $('.unit-image').height(newWidth / aspectRatio);

                $('.image-wrapper').width(newWidth);
                $('.image-wrapper').height(newWidth / aspectRatio);
            }
        });

        $('.zoom-out').click(function () {
            var newWidth = $('.unit-image').width() - (fullWidth / 10);
            var newHeight = newWidth / aspectRatio;

            if (newHeight < visibleViewportHeight) {
                $('.unit-image').width(visibleViewportHeight * aspectRatio);
                $('.unit-image').height(visibleViewportHeight);

                $('.image-wrapper').width(visibleViewportHeight * aspectRatio);
                $('.image-wrapper').height(visibleViewportHeight);
            } else {
                $('.unit-image').width(newWidth);
                $('.unit-image').height(newWidth / aspectRatio);

                $('.image-wrapper').width(newWidth);
                $('.image-wrapper').height(newWidth / aspectRatio);
            }
        });

        $('.scroll-wrapper').on("mousewheel", function (event) {
            event.preventDefault();

            if (event.deltaY === 1) {
                $('.zoom-in').click();
            } else if (event.deltaY === -1) {
                $('.zoom-out').click();
            }
        });

        $('.coord').click(function () {
            if (clickable) {
                $('.flex-laximo .flex-oe-part .flex-item[data-flex-image-code="' + $(this).attr('data-number') + '"]').first().click();
            }
        });

        $('.coord').mouseenter(function () {
            $('.flex-oe-part .flex-item[data-flex-image-code=' + $(this).attr('data-number') + ']').addClass('highlighted');
            $('.coord[data-number=' + $(this).attr('data-number') + ']').addClass('highlighted');
        });

        $('.coord').mouseleave(function () {
            $('.flex-oe-part .flex-item').removeClass('highlighted');
            $('.coord').removeClass('highlighted');
        });
    };

    $.fn.AdvancedImageViewer = function () {
        this.each(function () {
            let element = $(this);
            let viewport = element.find('.viewport');
            let scaleWrapper = element.find('.scale-wrapper');
            let zoomIn = element.find('#ZoomInButton');
            let zoomOut = element.find('#ZoomOutButton');
            let fitViewport = element.find('#FitInButton');

            let originalContentSize = {
                width: -1,
                height: -1
            }

            let position = {
                top: 0,
                left: 0,
                x: 0,
                y: 0
            };

            let scale = 1;

            let getContentWidth = function () {
                return originalContentSize.width * scale;
            };

            let getContentHeight = function () {
                return originalContentSize.height * scale;
            };

            let getFitScale = function () {
                let widthScale = viewport.width() / originalContentSize.width;
                let heightScale = viewport.height() / originalContentSize.height;
                return Math.min(widthScale, heightScale);  
            };

            let setViewportWidth = function () {
                viewport.css('display', 'none');

                let containerWidth = element.parent().width();

                viewport.css({
                    'width': containerWidth + 'px',
                    'display': 'block'
                });

                originalContentSize = {
                    width: scaleWrapper.width(),
                    height: scaleWrapper.height()
                }
            };

            let mouseDown = function (e) {
                position = {
                    left: viewport.scrollLeft(),
                    top: viewport.scrollTop(),
                    x: e.clientX,
                    y: e.clientY,
                };

                $(document).on('mousemove', mouseMove);
                $(document).on('mouseup', mouseUp);
            };

            let mouseMove = function (e) {
                const dx = e.clientX - position.x;
                const dy = e.clientY - position.y;

                viewport.scrollTop(position.top - dy);
                viewport.scrollLeft(position.left - dx);
            };

            let mouseUp = function () {
                $(document).off('mousemove', mouseMove);
                $(document).off('mouseup', mouseUp);
            };

            let centerContent = function () {
                viewport.scrollLeft((scaleWrapper.width() - viewport.width()) / 2);
                viewport.scrollTop((scaleWrapper.height() - viewport.height()) / 2);
            };

            let scaleViewport = function (checkBounderies = true) {
                if (checkBounderies && scale > 1.6)
                    scale = 1.6;
                else if (checkBounderies && scale < 0.1)
                    scale = 0.1;

                scaleWrapper.css({
                    '-webkit-transform': 'scale(' + scale + ')',
                    '-moz-transform': 'scale(' + scale + ')',
                    '-ms-transform': 'scale(' + scale + ')',
                    '-o-transform': 'scale(' + scale + ')',
                    'transform': 'scale(' + scale + ')'
                });

                scaleWrapper.off('transitionend').on('transitionend', function () {
                    if (scale >= 1) {
                        scaleWrapper.css({
                            'width': 'auto',
                            'height': 'auto'
                        });
                    } else {
                        scaleWrapper.css({
                            'width': getContentWidth() + 'px',
                            'height': getContentHeight() + 'px'
                        });
                    }
                });

                centerContent();
            };

            viewport.on('mousedown', mouseDown);
            zoomIn.on('click', function () {
                scale += 0.1;
                scaleViewport();
            });
            zoomOut.on('click', function () {
                scale += -0.1;
                scaleViewport();
            });
            fitViewport.on('click', function () {
                scale = getFitScale();
                scaleViewport();
            });

            $(window).on("resize", function () {
                setViewportWidth();
            });

            window.addEventListener('wheel', function (e) {
                let delta = e.deltaY;

                let hoveredElement = $(e.target);

                if ((hoveredElement.hasClass('viewport') && hoveredElement.parents('.advanced-image-viewer').length) ||
                    hoveredElement.parents('.advanced-image-viewer .viewport').length) {

                    e.preventDefault();

                    if (delta > 0) {
                        scale -= 0.1;
                        scaleViewport();
                    } else {
                        scale += 0.1;
                        scaleViewport();
                    }
                }
            }, {
                passive: false
            });

            setViewportWidth();

            scale = getFitScale();
            scaleViewport(false);
        });
    };

    $.fn.FlexCsGraphicsZoomSlider = function (manufacturer, model, engine, constructionGroup, manufacturerIDRoute, modelIDRoute, engineIDRoute, constructionGroupIDRoute, constructionGroupTargetIDsRoute, genericArticleIDRoute, vehicleType) {
        this.each(function () {
            var element = $(this);
            var values = element.attr('data-values');

            element.attr('data-flex', 'true');

            var snapSlider = document.getElementById(element.attr('ID'));

            var valuePairs = {};

            var valueArray = values.split(';');

            var minValue = parseFloat(valueArray[0].replace(',', '.'));
            var maxValue = parseFloat(valueArray[valueArray.length - 1].replace(',', '.'));

            var startValue = minValue;

            if (element.attr('data-start-value')) {
                startValue = parseFloat(element.attr('data-start-value').replace(',', '.'))
            }

            var stepSize = 100.0 / (valueArray.length - 1);

            valuePairs["min"] = minValue;

            var currentStepSize = 0.0;

            for (var i = 1, len = valueArray.length; i < len - 1; i++) {

                var percentage = (parseFloat(valueArray[i].replace(',', '.')) - parseFloat(minValue)) / (parseFloat(maxValue) - parseFloat(minValue)) * 100.0;

                currentStepSize += stepSize;

                //valuePairs[percentage + '%'] = parseFloat(valueArray[i].replace(',', '.'));
                valuePairs[currentStepSize + '%'] = parseFloat(valueArray[i].replace(',', '.'));
            }

            valuePairs["max"] = maxValue;

            noUiSlider.create(snapSlider, {
                start: startValue,
                snap: (element.attr('data-snap') == 'true'),
                range: valuePairs
            });

            snapSlider.noUiSlider.on('change', function (values, handle) {
                changeCsGraphicsItem('.cs-graphics .detail', $('.cs-graphics .detail').attr('data-code-pair'), $('.cs-graphics .detail').attr('data-brand-id'), manufacturer, model, engine, constructionGroup, manufacturerIDRoute, modelIDRoute, engineIDRoute, constructionGroupIDRoute, constructionGroupTargetIDsRoute, genericArticleIDRoute, vehicleType, values[0]);
            });

            $('.cs-graphics-title').click(function () {
                if ($(this).hasClass('expanded')) {
                    $('.cs-graphics').slideUp(400, 'easeInBack', function () {
                        $('.cs-graphics-title').removeClass('expanded');
                    });
                } else {
                    $('.cs-graphics').slideDown({ duration: 600, easing: 'easeOutExpo' });
                    $(this).addClass('expanded');
                }
            });
        });
    };

    $.fn.FlexVehicleSelector = function () {
        this.each(function () {
            var element = $(this);

            var listItems = element.find('.list .item');
            var detailItems = element.find('.detail .item');

            listItems.mouseenter(function () {
                var engineId = $(this).attr('data-engine-id');
                element.find('.detail .item[data-engine-id=' + engineId + ']').addClass('visible');
            });

            listItems.mouseleave(function () {
                detailItems.removeClass("visible");
            });
        });
    };

    $.fn.FlexSideBanner = function () {
        this.each(function () {
            var element = $(this);

            var windowWidth = $(window).width();
            var bannerWidth = element.outerWidth();

            var offset = (windowWidth - 1210) / 2 - bannerWidth - 10;

            if (element.hasClass('left')) {
                element.css('left', offset + 'px');
            }
            else {
                element.css('right', offset + 'px');
            }

            element.css('visibility', 'visible');

            $(window).on('resize', function () {

                var windowWidth = $(window).width();
                var bannerWidth = element.outerWidth();

                var offset = (windowWidth - 1210) / 2 - bannerWidth;

                if (element.hasClass('left')) {
                    element.css('left', offset + 'px');
                }
                else {
                    element.css('right', offset + 'px');
                }
            });
        });
    };

    $.fn.TecDocOutage = function () {
        let element = $(this);
        let height = element.outerHeight();

        let cookieConsentBox = $('.cookie-consent');

        if (cookieConsentBox.length)
            cookieConsentBox.css('bottom', height + 'px');
    };

    raiseCheckboxEvent = function (sender) {
        const checkbox = $(sender).find('input.flex-checkbox');

        const isSenderChecked = checkbox.is(':checked');

        $('.mounting-side-filter .mounting-side-group input[type="checkbox"]').each(function () {
            $(this).prop('checked', false);
        });

        if (isSenderChecked === false) {
            checkbox.prop('checked', true);
        }

        checkbox.change();
    };


    makeCookieBarInvisible = function () {
        if ($("#seoSettings").attr("data-flex-reload") === "true") {
            location.reload()
            return;
        }
        $('.cookie-consent').fadeOut(250);
    }

    displayCustomCookieSelection = function (selectorOfElementFrom) {
        $(selectorOfElementFrom).fadeOut(250);
        $('.cookie-custom-selection').fadeIn(250);
    }

    let confirmCookieTimeout;

    confirmAllCookiesFromCustomCookieSelection = function (ev) {
        if (confirmCookieTimeout) {
            return;
        }

        $('.custom-cookies-checkbox input').each(function () {
            $(this).prop('checked', true)
            $(this).change()
        })

        confirmCookieTimeout = setTimeout(() => {
            confirmCookieConsent(ev, false)
            confirmCookieTimeout = undefined
        }, 700)
    }

    deleteAllCookies = function () {
        const cookieParts = document.cookie.split(';');

        for (let i = 0; i < cookieParts.length; i++) {
            deleteCookie(cookieParts[i].split("=")[0]);
        }

        localStorage.removeItem('RememberedUserLogin');
    }

    deleteCookie = function (cookieName) {
        const cookieBase = cookieName + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=';
        let pathParts = location.pathname.split('/');
        document.cookie = cookieBase + '/';
        while (pathParts.length > 0) {
            document.cookie = cookieBase + pathParts.join('/');
            pathParts.pop();
        };
    }

    setCookiesToConfirmCookieBar = function (additionalCookieBarOnly) {
        const valueOfhoursToExpire = $('#seoSettings').attr('data-confirm-time');
        let daysToExpire = 0.5;

        if (valueOfhoursToExpire !== null && valueOfhoursToExpire !== undefined) {
            const hoursToExpire = parseFloat(valueOfhoursToExpire)
            if (!isNaN(hoursToExpire)) {
                daysToExpire = hoursToExpire / 24
            }
        }

        $.cookie('isAdditionalCookieBarConfirmed', true, { expires: daysToExpire, path: '/' });

        if (additionalCookieBarOnly) {
            return;
        }

        $.cookie('isCookieConsentSetted', 'true', { expires: 999, path: '/' });
    }

    continueWithoutCookies = function (withDeletion) {
        if (withDeletion) {
            deleteAllCookies();
            setCookiesToConfirmCookieBar(false);
            makeCookieBarInvisible();

            return;
        }

        confirmCookieConsent(null, true);
    }

    changePreviousCookiesSelection = function () {
        $('.cookie-basic-selection').fadeOut(250);
        $('.cookie-additional-selection').fadeIn(250);
    }

    confirmAdditionalCookieBar = function () {
        setCookiesToConfirmCookieBar(true);
        makeCookieBarInvisible();
    }

    toggleCookiesModalDialog = function (selector, open) {
        if (open) {
            $('.reject-cookies-modal' + selector).fadeIn(250);
            return;
        }
        $('.reject-cookies-modal' + selector).fadeOut(250);
    }

    applyCookiesUserSettings = function (necessaryOnly, invoker) {
        let detailsElement = $('.cookie-consent .content .details');
        let shouldAcceptAllSettings = $("#seoSettings").attr("data-flex-fake-engine");

        areAnalyticalCookiesEnabled = false;
        areMarketingCookiesEnabled = false;

        if (shouldAcceptAllSettings === "true") {
            areAnalyticalCookiesEnabled = true;
            areMarketingCookiesEnabled = true;
            return;
        }

        if (!necessaryOnly && detailsElement.attr('expanded') === 'true') {
            areAnalyticalCookiesEnabled = $('#AnalyticalCookies').is(':checked');
            areMarketingCookiesEnabled = $('#MarketingCookies').is(':checked');
            return;
        }

        if (!necessaryOnly
            && $(invoker).attr('id') !== 'confirm-all-cookies'
            && $(invoker).hasClass('primary-cookie-button')) {
            areAnalyticalCookiesEnabled = $('#analytical-cookie-selector').is(':checked');
            areMarketingCookiesEnabled = $('#marketing-cookie-selector').is(':checked');
            return;
        }

        if (!necessaryOnly) {
            areAnalyticalCookiesEnabled = true;
            areMarketingCookiesEnabled = true;
        }
    }

    toggleCookieDetails = function () {
        let detailsElement = $('.cookie-consent .content .details');
        let toogleLink = $('.cookie-consent .controls a');
        let agreeAllText = $("#seoSettings").attr("data-flex-agree-all-text");
        let agreeSelectedText = $("#seoSettings").attr("data-flex-agree-selected-text");

        if (detailsElement.attr('expanded') == 'true') {
            detailsElement.slideUp({ duration: 300 });
            detailsElement.removeAttr('expanded');
            toogleLink.html(toogleLink.attr('data-expand-text'));
            $("#agreeButton").text(agreeAllText);
        } else {
            detailsElement.slideDown({ duration: 300 });
            detailsElement.attr('expanded', 'true');
            toogleLink.html(toogleLink.attr('data-collapse-text'));
            $("#agreeButton").text(agreeSelectedText);
        }
    }

    openCookieConsent = function () {
        deleteCookie('isCookieConsentSetted');
        location.reload()
    }

}(jQuery));

$(window).on('load', function () {
    $('.advanced-image-viewer').AdvancedImageViewer();
});

$(function () {
    $('.flex-cookies-statement').FlexCookiesStatement();
    $('.flex-back-to-top').FlexBackToTop();
    $('.flex-breadcrumb-bar').CollapseBreadCrumbs();
    $('#seoSettings').SetupSeoSettings();

    $('.products .flex-filter .flex-extended .flex-parameters .flex-content > div > .flex-attributes-wrapper > .flex-attributes > span.flex-title').FlexAttributeLoad();
    $('.flex-drop-down[data-flex!="true"]').FlexDropDown();
    $('.flex-checkbox[data-flex!="true"]').FlexCheckbox();
    $('.flex-range-slider[data-flex!="true"]').FlexRangeSlider();
    $('.flex-file-upload[data-flex!="true"]').FlexFileUpload();
    $('input.flex-one-click-selectable[data-flex!="true"]').OneClickSelectable();
    $('.flex-radio-buttons[data-flex!="true"]').FlexRadioButtons();
    $('.flex-top-panel-container .flex-menu').FlexMenu();
    $('.flex-main-menu .flex-menu').FlexCatalogMenu();
    $('.flex-tabs').FlexTabs();
    $('.flex-half-collapsed-box').FlexHalfCollapsedBox();
    $('.products .flex-attributes[data-flex!="true"]').FlexCollapsibleAttributes();
    $('.products .flex-delivery-times[data-flex!="true"]').FlexCollapsibleDeliveryTimes();
    $('.flex-product-detail .flex-delivery-times[data-flex!="true"]').FlexCollapsibleDeliveryTimes();
    $('.flex-slider').FlexSlider();
    $('input[data-flex-watermark]').FlexWatermark();
    $('.flex-search').FlexSearchBar();
    $('.flex-smart-search').FlexSmartSearchBar();
    $('.flex-login-form').FlexLoginForm();
    $('.flex-user-menu').FlexUserMenu();
    $('.flex-stocks[data-flex!="true"]').FlexStocks();
    $('.flex-basket-summary').FlexBasketSummary();
    $('.flex-basket-spinner[data-flex!="true"]').FlexSpinner();
    $('.flex-carousel').FlexCarousel();
    $('.flex-filter .flex-extended > div').FlexFilterTabs();
    $('img[data-flex-async-image-src]').FlexAsyncImageLoader();
    $('.flex-tree[data-flex-dynamic!="true"]').FlexTree();
    $('.flex-tree[data-flex-dynamic="true"]').FlexDynamicTree();
    $('.flex-product-groups-tree').FlexProductGroupsTree();
    $('*[data-flex-tooltip]').FlexTooltip();
    $('*[data-flex-html-tooltip]').FlexHtmlTooltip();
    $('*[data-flex-html-tooltip-desktop-only]').FlexHtmlTooltip();
    $('*[data-flex-hide-empty="true"]').FlexHideEmptyElement();
    //$('.products-list[data-flex-is-last-page="false"][data-flex-catalog-type="1"]').SearchByNumberScrollPager();
    //$('.products-list[data-flex-is-last-page="false"][data-flex-catalog-type="2"]').TecDocScrollPager();
    //$('.products-list[data-flex-is-last-page="false"][data-flex-catalog-type="3"]').UniversalPartsScrollPager();
    //$('.products-list[data-flex-is-last-page="false"][data-flex-catalog-type="4"]').LaximoScrollPager();
    //$('.products-list[data-flex-is-last-page="false"][data-flex-catalog-type="5"]').SaleScrollPager();
    //$('.products-list').FlexTecDocDynamicCross();
    $('.flex-oe-part-table').FlexPinnableBox();
    $('.flex-same-height-container').FlexSameHeightContainer();
    $('.flex-add-to-license-plate').FlexAddToLicensePlate();
    //$('.flex-share').FlexShare();
    $('.flex-overdue-invoices-modal-popup').FlexOverdueInvoicesModalPopup();
    $('.flex-modal-popup').FlexModalPopup();
    $('.flex-custom-modal-popup').FlexCustomModalPopup();
    $('.flex-progress-bar').FlexProgressBar();
    $('.flex-gauge').FlexGauge();
    $('.flex-transport-methods-wrapper').FlexTransportMethods();
    $('.flex-transport-methods-wrapper').FlexZasilkovnaBranchPosition();
    $('.flex-transport-methods-wrapper').FlexBalikovnaBranchPosition();
    $('.flex-transport-methods-wrapper').FlexDpdBranchPosition();
    $('.flex-transport-methods-wrapper').FlexPplBranchPosition();
    $('.flex-transport-methods-wrapper').FlexGlsBranchPosition();
    $('.flex-transport-methods-wrapper').FlexWeDoBranchPosition();
    $('.flex-transport-methods-wrapper').FlexPackageToPostBranchPosition();
    $('.flex-transport-methods-wrapper').FlexPaczkomatBranchPosition();
    $('.flex-transport-methods-wrapper').FlexPersonalPickBranchPosition();
    $('.levam-unit-viewer').FlexLevamUnitViewer();
    $('.flex-laximo .models-list').FlexLevamModelSelectionHistory();
    $('.flex-laximo .flex-laximo-vehicle-detail').FlexLevamVehicleDetailHistory();
    $('.flex-products').FlexProducts();
    $('.conditional-items').FlexConditionalItems();
    $('.categories').FlexCategories();
    $('.select-universal-parts-category-wizard').SelectUniversalPartsCategoryWizard();
    $('.vehicle-search').FlexVehicleSelector();
    $('.side-container').FlexSideBanner();
    $('.tecdoc-outage').TecDocOutage();

    getRememberedUserLogin('IsRememberedLogin_Popup', 'BodyContentPlaceHolder_LoginForm_Username');
    getRememberedUserLogin('IsRememberedLogin_OrderForm', 'OrderFormLoginUsername');
    getRememberedUserLogin('IsRememberedLogin_HomePage', 'BodyContentPlaceHolder_LoginCPH_LoginForm_Username');

    setAnchor();
    flexMandatoryField();
    flexInvoiceSearchBar();
    flexDeliveryNoteSearchBar();

    window.addEventListener("pageshow", function (event) {
        if ($('.flex-add-to-license-plate') != undefined) {
            var historyTraversal = event.persisted || (typeof window.performance != "undefined" && window.performance.navigation.type === 2);

            var vehicleType = $('.flex-spz').attr('data-spz-vehicle-type');
            var manufacturerID = $('.flex-spz').attr('data-spz-manufacturer-id');
            var modelID = $('.flex-spz').attr('data-spz-model-id');
            var engineID = $('.flex-spz').attr('data-spz-engine-id');

            if (historyTraversal) {

                app.ajax.post({
                    url: 'Product.svc/BuildLicensePlateContent',
                    data: { vehicleType: vehicleType, manufacturerID: manufacturerID, modelID: modelID, engineID: engineID },
                }, function (response) {
                    $('.flex-add-to-license-plate').html(response.d);
                    $('.flex-add-to-license-plate').FlexAddToLicensePlate();
                    $('.flex-drop-down[data-flex!="true"]').FlexDropDown();
                });


                //$('.flex-add-to-license-plate').html("TEST");



            }
        }
    });
    var refreshProductsState = $('#RefreshProductsState');
    if (refreshProductsState.length) {
        if (refreshProductsState.val() == 'true') {
            var executableFunction = new Function($('.products-list').attr('data-flex-refresh-event'));
            executableFunction();
        } else {
            refreshProductsState.val('true');
        }
    }

    validatePhoneNumber = function (val) {
        let reg = /^[\d\s()+-.]+$/;
        return reg.test(val);
    }

    validateEmail = function (val) {
        let reg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        return reg.test(val);
    }

});;
/// <reference path="/JScripts/jquery-1.9.1-vsdoc.js" />

(function ($) {

    replaceCustomMenu = function () {
        if (isSmallScreen()) {
            $('.flex-container.flex-top-panel-container .flex-menu').appendTo('.flex-container.flex-top-panel-container .flex-dock-right');
        } else {
            $('.flex-container.flex-top-panel-container .flex-menu').prependTo('.flex-container.flex-top-panel-container .flex-dock-left');
            $('.flex-container.flex-top-panel-container .user-owner-contact').prependTo('.flex-container.flex-top-panel-container .flex-dock-left');
        }
    }

    setCustomPopup = function () {
        //$(".flex-custom-modal-popup")

    }


    setSearchBarWidth = function () {
        if (isSmallScreen()) {
            var windowWidth = $(window).width();
            var inputWidth = windowWidth - 107;

            $('.flex-search .flex-search-input input[type="text"]').css('width', inputWidth + 'px');
        } else {
            $('.flex-search .flex-search-input input[type="text"]').css('width', '');
        }
    }

        setProductListViewMode = function () {
            if (isSmallScreen()) {
                if ($('.products-list').length && $('.flex-view-modes #ProductViewMode_2').hasClass('flex-selected')) {
                    $('.flex-view-modes #ProductViewMode_0').click();
                }
            }
        }
    
}(jQuery));

$(window).on('resize', function () {
    replaceCustomMenu();
    setSearchBarWidth();
    setProductListViewMode();
    $('.flex-custom-modal-popup').FlexCustomModalPopup();
    //setCustomPopup();
});;
/// <reference path="/JScripts/jquery-1.9.1-vsdoc.js" />

(function ($) {

    // Pool for all Ajax requests
    var xhrPool = [];

    $(document).ajaxSend(function (e, jqXHR, options) {
        xhrPool.push({
            Url: options.url,
            JqXhr: jqXHR
        });
    });

    $(document).ajaxComplete(function (e, jqXHR, options) {
        //showAllAjaxRequests();

        xhrPool = $.grep(xhrPool, function (x) {
            return x.JqXhr != jqXHR;
        });
    });

    abortAjaxRequest = function (url) {
        $.each(xhrPool, function (idx, item) {
            if (url == item.Url) {
                item.JqXhr.abort();
            }
        });
    };

    showAllAjaxRequests = function () {
        console.log('Running ajax requests: ' + xhrPool.length);

        $.each(xhrPool, function (idx, item) {
            console.log(item.Url);
        });
    };

    var getSearchTargetTypeActiveAjaxRequest = null;
    var getSmartSearchWhispersActiveAjaxRequest = null;

    getUniversalPartsBySearchPhrase = function (loadOverlayPlaceholder, searchPhrase, watermarkText, ignoreCharsLimit) {
        if ((searchPhrase.length > 2 && searchPhrase !== watermarkText) || (ignoreCharsLimit && searchPhrase.length > 0 && searchPhrase !== watermarkText)) {
            $.ajax({
                type: 'POST',
                url: '/AjaxWS.svc/GetUniversalPartsBySearchPhrase',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                data: '{ "searchPhrase": "' + searchPhrase + '", "watermarkText": "' + watermarkText + '" }',

                success: function (response) {
                    $(loadOverlayPlaceholder).html(response.d);
                },

                error: function (xhr, textStatus, errorThrown) {
                    if (xhr.status != 0 && xhr.statusText != 'abort')
                        alert('There is an error in your request (getUniversalPartsBySearchPhrase): ' + errorThrown);
                },

                beforeSend: function () {
                    //abortAllRequests();
                    // Loading animation.
                    $(loadOverlayPlaceholder).FlexShowLoadingOverlay();
                    abortAjaxRequest('/AjaxWS.svc/GetUniversalPartsBySearchPhrase');
                },

                complete: function () {
                }
            });

        } else if (searchPhrase.length === 0) {
            $.ajax({
                type: 'POST',
                url: '/AjaxWS.svc/GetUniversalPartsCategories',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                data: '{}',

                success: function (response) {
                    $(loadOverlayPlaceholder).html(response.d);
                },

                error: function (xhr, textStatus, errorThrown) {
                    if (xhr.status != 0 && xhr.statusText != 'abort')
                        alert('There is an error in your request (getUniversalPartsBySearchPhrase): ' + errorThrown);
                },

                beforeSend: function () {
                    //abortAllRequests();
                    // Loading animation.
                    $(loadOverlayPlaceholder).FlexShowLoadingOverlay();
                    abortAjaxRequest('/AjaxWS.svc/GetUniversalPartsCategories');
                },

                complete: function () {
                    $('.flex-tree[data-flex-dynamic="true"]').FlexDynamicTree();
                }
            });
        }
    }

    getUniversalPartsBySearchPhrase2 = function (loadOverlayPlaceholder, searchPhrase, watermarkText, rootCategoryID, ignoreCharsLimit) {
        if ((searchPhrase.length > 2 && searchPhrase !== watermarkText) || (ignoreCharsLimit && searchPhrase.length > 0 && searchPhrase !== watermarkText)) {
            $.ajax({
                type: 'POST',
                url: '/AjaxWS.svc/GetUniversalPartsBySearchPhrase2',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                data: '{ "searchPhrase": "' + searchPhrase + '", "rootCategoryID": ' + rootCategoryID + ' }',

                success: function (response) {
                    $(loadOverlayPlaceholder).html(response.d);
                },

                error: function (xhr, textStatus, errorThrown) {
                    if (xhr.status != 0 && xhr.statusText != 'abort')
                        alert('There is an error in your request (getUniversalPartsBySearchPhrase2): ' + errorThrown);
                },

                beforeSend: function () {
                    //abortAllRequests();
                    // Loading animation.
                    $(loadOverlayPlaceholder).FlexShowLoadingOverlay();
                    abortAjaxRequest('/AjaxWS.svc/GetUniversalPartsBySearchPhrase2');
                },

                complete: function () {
                }
            });

        } else if (searchPhrase.length === 0) {
            $.ajax({
                type: 'POST',
                url: '/AjaxWS.svc/GetUniversalPartsCategories2',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                data: '{ "searchPhrase": "' + searchPhrase + '", "rootCategoryID": ' + rootCategoryID + ' }',

                success: function (response) {
                    $(loadOverlayPlaceholder).html(response.d);
                },

                error: function (xhr, textStatus, errorThrown) {
                    if (xhr.status != 0 && xhr.statusText != 'abort')
                        alert('There is an error in your request (getUniversalPartsCategories2): ' + errorThrown);
                },

                beforeSend: function () {
                    //abortAllRequests();
                    // Loading animation.
                    $(loadOverlayPlaceholder).FlexShowLoadingOverlay();
                    abortAjaxRequest('/AjaxWS.svc/GetUniversalPartsCategories2');
                },

                complete: function () {
                }
            });
        }
    }

    getSearchWhispers = function (loadOverlayPlaceholder, searchPhrase, type, subType) {
        if (searchPhrase.trim().length > 0) {
            //if ((type == 1 && subType == 1) || (type == 1 && subType == 5) || (type == 5)) {
            if ((type == 1 && subType == 1) || (type == 1 && subType == 5)) {
                $.ajax({
                    type: 'POST',
                    url: `Navigation/Search/GetSmartSearchWhispers?searchPhrase=${searchPhrase}&target=${type}`,

                    success: function (response) {
                        let result = jQuery.parseJSON(response);

                        $(loadOverlayPlaceholder).html(result.ProductHtmlContent);

                        $('.flex-search-input .flex-count').html(result.ItemTotalCount);
                        $('.flex-search-input .flex-count').fadeIn({ duration: 600 });

                        if (response.d.length > 0) {
                            $(loadOverlayPlaceholder).slideDown({ duration: 600, easing: 'easeOutExpo' });
                        } else {
                            $(loadOverlayPlaceholder).slideUp({ duration: 400, easing: 'easeOutBounce' });
                        }
                    },

                    error: function (xhr, textStatus, errorThrown) {
                        if (xhr.status != 0 && xhr.statusText != 'abort')
                            alert('There is an error in your request (getSearchWhispers): ' + errorThrown);
                    },

                    beforeSend: function () {
                        //abortAllRequests();
                        // Loading animation.
                        abortAjaxRequest(`Navigation/Search/GetSmartSearchWhispers?searchPhrase=${searchPhrase}&target=${type}`);
                        $(loadOverlayPlaceholder).FlexShowLoading();
                    },

                    complete: function () {
                    }
                });
            } else if (type == 4) {
                $.ajax({
                    type: 'POST',
                    url: '/AjaxWS.svc/GetVehicleSearchWhispers',
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    data: '{ "searchPhrase": "' + safeUrlEncode(searchPhrase) + '" }',

                    success: function (response) {
                        var result = jQuery.parseJSON(response.d);

                        $(loadOverlayPlaceholder).html(result.WhispererHTMLContent);

                        $('.flex-search-input .flex-count').html(result.TotalItemsCount);
                        $('.flex-search-input .flex-count').fadeIn({ duration: 600 });

                        if (response.d.length > 0) {
                            $(loadOverlayPlaceholder).slideDown({ duration: 600, easing: 'easeOutExpo' });
                        } else {
                            $(loadOverlayPlaceholder).slideUp({ duration: 400, easing: 'easeOutBounce' });
                        }
                    },

                    error: function (xhr, textStatus, errorThrown) {
                        if (xhr.status != 0 && xhr.statusText != 'abort')
                            alert('There is an error in your request (getSearchWhispers): ' + errorThrown);
                    },

                    beforeSend: function () {
                        //abortAllRequests();
                        // Loading animation.
                        abortAjaxRequest('/AjaxWS.svc/GetVehicleSearchWhispers');
                        $(loadOverlayPlaceholder).FlexShowLoading();
                    },

                    complete: function () {
                    }
                });
            } else {
                $(loadOverlayPlaceholder).slideUp({ duration: 400, easing: 'easeOutBounce' });
            }
        } else {
            $(loadOverlayPlaceholder).slideUp({ duration: 400, easing: 'easeOutBounce' });
        }
    }

    //Zatim jeste nepresouvat do Product.js (nefunguje pak správně)!
    getProductDetailInformations = function (loadOverlayPlaceholder, groupID, tecDocCodePair, tecDocBrandID, articleLinkID, manufacturerID, modelID, engineID) {
        var urlEngineID = getUrlHistoryValue('engine-id');
        if (urlEngineID) {
            engineID = urlEngineID;
        }

        app.ajax.post({
            url: 'Product.svc/GetProductDetailInformations',
            data: { groupID: groupID, tecDocCodePair: tecDocCodePair, tecDocBrandID: tecDocBrandID, articleLinkID: articleLinkID, manufacturerID: manufacturerID, modelID: modelID, engineID: engineID },
            loading: loadOverlayPlaceholder,
        }, function (response) {
            $(loadOverlayPlaceholder).html(response.d);

            $('.flex-tab').removeClass('flex-selected');
            $('.flex-tab.flex-informations').addClass('flex-selected');

            $(window).unbind('scroll', getNextApplicationsPageEvent);
        });
    }

    getSmartSearchNumberPlate = function (searchPhrase) {
        if (searchPhrase) {
            var countryID = $("#SmartSearchBySPZ").val();

            if (countryID == -1) {
                flexShowToastError($('#SmartSearchBySPZText').attr('data-state-not-selected-text'));
            } else {
                var defer = $.Deferred();
                app.ajax.post({
                    url: 'SmartSearch.svc/GetSmartSearchNumberPlate',
                    data: { searchPhrase: safeUrlEncode(searchPhrase), countryID: countryID },
                    complete: function () { defer.resolve(); },
                    beforeSend: function () { abortAjaxRequest('/AjaxServices/SmartSearch.svc/GetSmartSearchNumberPlate'); }
                }, function (response) {
                    var result = jQuery.parseJSON(response.d);
                    if (result.errorText) {
                        flexShowToastError(result.errorText);
                    }

                    if (result.isRedirect) {
                        window.location.href = result.redirectUrl;
                    }
                });
            }
        }
    }

    getSmartSearchHistory = function (loadOverlayPlaceholder, target, event) {
        let defer = $.Deferred();
        app.ajax.postMvc({
            url: `Navigation/Search/GetSearchHistory?searchType=${target}`,
            data: {},
            complete: function () {
                defer.resolve();
            }
        }, function (response) {

            $(loadOverlayPlaceholder + ' .flex-items').html(response);
            $(loadOverlayPlaceholder).slideDown({duration: 600, easing: 'easeOutExpo'});
            $('.flex-smart-search-input .flex-count').fadeOut({ duration: 600 });

            $('.flex-smart-search-input .flex-search-targets input[type="button"]').removeClass("flex-selected");
            $('.flex-smart-search-input .flex-search-targets input[type="button"].flex-history').addClass("flex-selected");
        });

        return defer;
    }
    getSmartSearchWhispers = function (loadOverlayPlaceholder, searchPhrase, target, showWhispers, showHistory, event) {
        let defer = $.Deferred();
        if (event == null || (isKeyPrintable(event.which) || event.which == 229)) {
            if (searchPhrase.trim().length > 2) {
                if (getSearchTargetTypeActiveAjaxRequest !== null){
                    getSearchTargetTypeActiveAjaxRequest.abort();
                }
                getSearchTargetTypeActiveAjaxRequest = app.ajax.postMvc(
                    {
                        url: `Navigation/Search/GetSearchTargetType?searchPhrase=${searchPhrase}&target=${target}`,
                        complete: function() {
                            getSearchTargetTypeActiveAjaxRequest = null;
                        }
                    }, function (response) {
                        let buttonToSellectClassSname = '';
                        let searchTargetType = parseInt(response);
                        switch (searchTargetType) {
                            case 0:
                                return;
                            case 1:
                                buttonToSellectClassSname='.flex-code'
                                break;
                            case 2:
                                buttonToSellectClassSname='.flex-text'
                                break;
                            case 3:
                                buttonToSellectClassSname='.flex-vehicle'
                                break;
                            case 4:
                                buttonToSellectClassSname='.flex-vin'
                                break;
                            case 5:
                                buttonToSellectClassSname='.flex-kba'
                                break;
                            default:
                                console.log("Invalid target type");
                                return;
                        }

                        $('.flex-smart-search-input .flex-search-targets input[type="button"]').removeClass("flex-selected");
                        $('.flex-smart-search-input .flex-search-targets input[type="button"]'+buttonToSellectClassSname).addClass("flex-selected");


                        defer.resolve();

                        if (getSmartSearchWhispersActiveAjaxRequest !== null){
                            getSmartSearchWhispersActiveAjaxRequest.abort();
                        }
                        getSmartSearchWhispersActiveAjaxRequest = app.ajax.postMvc({
                            url: `Navigation/Search/GetSmartSearchWhispers?searchPhrase=${searchPhrase}&target=${searchTargetType}`,
                            complete: function() {
                                getSmartSearchWhispersActiveAjaxRequest = null;
                            }
                        }, function (response) {

                            let result = jQuery.parseJSON(response);

                            if (showWhispers && (result.ItemTotalCount > 0 )) {
                                $(loadOverlayPlaceholder + ' .flex-items').html(result.ProductHtmlContent);
                                $(loadOverlayPlaceholder).slideDown({ duration: 600, easing: 'easeOutExpo' });
                            } else {
                                $(loadOverlayPlaceholder).slideUp({
                                    duration: 400, easing: 'easeOutBounce', done: function () {
                                        if (searchPhrase == $('SmartSearchInput').val()) {
                                            $(loadOverlayPlaceholder).find('.flex-items a').remove();
                                        }
                                    }
                                });
                            }
                            $('.flex-smart-search-input .flex-count').html(result.ItemTotalCount);
                            $('.flex-smart-search-input .flex-count').fadeIn({ duration: 600 });
                        });

                    }
                );


            } else {
                $(loadOverlayPlaceholder).find('.flex-items a').remove();
                $(loadOverlayPlaceholder).slideUp({ duration: 400, easing: 'easeOutBounce' });
                $('.flex-smart-search-input .flex-count').fadeOut({ duration: 600 });
                $('.flex-smart-search-input .flex-search-targets input[type="button"]').removeClass("flex-selected");
            }
        }

        return defer;
    }


    //getTecDocCrossData = function (products) {
    //    $.ajax({
    //        type: 'POST',
    //        url: '/AjaxWS.svc/GetTecDocCrossData',
    //        contentType: 'application/json; charset=utf-8',
    //        dataType: 'json',
    //        data: '{ "productItems": ' + JSON.stringify(products) + ' }',

    //        success: function (response) {
    //            var result = jQuery.parseJSON(response.d);

    //            for (var i = 0; i < result.length; i++) {
    //                var element = $('#ProductItem_' + result[i].GroupID);
    //                if (result[i].NameHTMLContent.length > 0) {
    //                    element.find('h2 a strong').html(result[i].NameHTMLContent);
    //                    element.find('.read-more a strong span.name').html(result[i].NameHTMLContent);
    //                }

    //                if (result[i].UsageNumbersHTMLContent.length > 0) {
    //                    if (jQuery('.usage-numbers').length > 0) {
    //                        element.find('.usage-numbers').html(result[i].UsageNumbersHTMLContent);
    //                    }
    //                    else {
    //                        element.find('.tecdoc-numbers').append(result[i].UsageNumbersHTMLContent);
    //                    }
    //                }

    //                if (result[i].ReplacedByNumbersContent.length > 0) {
    //                    if (jQuery('.replaced-by-numbers').length > 0) {
    //                        element.find('.replaced-by-numbers').html(result[i].ReplacedByNumbersContent);
    //                    }
    //                    else {
    //                        element.find('.tecdoc-numbers').append(result[i].ReplacedByNumbersContent);
    //                    }
    //                }

    //                if (result[i].ReplacedNumbersContent.length > 0) {
    //                    if (jQuery('.replaced-numbers').length > 0) {
    //                        element.find('.replaced-numbers').html(result[i].ReplacedNumbersContent);
    //                    }
    //                    else {
    //                        element.find('.tecdoc-numbers').append(result[i].ReplacedNumbersContent);
    //                    }
    //                }

    //                if (result[i].TecDocWarningsHTMLContent.length > 0) {
    //                    element.find('.tecdoc-warnings').html(result[i].TecDocWarningsHTMLContent);
    //                }

    //                if (result[i].ImageHTMLContent.length > 0) {

    //                    if (element.find('.flex-image-wrapper').has('.flex-product-flags')) {
    //                        var elementFlags = element.find('.flex-image-wrapper .flex-product-flags');
    //                        //element.find('.flex-image-wrapper').html(elementFlags);
    //                        element.find('.flex-image-wrapper a').html(result[i].ImageHTMLContent);

    //                    }
    //                    else {
    //                        element.find('.flex-image-wrapper a').html(result[i].ImageHTMLContent);
    //                    }

    //                    $(element).find('img[data-flex-async-image-src]').FlexAsyncImageLoader();
    //                }

    //                //var areCrossAttributesPreffered = $('.products-list').attr('data-are-cross-attributes-preffered');
    //                //var hasSystemAttributes = element.find('.flex-attributes table > *').length > 0;

    //                if (result[i].AttributesHTMLContent.length > 0) { //&& (areCrossAttributesPreffered == 'true' || !hasSystemAttributes)
    //                    element.find('.flex-attributes').html(result[i].AttributesHTMLContent);
    //                    element.find('.flex-attributes').attr('data-flex', 'false').html(result[i].AttributesHTMLContent);
    //                }
    //            }
    //        },

    //        error: function (xhr, textStatus, errorThrown) {
    //            if (xhr.status != 0 && xhr.statusText != 'abort')
    //                alert('There is an error in your request (getTecDocCrossData): ' + errorThrown);

    //        },

    //        beforeSend: function () {
    //        },

    //        complete: function () {
    //            $('.flex-same-height-container').FlexSameHeightContainer();
    //            $('.products .flex-attributes[data-flex!="true"]').FlexCollapsibleAttributes();
    //            $('.products .flex-delivery-times[data-flex!="true"]').FlexCollapsibleDeliveryTimes();
    //        }
    //    });
    //}

    getSearchByNumberProducts = function (loadOverlayPlaceholder, sortBy, onStockOnly, purchasePricePriorized, viewMode, text, type, subType, refreshFilters, areHiddenGroupsVisible, loadAllItems, page, pushHistoryFilters, detectFilterType, $event) {
        //var filteredManufacturers = [];

        //$('.flex-filter .flex-manufacturers').find('input[type="checkbox"]').each(function () {
        //    var element = $(this);

        //    if (element.is(':checked')) {
        //        filteredManufacturers.push(element.attr('value'));
        //    }
        //});

        var manufacturersQuery = ($('.products .flex-filter').find('.flex-extended').attr('data-flex-manufacturers-filters-query') != undefined ? $('.products .flex-filter').find('.flex-extended').attr('data-flex-manufacturers-filters-query') : "");
        var isManufacturersModulExpanded = $(".flex-filter .flex-manufacturers .flex-title").hasClass("flex-expanded");
        var isParametersModulExpanded = $(".flex-filter .flex-parameters .flex-title").hasClass("flex-expanded");
        var autoCollapseFilterModuleAfterApplication = $('.flex-filter .flex-extended').attr('data-auto-collapse-filter-module-after-application');

        var filtersQuery = buildFilterQuery();

        if (pushHistoryFilters) {
            var expandedIDsPath = getUrlHistoryValue('path');

            if (filtersQuery) {
                history.pushState(null, document.title, getUrlPath() + '?path=' + expandedIDsPath + '&m-filter=' + manufacturersQuery + '&td-filter=' + filtersQuery + '&onstock-only=' + onStockOnly + '&sort-by=' + sortBy);
            } else {
                history.pushState(null, document.title, getUrlPath() + '?path=' + expandedIDsPath + '&m-filter=' + manufacturersQuery + '&onstock-only=' + onStockOnly + '&sort-by=' + sortBy);
                $('.flex-remove-filter').hide();
                $('.flex-tags .flex-item').remove();
            }

            if ($('.flex-tags').find('.flex-item').length > 0) {
                $('.flex-tags .flex-remove-all-filters').show();
            } else {
                $('.flex-tags .flex-remove-all-filters').hide();
            }
        }

        let filteredParams = [];
        $('.flex-filter .flex-parameters .flex-block-filter-params').find('input[type="checkbox"]').each(function () {
            var element = $(this);

            if (element.is(':checked')) {
                filteredParams.push(element.attr('value'));
            }
        });

        //if(filteredParams.length > 0){
        //    $(".flex-filter .flex-controls .flex-filtrate").show();
        //}else{
        //    $(".flex-filter .flex-controls .flex-filtrate").hide();
        //}

        let target = undefined;
        if ($event !== undefined) {
            target = ($event.target === undefined || false) ? $event.srcElement : $event.target;
        }

        if ((target !== undefined || null) && $(target).attr("data-flex-instant-filter") === "false") {
            return;
        }

        var filteredManufacturers = [];

        if (getUrlHistoryValue('m-filter')) {
            var splittedManufacturers = getUrlHistoryValue('m-filter').toString().split('~');
            for (var i = 0; i < splittedManufacturers.length; i++) {
                if (splittedManufacturers[i].length > 0) {
                    filteredManufacturers.push(decodeURI(splittedManufacturers[i]));
                }
            }
        }

        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/GetSearchByNumberProducts',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "sortBy": "' + sortBy + '", "onStockOnly": "' + onStockOnly + '", "purchasePricePriorized": "' + purchasePricePriorized + '", "viewMode": "' + viewMode + '", "filteredManufacturers": ' + JSON.stringify(filteredManufacturers) + ', "text": "' + text + '", "type": "' + type + '", "subType": ' + subType + ', "areHiddenGroupsVisible": "' + areHiddenGroupsVisible + '", "parametersFilterQuery": "' + filtersQuery + '", "loadAllItems": "' + loadAllItems + '", "page": "' + page + '" }',

            success: function (response) {
                var result = jQuery.parseJSON(response.d);

                if (refreshFilters)
                    $('.flex-filter').html(result.FilterHTMLContent);

                $(loadOverlayPlaceholder).html(result.HTMLContent);


                switch (viewMode) {
                    case 0:
                        $(loadOverlayPlaceholder).addClass("catalog-view");
                        $(loadOverlayPlaceholder).removeClass("list-view");
                        $(loadOverlayPlaceholder).removeClass("tiles-view");
                        break;
                    case 1:
                        $(loadOverlayPlaceholder).removeClass("catalog-view");
                        $(loadOverlayPlaceholder).addClass("list-view");
                        $(loadOverlayPlaceholder).removeClass("tiles-view");
                        break;
                    case 2:
                        $(loadOverlayPlaceholder).removeClass("catalog-view");
                        $(loadOverlayPlaceholder).removeClass("list-view");
                        $(loadOverlayPlaceholder).addClass("tiles-view");
                        break;

                    default:
                        break;
                }


                $('#ViewMode').val(viewMode);
                $('.flex-view-modes input[type="button"]').removeClass('flex-selected');
                $("#ProductViewMode_" + viewMode).addClass('flex-selected');

                $('.flex-basket-spinner[data-flex!="true"]').FlexSpinner();
                $('img[data-flex-async-image-src]').FlexAsyncImageLoader();
                $('*[data-flex-html-tooltip]').FlexHtmlTooltip();

                if (areHiddenGroupsVisible)
                    $('#AreHiddenGroupsVisible').val(areHiddenGroupsVisible);

                $('.products-list').attr('data-flex-is-last-page', result.IsLastPage);

                $('#CurrentPage').val(page);

                //$(window).unbind('scroll', getNextSearchByNumberPageEvent);

                //if (!result.IsLastPage)
                //    $('.products-list').SearchByNumberScrollPager();

                //if ($('#RefreshProductsState').val() == 'true')
                //    $(window).scrollTop($('#PageScrollTop').val());
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (getSearchByNumberProducts): ' + errorThrown);
            },

            beforeSend: function () {
                $(loadOverlayPlaceholder).parent().find('.other-parameters').hide();
                $(loadOverlayPlaceholder).FlexShowLoading();

                if (areHiddenGroupsVisible && $('#RefreshProductsState').val() != 'true')
                    $('.products-list').scrollTo();

                if ($('#RefreshProductsState').val() == 'true')
                    $(window).scrollTop(0);
            },

            complete: function () {
                if (refreshFilters) {
                    $('.flex-drop-down[data-flex!="true"]').FlexDropDown();
                    $('.flex-checkbox[data-flex!="true"]').FlexCheckbox();
                    $('.flex-filter .flex-extended > div').FlexFilterTabs();
                    $('.flex-range-slider[data-flex!="true"]').FlexRangeSlider();
                }

                if (isManufacturersModulExpanded && !autoCollapseFilterModuleAfterApplication) {
                    $(".flex-filter .flex-manufacturers .flex-title").addClass("flex-expanded");
                    $(".flex-filter .flex-manufacturers .flex-content").show();
                }

                if (isParametersModulExpanded && !autoCollapseFilterModuleAfterApplication) {
                    $(".flex-filter .flex-parameters .flex-title").addClass("flex-expanded");
                    $(".flex-filter .flex-parameters .flex-content").show();
                }

                //$('.products-list').FlexTecDocDynamicCross();
                $('.products .flex-attributes[data-flex!="true"]').FlexCollapsibleAttributes();
                $('.products .flex-delivery-times[data-flex!="true"]').FlexCollapsibleDeliveryTimes();
                $('.flex-stocks[data-flex!="true"]').FlexStocks();

                let selectedAttributes = sessionStorage.getItem("attributeHash").split(',');
                setTimeout(function () {
                    for (let id of selectedAttributes) {
                        $(`#${id}`).click();
                    }
                }, 0);
            }
        });
    }

    getSearchByNumberProductsPerPage = function (loadOverlayPlaceholder, sortBy, text, type, subType, startIndex, areHiddenGroupsVisible, parametersFilterQuery, event) {
        event.preventDefault();

        //var filteredManufacturers = [];

        //$('.flex-filter .flex-manufacturers').find('input[type="checkbox"]').each(function () {
        //    var element = $(this);

        //    if (element.is(':checked')) {
        //        filteredManufacturers.push(element.attr('value'));
        //    }
        //});

        var filteredManufacturers = [];

        if (getUrlHistoryValue('m-filter')) {
            var splittedManufacturers = getUrlHistoryValue('m-filter').toString().split('~');
            for (var i = 0; i < splittedManufacturers.length; i++) {
                if (splittedManufacturers[i].length > 0) {
                    filteredManufacturers.push(decodeURI(splittedManufacturers[i]));
                }
            }
        }

        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/GetSearchByNumberProductsPerPage',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "filteredManufacturers": ' + JSON.stringify(filteredManufacturers) + ', "sortBy": "' + sortBy + '", "text": "' + text + '", "type": ' + type + ', "subType": "' + subType + '", "startIndex": ' + startIndex + ', "areHiddenGroupsVisible": "' + areHiddenGroupsVisible + '", "parametersFilterQuery": "' + parametersFilterQuery + '" }',

            success: function (response) {
                var result = jQuery.parseJSON(response.d);

                $('.item-empty').remove();

                loadOverlayPlaceholder.append(result.HTMLContent);

                loadOverlayPlaceholder.FlexHideNextPageLoading();

                $('.flex-basket-spinner[data-flex!="true"]').FlexSpinner();
                $('img[data-flex-async-image-src]').FlexAsyncImageLoader();
                $('*[data-flex-html-tooltip]').FlexHtmlTooltip();

                $('.products-list').attr('data-flex-is-last-page', result.IsLastPage);

                var currentPage = parseInt($('#CurrentPage').val()) + 1;
                $('#CurrentPage').val(currentPage);
                $('#currentPage2').val(currentPage);

                //if (!result.IsLastPage)
                //    $('.products-list').SearchByNumberScrollPager();
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (getSearchByNumberProductsPerPage): ' + errorThrown);
            },

            beforeSend: function () {
                //abortAllRequests();
                // Loading animation.
                $('.products-list').find('.load-btns').remove();
                $('.products-list').find('.item-empty').remove();
                loadOverlayPlaceholder.FlexShowNextPageLoading();
            },

            complete: function () {
                //$('.products-list').FlexTecDocDynamicCross();
                $('.products .flex-attributes[data-flex!="true"]').FlexCollapsibleAttributes();
                $('.products .flex-delivery-times[data-flex!="true"]').FlexCollapsibleDeliveryTimes();
                $('.flex-stocks[data-flex!="true"]').FlexStocks();
            }
        });
    }

    scrollToDisintegration = function () {
        $('html, body').animate({ scrollTop: $('.flex-disintegration-categories').offset().top }, 600, 'easeInOutBack');
    }

    getUniversalPartsCategoryNode = function (loadOverlayPlaceholder, parentNodeID, fullCategoryIDsPath, showBigItems) {
        if ($(loadOverlayPlaceholder).attr('data-flex-show-products-direct').toLowerCase() == 'true') {
            window.location.href = $(loadOverlayPlaceholder).attr('data-flex-products-direct-url');
            return true;
        }

        if (!$(loadOverlayPlaceholder).hasClass('flex-selected')) {
            $.ajax({
                type: 'POST',
                url: '/AjaxWS.svc/GetUniversalPartsCategoryNode',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                data: '{ "parentNodeID": ' + parentNodeID + ', "fullCategoryIDsPath": "' + fullCategoryIDsPath + '" }',

                success: function (response) {
                    var result = jQuery.parseJSON(response.d);

                    $(loadOverlayPlaceholder).append(result.ItemsHTMLContent);

                    if ($(loadOverlayPlaceholder).parents('.flex-shortcut').length > 0)
                        showBigItems = false;

                    if (showBigItems)
                        $('.flex-shortcuts .flex-tree').html(result.BigItemsHTMLContent);

                    $(loadOverlayPlaceholder).FlexHideInlineLoadingOverlay();

                    $(loadOverlayPlaceholder).children().not('span:first').hide();
                    $(loadOverlayPlaceholder).children().not('span:first').slideDown(300);
                },

                error: function (xhr, textStatus, errorThrown) {
                    if (xhr.status != 0 && xhr.statusText != 'abort')
                        alert('There is an error in your request (getUniversalPartsCategoryNode): ' + errorThrown);
                },

                beforeSend: function () {
                    // Loading animation.
                    $(loadOverlayPlaceholder).FlexShowInlineLoadingOverlay();
                },

                complete: function () {
                    var expandedIDsPath = getUrlHistoryValue('path');

                    if ($(loadOverlayPlaceholder).parents('.flex-tree').attr('data-flex-expanded') == 'true') {
                        history.pushState(null, document.title, getUrlPath() + "?path=" + fullCategoryIDsPath);
                    }

                    if (expandedIDsPath != '' && $(loadOverlayPlaceholder).parents('.flex-tree').attr('data-flex-expanded') != 'true') {
                        var expandedIDsPathSplitted = expandedIDsPath.split('~');

                        var indexOfCurrentID = expandedIDsPathSplitted.indexOf(String(parentNodeID));

                        if (indexOfCurrentID == (expandedIDsPathSplitted.length - 1)) {
                            $(loadOverlayPlaceholder).parents('.flex-tree').attr('data-flex-expanded', 'true');
                        }
                        else {
                            if ($('#TreeNode_' + expandedIDsPathSplitted[indexOfCurrentID + 1]).is('a')) {
                                $('#TreeNode_' + expandedIDsPathSplitted[indexOfCurrentID + 1]).addClass("flex-selected");
                                $(loadOverlayPlaceholder).parents('.flex-tree').attr('data-flex-expanded', 'true');
                            }
                            else {
                                $('#TreeNode_' + expandedIDsPathSplitted[indexOfCurrentID + 1]).attr('data-flex-show-products-direct', 'false');
                                $('#TreeNode_' + expandedIDsPathSplitted[indexOfCurrentID + 1]).click();
                            }
                        }
                    }
                }
            });
        }
    }


    getUniversalPartsSubcategories = function (id, useDynamicLoad, rootCategoryID, showSubnodesInShortcuts) {
        var defer = $.Deferred();

        if (!$('.node a[data-node-id="' + id + '"]').hasClass('selected')) {
            $.ajax({
                type: 'POST',
                url: '/AjaxWS.svc/GetUniversalPartsSubcategories',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                data: '{ "id": ' + id + ', "useDynamicLoad": ' + useDynamicLoad + ', "rootCategoryID": ' + rootCategoryID + ' }',

                success: function (response) {
                    var result = jQuery.parseJSON(response.d);

                    if (useDynamicLoad) {
                        $('.categories .tree a[data-node-id="' + id + '"]').parent().append(result.ItemsHTMLContent);
                        if (showSubnodesInShortcuts)
                            $('.categories .shortcuts').html(result.ShortcutsHTMLContent);
                    } else {
                        $('.categories .shortcuts').html(result.ShortcutsHTMLContent);
                    }
                },

                error: function (xhr, textStatus, errorThrown) {
                    if (xhr.status != 0 && xhr.statusText != 'abort')
                        alert('There is an error in your request (getUniversalPartsSubcategories): ' + errorThrown);
                },

                beforeSend: function () {
                },

                complete: function () {
                    defer.resolve();
                }
            });
        } else {
            defer.resolve();
        }

        return defer;
    }

    //selectChildNode = function (sender) {
    //    $(sender).addClass("selected");
    //}



    getUniversalPartsCategoryShortcutNode = function (loadOverlayPlaceholder, shortcutID, fullCategoryIDsPath) {
        if (!$(loadOverlayPlaceholder).hasClass('flex-selected')) {
            $.ajax({
                type: 'POST',
                url: '/AjaxWS.svc/GetUniversalPartsCategoryShortcutNode',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                data: '{ "shortcutID": ' + shortcutID + ', "fullCategoryIDsPath": "' + fullCategoryIDsPath + '" }',

                success: function (response) {
                    $(loadOverlayPlaceholder).append(response.d);
                    $(loadOverlayPlaceholder).FlexHideLoadingOverlay();

                    if ($(loadOverlayPlaceholder).find('.flex-node').length == 1) {
                        $(loadOverlayPlaceholder).find('.flex-node').click();
                    }
                },

                error: function (xhr, textStatus, errorThrown) {
                    if (xhr.status != 0 && xhr.statusText != 'abort')
                        alert('There is an error in your request (getUniversalPartsCategoryShortcutNode): ' + errorThrown);
                },

                beforeSend: function () {
                    // Loading animation.
                    $(loadOverlayPlaceholder).FlexShowLoadingOverlay();
                },

                complete: function () {
                }
            });
        }
    }

    getUniversalPartsCategoriesBySearchPhrase = function (loadOverlayPlaceholder, searchPhrase, watermarkText) {
        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/GetUniversalPartsCategoriesBySearchPhrase',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "searchPhrase": "' + searchPhrase + '", "watermarkText": "' + watermarkText + '" }',

            success: function (response) {
                $(loadOverlayPlaceholder).html(response.d);
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (getUniversalPartsCategoriesBySearchPhrase): ' + errorThrown);
            },

            beforeSend: function () {
                // Loading animation.
                $(loadOverlayPlaceholder).FlexShowLoadingOverlay();
            },

            complete: function () {
            }
        });
    }

    getUniversalPartsProducts = function (loadOverlayPlaceholder, sortBy, onStockOnly, purchasePricePriorized, viewMode, categoryID, fullCategoryIDs, rootCategoryID, category, itemsCount, refreshFilters, areHiddenGroupsVisible, loadAllItems, page, pushHistoryFilters, detectFilterType, $event) {
        //var filteredManufacturers = [];

        //$('.flex-filter .flex-manufacturers').find('input[type="checkbox"]').each(function () {
        //    var element = $(this);

        //    if (element.is(':checked')) {
        //        filteredManufacturers.push(element.attr('value'));
        //    }
        //});
        var isManufacturersModulExpanded = $(".flex-filter .flex-manufacturers .flex-title").hasClass("flex-expanded");
        let isParametersModulExpanded = $("#FilterParamsExpanded").val();
        var manufacturersQuery = ($('.products .flex-filter').find('.flex-extended').attr('data-flex-manufacturers-filters-query') != undefined ? $('.products .flex-filter').find('.flex-extended').attr('data-flex-manufacturers-filters-query') : "");
        var autoCollapseFilterModuleAfterApplication = $('.flex-filter .flex-extended').attr('data-auto-collapse-filter-module-after-application');

        var filtersQuery = buildFilterQuery();

        if (pushHistoryFilters) {
            var expandedIDsPath = getUrlHistoryValue('path');

            if (filtersQuery) {
                history.pushState(null, document.title, getUrlPath() + '?path=' + expandedIDsPath + '&m-filter=' + manufacturersQuery + '&td-filter=' + filtersQuery + '&onstock-only=' + onStockOnly + '&sort-by=' + sortBy);
            } else {
                history.pushState(null, document.title, getUrlPath() + '?path=' + expandedIDsPath + '&m-filter=' + manufacturersQuery + '&onstock-only=' + onStockOnly + '&sort-by=' + sortBy);
                $('.flex-remove-filter').hide();
                $('.flex-tags .flex-item').remove();
            }

            if ($('.flex-tags').find('.flex-item').length > 0) {
                $(".flex-remove-all-filters").each(function () {
                    $(this).show();
                });
            } else {
                $(".flex-remove-all-filters").each(function () {
                    $(this).hide();
                });
            }
        }

        let filteredParams = [];
        $('.flex-filter .flex-parameters .flex-block-filter-params').find('input[type="checkbox"]').each(function () {
            var element = $(this);

            if (element.is(':checked')) {
                filteredParams.push(element.attr('value'));
            }
        });

        //if(filteredParams.length > 0){
        //    $(".flex-filter .flex-controls .flex-filtrate").show();
        //}else{
        //    $(".flex-filter .flex-controls .flex-filtrate").hide();
        //}

        let target = undefined;
        if ($event !== undefined) {
            target = ($event.target === undefined || false) ? $event.srcElement : $event.target;
        }

        if ((target !== undefined || null) && $(target).attr("data-flex-instant-filter") === "false") {
            return;
        }

        var filteredManufacturers = [];

        if (getUrlHistoryValue('m-filter')) {
            var splittedManufacturers = getUrlHistoryValue('m-filter').toString().split('~');
            for (var i = 0; i < splittedManufacturers.length; i++) {
                if (splittedManufacturers[i].length > 0) {
                    filteredManufacturers.push(decodeURI(splittedManufacturers[i]));
                }
            }
        }

        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/GetUniversalPartsProducts',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "sortBy": "' + sortBy + '", "onStockOnly": "' + onStockOnly + '", "purchasePricePriorized": "' + purchasePricePriorized + '", "viewMode": "' + viewMode + '", "filteredManufacturers": ' + JSON.stringify(filteredManufacturers) + ', "parametersFilterQuery": "' + filtersQuery + '", "categoryID": "' + categoryID + '", "fullCategoryIDs": "' + fullCategoryIDs + '", "rootCategoryID": "' + rootCategoryID + '", "category": "' + category + '", "itemsCount": "' + itemsCount + '", "areHiddenGroupsVisible": "' + areHiddenGroupsVisible + '", "loadAllItems": "' + loadAllItems + '", "page": "' + page + '" }',
            success: function (response) {
                var result = jQuery.parseJSON(response.d);

                if (refreshFilters)
                    $('.flex-filter').html(result.FilterHTMLContent);

                $(loadOverlayPlaceholder).html(result.HTMLContent);

                $('#ViewMode').val(viewMode);
                $('.flex-view-modes input[type="button"]').removeClass('flex-selected');
                $("#ProductViewMode_" + viewMode).addClass('flex-selected');

                $('.flex-basket-spinner[data-flex!="true"]').FlexSpinner();
                $('img[data-flex-async-image-src]').FlexAsyncImageLoader();
                $('*[data-flex-html-tooltip]').FlexHtmlTooltip();

                if (areHiddenGroupsVisible)
                    $('#AreHiddenGroupsVisible').val(areHiddenGroupsVisible);

                $('.products-list').attr('data-flex-is-last-page', result.IsLastPage);

                $('#CurrentPage').val(page);

                let selectedAttributes = sessionStorage.getItem("attributeHash").split(',');
                setTimeout(function () {
                    for (let id of selectedAttributes) {
                        $(`#${id}`).click();
                    }
                }, 0);

                //$(window).unbind('scroll', getNextUniversalPartsPageEvent);

                //if (!result.IsLastPage)
                //    $('.products-list').UniversalPartsScrollPager();
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (getUniversalPartsProducts): ' + errorThrown);
            },

            beforeSend: function () {
                //abortAllRequests();
                // Loading animation.
                $(loadOverlayPlaceholder).FlexShowLoading();
                $(loadOverlayPlaceholder).parent().find('.other-parameters').hide();

                if (areHiddenGroupsVisible && $('#RefreshProductsState').val() != 'true')
                    $('.products-list').scrollTo();

                if ($('#RefreshProductsState').val() == 'true')
                    $(window).scrollTop(0);
            },

            complete: function () {
                if (refreshFilters) {
                    $('.flex-drop-down[data-flex!="true"]').FlexDropDown();
                    $('.flex-checkbox[data-flex!="true"]').FlexCheckbox();
                    $('.flex-filter .flex-extended > div').FlexFilterTabs();
                    $('.flex-range-slider[data-flex!="true"]').FlexRangeSlider();
                }

                if (isManufacturersModulExpanded && autoCollapseFilterModuleAfterApplication === "False") {
                    $(".flex-filter .flex-manufacturers .flex-title").addClass("flex-expanded");
                    $(".flex-filter .flex-manufacturers .flex-content").show();
                }

                if (isParametersModulExpanded === "true" && autoCollapseFilterModuleAfterApplication == "False") {
                    $(".flex-filter .flex-parameters .flex-title").addClass("flex-expanded");
                    $(".flex-filter .flex-parameters .flex-content").show();
                    $(".flex-title.flex-expanded .flex-tags").hide();
                }

                //$('.products-list').FlexTecDocDynamicCross();
                $('.products .flex-attributes[data-flex!="true"]').FlexCollapsibleAttributes();
                $('.products .flex-delivery-times[data-flex!="true"]').FlexCollapsibleDeliveryTimes();
                $('.flex-stocks[data-flex!="true"]').FlexStocks();
            }
        });
    }

    getUniversalPartsProductsPerPage = function (loadOverlayPlaceholder, sortBy, categoryID, fullCategoryIDs, rootCategoryID, category, itemsCount, startIndex, areHiddenGroupsVisible, event) {
        event.preventDefault();

        //var filteredManufacturers = [];

        //$('.flex-filter .flex-manufacturers').find('input[type="checkbox"]').each(function () {
        //    var element = $(this);

        //    if (element.is(':checked')) {
        //        filteredManufacturers.push(element.attr('value'));
        //    }
        //});

        var filtersQuery = "";

        if (getUrlHistoryValue('td-filter')) {
            filtersQuery = getUrlHistoryValue('td-filter')
        }

        var filteredManufacturers = [];

        if (getUrlHistoryValue('m-filter')) {
            var splittedManufacturers = getUrlHistoryValue('m-filter').toString().split('~');
            for (var i = 0; i < splittedManufacturers.length; i++) {
                if (splittedManufacturers[i].length > 0) {
                    filteredManufacturers.push(decodeURI(splittedManufacturers[i]));
                }
            }
        }

        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/GetUniversalPartsProductsPerPage',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "filteredManufacturers": ' + JSON.stringify(filteredManufacturers) + ', "sortBy": "' + sortBy + '", "parametersFilterQuery": "' + filtersQuery + '", "categoryID": "' + categoryID + '", "fullCategoryIDs": "' + fullCategoryIDs + '", "rootCategoryID": "' + rootCategoryID + '", "category": "' + category + '", "itemsCount": "' + itemsCount + '", "startIndex": ' + startIndex + ', "areHiddenGroupsVisible": "' + areHiddenGroupsVisible + '" }',

            success: function (response) {
                var result = jQuery.parseJSON(response.d);

                loadOverlayPlaceholder.append(result.HTMLContent);

                loadOverlayPlaceholder.FlexHideNextPageLoading();

                $('.flex-basket-spinner[data-flex!="true"]').FlexSpinner();
                $('img[data-flex-async-image-src]').FlexAsyncImageLoader();
                $('*[data-flex-html-tooltip]').FlexHtmlTooltip();

                $('.products-list').attr('data-flex-is-last-page', result.IsLastPage);

                var currentPage = parseInt($('#CurrentPage').val()) + 1;
                $('#CurrentPage').val(currentPage);

                //if (!result.IsLastPage)
                //    $('.products-list').UniversalPartsScrollPager();
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (getUniversalPartsProductsPerPage): ' + errorThrown);
            },

            beforeSend: function () {
                //abortAllRequests();
                // Loading animation.
                $('.products-list').find('.load-btns').remove();
                $('.products-list').find('.item-empty').remove();
                loadOverlayPlaceholder.FlexShowNextPageLoading();
            },

            complete: function () {
                //$('.products-list').FlexTecDocDynamicCross();
                $('.products .flex-attributes[data-flex!="true"]').FlexCollapsibleAttributes();
                $('.products .flex-delivery-times[data-flex!="true"]').FlexCollapsibleDeliveryTimes();
                $('.flex-stocks[data-flex!="true"]').FlexStocks();

                if (isManufacturersModulExpanded) {
                    $(".flex-filter .flex-manufacturers .flex-title").addClass("flex-expanded");
                    $(".flex-filter .flex-manufacturers .flex-content").show();
                }
            }
        });
    }

    getRecommendedProductsPerPage = function (loadOverlayPlaceholder, page, pageSize) {
        event.preventDefault();

        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/GetRecommendedProductsPerPage',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "page": "' + page + '", "pageSize": "' + pageSize + '" }',

            success: function (response) {
                loadOverlayPlaceholder.append(response.d);
                loadOverlayPlaceholder.FlexHideNextPageLoading();

                var currentPage = parseInt($('#CurrentPage').val()) + 1;
                $('#CurrentPage').val(currentPage);
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (getRecommendedProductsPerPage): ' + errorThrown);
            },

            beforeSend: function () {
                //abortAllRequests();
                // Loading animation.
                $('.products-list').find('.load-btns').remove();
                $('.products-list').find('.flex-load-next').hide();
                $('.products-list').find('.item-empty').remove();
                loadOverlayPlaceholder.FlexShowNextPageLoading();
            },

            complete: function () {
            }
        });
    }

    getSaleProducts = function (loadOverlayPlaceholder, sortBy, onStockOnly, purchasePricePriorized, viewMode, refreshFilters, areHiddenGroupsVisible, loadAllItems, page, detectFilterType, $event) {
        //var filteredManufacturers = [];

        //$('.flex-filter .flex-manufacturers').find('input[type="checkbox"]').each(function () {
        //    var element = $(this);

        //    if (element.is(':checked')) {
        //        filteredManufacturers.push(element.attr('value'));
        //    }
        //});

        //var manufacturersQuery = $('.products .flex-filter').find('.flex-extended').attr('data-flex-manufacturers-filters-query');
        var isManufacturersModulExpanded = $(".flex-filter .flex-manufacturers .flex-title").hasClass("flex-expanded");

        var manufacturersQuery = ($('.products .flex-filter').find('.flex-extended').attr('data-flex-manufacturers-filters-query') != undefined ? $('.products .flex-filter').find('.flex-extended').attr('data-flex-manufacturers-filters-query') : "");


        if (pushHistoryFilters) {
            history.pushState(null, document.title, wgetUrlPath() + '?path=' + fullCategoryIDs + '&m-filter=' + manufacturersQuery + '&onstock-only=' + onStockOnly + '&sort-by=' + sortBy);
        }

        let filteredParams = [];
        $('.flex-filter .flex-parameters .flex-block-filter-params').find('input[type="checkbox"]').each(function () {
            var element = $(this);

            if (element.is(':checked')) {
                filteredParams.push(element.attr('value'));
            }
        });

        //if(filteredParams.length > 0){
        //    $(".flex-filter .flex-controls .flex-filtrate").show();
        //}else{
        //    $(".flex-filter .flex-controls .flex-filtrate").hide();
        //}

        let target = undefined;
        if ($event !== undefined) {
            target = ($event.target === undefined || false) ? $event.srcElement : $event.target;
        }

        if ((target !== undefined || null) && $(target).attr("data-flex-instant-filter") === "false") {
            return;
        }

        var filteredManufacturers = [];

        if (getUrlHistoryValue('m-filter')) {
            var splittedManufacturers = getUrlHistoryValue('m-filter').toString().split('~');
            for (var i = 0; i < splittedManufacturers.length; i++) {
                if (splittedManufacturers[i].length > 0) {
                    filteredManufacturers.push(decodeURI(splittedManufacturers[i]));
                }
            }
        }

        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/GetSaleProducts',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "sortBy": "' + sortBy + '", "onStockOnly": "' + onStockOnly + '", "purchasePricePriorized": "' + purchasePricePriorized + '", "viewMode": "' + viewMode + '", "filteredManufacturers": ' + JSON.stringify(filteredManufacturers) + ', "areHiddenGroupsVisible": "' + areHiddenGroupsVisible + '", "loadAllItems": "' + loadAllItems + '", "page": "' + page + '" }',

            success: function (response) {
                var result = jQuery.parseJSON(response.d);

                if (refreshFilters)
                    $('.flex-filter').html(result.FilterHTMLContent);

                $(loadOverlayPlaceholder).html(result.HTMLContent);

                $('#ViewMode').val(viewMode);
                $('.flex-view-modes input[type="button"]').removeClass('flex-selected');
                $("#ProductViewMode_" + viewMode).addClass('flex-selected');

                $('.flex-basket-spinner[data-flex!="true"]').FlexSpinner();
                $('img[data-flex-async-image-src]').FlexAsyncImageLoader();
                $('*[data-flex-html-tooltip]').FlexHtmlTooltip();

                if (areHiddenGroupsVisible)
                    $('#AreHiddenGroupsVisible').val(areHiddenGroupsVisible);

                $('.products-list').attr('data-flex-is-last-page', result.IsLastPage);

                $('#CurrentPage').val(page);

                //$(window).unbind('scroll', getNextSalePageEvent);

                //if (!result.IsLastPage)
                //    $('.products-list').SaleScrollPager();
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (getSaleProducts): ' + errorThrown);
            },

            beforeSend: function () {
                //abortAllRequests();
                // Loading animation.
                $(loadOverlayPlaceholder).FlexShowLoading();
                $(loadOverlayPlaceholder).parent().find('.other-parameters').hide();

                if (areHiddenGroupsVisible && $('#RefreshProductsState').val() != 'true')
                    $('.products-list').scrollTo();

                if ($('#RefreshProductsState').val() == 'true')
                    $(window).scrollTop(0);
            },

            complete: function () {
                if (refreshFilters) {
                    $('.flex-drop-down[data-flex!="true"]').FlexDropDown();
                    $('.flex-checkbox[data-flex!="true"]').FlexCheckbox();
                    $('.flex-filter .flex-extended > div').FlexFilterTabs();
                }

                if (isManufacturersModulExpanded) {
                    $(".flex-filter .flex-manufacturers .flex-title").addClass("flex-expanded");
                    $(".flex-filter .flex-manufacturers .flex-content").show();
                }

                //$('.products-list').FlexTecDocDynamicCross();
                $('.products .flex-attributes[data-flex!="true"]').FlexCollapsibleAttributes();
                $('.products .flex-delivery-times[data-flex!="true"]').FlexCollapsibleDeliveryTimes();
                $('.flex-stocks[data-flex!="true"]').FlexStocks();
            }
        });
    }

    getSaleProductsPerPage = function (loadOverlayPlaceholder, startIndex, areHiddenGroupsVisible, event) {
        event.preventDefault();

        //var filteredManufacturers = [];

        //$('.flex-filter .flex-manufacturers').find('input[type="checkbox"]').each(function () {
        //    var element = $(this);

        //    if (element.is(':checked')) {
        //        filteredManufacturers.push(element.attr('value'));
        //    }
        //});

        var filteredManufacturers = [];

        if (getUrlHistoryValue('m-filter')) {
            var splittedManufacturers = getUrlHistoryValue('m-filter').toString().split('~');
            for (var i = 0; i < splittedManufacturers.length; i++) {
                if (splittedManufacturers[i].length > 0) {
                    filteredManufacturers.push(decodeURI(splittedManufacturers[i]));
                }
            }
        }

        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/GetSaleProductsPerPage',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "filteredManufacturers": ' + JSON.stringify(filteredManufacturers) + ', "startIndex": ' + startIndex + ', "areHiddenGroupsVisible": "' + areHiddenGroupsVisible + '" }',

            success: function (response) {
                var result = jQuery.parseJSON(response.d);

                loadOverlayPlaceholder.append(result.HTMLContent);

                loadOverlayPlaceholder.FlexHideNextPageLoading();

                $('.flex-basket-spinner[data-flex!="true"]').FlexSpinner();
                $('img[data-flex-async-image-src]').FlexAsyncImageLoader();
                $('*[data-flex-html-tooltip]').FlexHtmlTooltip();

                $('.products-list').attr('data-flex-is-last-page', result.IsLastPage);

                var currentPage = parseInt($('#CurrentPage').val()) + 1;
                $('#CurrentPage').val(currentPage);

                //if (!result.IsLastPage)
                //    $('.products-list').SaleScrollPager();
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (getSaleProductsPerPage): ' + errorThrown);
            },

            beforeSend: function () {
                //abortAllRequests();
                // Loading animation.
                $('.products-list').find('.load-btns').remove();
                $('.products-list').find('.item-empty').remove();
                loadOverlayPlaceholder.FlexShowNextPageLoading();
            },

            complete: function () {
                //$('.products-list').FlexTecDocDynamicCross();
                $('.products .flex-attributes[data-flex!="true"]').FlexCollapsibleAttributes();
                $('.products .flex-delivery-times[data-flex!="true"]').FlexCollapsibleDeliveryTimes();
                $('.flex-stocks[data-flex!="true"]').FlexStocks();
            }
        });
    }

    getActionDetailProducts = function (loadOverlayPlaceholder, sortBy, onStockOnly, purchasePricePriorized, viewMode, actionID, actionNameRoute, areHiddenGroupsVisible, loadAllItems, page, pushHistoryFilters, detectFilterType, $event) {
        //var filteredManufacturers = [];

        //$('.flex-filter .flex-manufacturers').find('input[type="checkbox"]').each(function () {
        //    var element = $(this);

        //    if (element.is(':checked')) {
        //        filteredManufacturers.push(element.attr('value'));
        //    }
        //});
        //var isManufacturersModulExpanded = $(".flex-filter .flex-manufacturers .flex-title").hasClass("flex-expanded");

        //var manufacturersQuery = ($('.products .flex-filter').find('.flex-extended').attr('data-flex-manufacturers-filters-query') != undefined ? $('.products .flex-filter').find('.flex-extended').attr('data-flex-manufacturers-filters-query') : "");



        //if (pushHistoryFilters) {
        //    history.pushState(null, document.title, getUrlPath() + '?m-filter=' + manufacturersQuery + '&onstock-only=' + onStockOnly + '&sort-by=' + sortBy);
        //}

        //var filteredManufacturers = [];

        //if (getUrlHistoryValue('m-filter')) {
        //    var splittedManufacturers = getUrlHistoryValue('m-filter').toString().split('~');
        //    for (var i = 0; i < splittedManufacturers.length; i++) {
        //        if (splittedManufacturers[i].length > 0) {
        //            filteredManufacturers.push(decodeURI(splittedManufacturers[i]));
        //        }
        //    }
        //}

        var filteredManufacturers = [];

        $('.flex-filter .flex-manufacturers').find('input[type="checkbox"]').each(function () {
            var element = $(this);

            if (element.is(':checked')) {
                filteredManufacturers.push(element.attr('value'));
            }
        });

        var isManufacturersModulExpanded = $(".flex-filter .flex-manufacturers .flex-title").hasClass("flex-expanded");
        var isParametersModulExpanded = $(".flex-filter .flex-parameters .flex-title").hasClass("flex-expanded");

        var manufacturersQuery = ($('.products .flex-filter').find('.flex-extended').attr('data-flex-manufacturers-filters-query') != undefined ? $('.products .flex-filter').find('.flex-extended').attr('data-flex-manufacturers-filters-query') : "");

        //var filtersQuery = ($('.products .flex-filter').find('.flex-extended').attr('data-flex-tecdoc-filters-query') != undefined ? $('.products .flex-filter').find('.flex-extended').attr('data-flex-tecdoc-filters-query') : "");
        var filtersQuery = buildFilterQuery();

        if (pushHistoryFilters) {
            var expandedIDsPath = getUrlHistoryValue('path');

            if (filtersQuery) {
                history.pushState(null, document.title, getUrlPath() + '?path=' + expandedIDsPath + '&m-filter=' + manufacturersQuery + '&td-filter=' + filtersQuery + '&onstock-only=' + onStockOnly + '&sort-by=' + sortBy);
            } else {
                history.pushState(null, document.title, getUrlPath() + '?path=' + expandedIDsPath + '&m-filter=' + manufacturersQuery + '&onstock-only=' + onStockOnly + '&sort-by=' + sortBy);
                $('.flex-remove-filter').hide();
                $('.flex-tags .flex-item').remove();
            }

            if ($('.flex-tags').find('.flex-item').length > 0) {
                $(".flex-remove-all-filters").each(function () {
                    $(this).show();
                });
            } else {
                $(".flex-remove-all-filters").each(function () {
                    $(this).hide();
                });
            }
        }

        let filteredParams = [];
        $('.flex-filter .flex-parameters .flex-block-filter-params').find('input[type="checkbox"]').each(function () {
            var element = $(this);

            if (element.is(':checked')) {
                filteredParams.push(element.attr('value'));
            }
        });

        //if(filteredParams.length > 0){
        //    $(".flex-filter .flex-controls .flex-filtrate").show();
        //}else{
        //    $(".flex-filter .flex-controls .flex-filtrate").hide();
        //}

        let target = undefined;
        if ($event !== undefined) {
            target = ($event.target === undefined || false) ? $event.srcElement : $event.target;
        }

        if ((target !== undefined || null) && $(target).attr("data-flex-instant-filter") === "false") {
            return;
        }

        var filteredManufacturers = [];

        if (getUrlHistoryValue('m-filter')) {
            var splittedManufacturers = getUrlHistoryValue('m-filter').toString().split('~');
            for (var i = 0; i < splittedManufacturers.length; i++) {
                if (splittedManufacturers[i].length > 0) {
                    filteredManufacturers.push(decodeURI(splittedManufacturers[i]));
                }
            }
        }

        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/GetActionDetailProducts',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "sortBy": "' + sortBy + '", "onStockOnly": "' + onStockOnly + '", "purchasePricePriorized": "' + purchasePricePriorized + '", "viewMode": "' + viewMode + '", "filteredManufacturers": ' + JSON.stringify(filteredManufacturers) + ', "parametersFilterQuery": "' + filtersQuery + '", "actionID": "' + actionID + '", "actionNameRoute": "' + actionNameRoute + '", "areHiddenGroupsVisible": "' + areHiddenGroupsVisible + '", "loadAllItems": "' + loadAllItems + '", "page": "' + page + '" }',

            success: function (response) {
                var result = jQuery.parseJSON(response.d);

                $('.flex-filter').html(result.FilterHTMLContent);

                $(loadOverlayPlaceholder).html(result.HTMLContent);

                $('#ViewMode').val(viewMode);
                $('.flex-view-modes input[type="button"]').removeClass('flex-selected');
                $("#ProductViewMode_" + viewMode).addClass('flex-selected');

                $('.flex-basket-spinner[data-flex!="true"]').FlexSpinner();
                $('img[data-flex-async-image-src]').FlexAsyncImageLoader();
                $('*[data-flex-html-tooltip]').FlexHtmlTooltip();

                if (areHiddenGroupsVisible)
                    $('#AreHiddenGroupsVisible').val(areHiddenGroupsVisible);

                $('.products-list').attr('data-flex-is-last-page', result.IsLastPage);

                $('#CurrentPage').val(page);

                //$(window).unbind('scroll', getNextSalePageEvent);

                //if (!result.IsLastPage)
                //    $('.products-list').SaleScrollPager();
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (getActionDetailProducts): ' + errorThrown);
            },

            beforeSend: function () {
                //abortAllRequests();
                // Loading animation.
                $(loadOverlayPlaceholder).FlexShowLoading();
                $(loadOverlayPlaceholder).parent().find('.other-parameters').hide();

                if (areHiddenGroupsVisible && $('#RefreshProductsState').val() != 'true')
                    $('.products-list').scrollTo();

                if ($('#RefreshProductsState').val() == 'true')
                    $(window).scrollTop(0);
            },

            complete: function () {
                //$('.products-list').FlexTecDocDynamicCross();

                $('.flex-drop-down[data-flex!="true"]').FlexDropDown();
                $('.flex-checkbox[data-flex!="true"]').FlexCheckbox();
                $('.flex-range-slider[data-flex!="true"]').FlexRangeSlider();
                $('.flex-filter .flex-extended > div').FlexFilterTabs();

                $('.products .flex-attributes[data-flex!="true"]').FlexCollapsibleAttributes();
                $('.products .flex-delivery-times[data-flex!="true"]').FlexCollapsibleDeliveryTimes();
                $('.flex-stocks[data-flex!="true"]').FlexStocks();

                if (isManufacturersModulExpanded) {
                    $(".flex-filter .flex-manufacturers .flex-title").addClass("flex-expanded");
                    $(".flex-filter .flex-manufacturers .flex-content").show();
                }

                if ($('.flex-tags').find('.flex-item').length > 0) {
                    $(".flex-remove-all-filters").each(function () {
                        $(this).show();
                    });
                } else {
                    $(".flex-remove-all-filters").each(function () {
                        $(this).hide();
                    });
                }
            }
        });
    }

    getActionDetailProductsPerPage = function (loadOverlayPlaceholder, sortBy, startIndex, actionID, actionNameRoute, areHiddenGroupsVisible, filtersQuery, event) {
        event.preventDefault();

        //var filteredManufacturers = [];

        //$('.flex-filter .flex-manufacturers').find('input[type="checkbox"]').each(function () {
        //    var element = $(this);

        //    if (element.is(':checked')) {
        //        filteredManufacturers.push(element.attr('value'));
        //    }
        //});

        var filteredManufacturers = [];

        if (getUrlHistoryValue('m-filter')) {
            var splittedManufacturers = getUrlHistoryValue('m-filter').toString().split('~');
            for (var i = 0; i < splittedManufacturers.length; i++) {
                if (splittedManufacturers[i].length > 0) {
                    filteredManufacturers.push(decodeURI(splittedManufacturers[i]));
                }
            }
        }

        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/GetActionDetailProductsPerPage',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "sortBy": "' + sortBy + '", "filteredManufacturers": ' + JSON.stringify(filteredManufacturers) + ', "parametersFilterQuery": "' + filtersQuery + '", "startIndex": ' + startIndex + ', "actionID": "' + actionID + '", "actionNameRoute": "' + actionNameRoute + '", "areHiddenGroupsVisible": "' + areHiddenGroupsVisible + '" }',

            success: function (response) {
                var result = jQuery.parseJSON(response.d);

                loadOverlayPlaceholder.append(result.HTMLContent);

                loadOverlayPlaceholder.FlexHideNextPageLoading();

                $('.flex-basket-spinner[data-flex!="true"]').FlexSpinner();
                $('img[data-flex-async-image-src]').FlexAsyncImageLoader();
                $('*[data-flex-html-tooltip]').FlexHtmlTooltip();

                $('.products-list').attr('data-flex-is-last-page', result.IsLastPage);

                var currentPage = parseInt($('#CurrentPage').val()) + 1;
                $('#CurrentPage').val(currentPage);

                //if (!result.IsLastPage)
                //    $('.products-list').SaleScrollPager();
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (getActionDetailProductsPerPage): ' + errorThrown);
            },

            beforeSend: function () {
                //abortAllRequests();
                // Loading animation.
                $('.products-list').find('.load-btns').remove();
                $('.products-list').find('.item-empty').remove();
                loadOverlayPlaceholder.FlexShowNextPageLoading();
            },

            complete: function () {
                //$('.products-list').FlexTecDocDynamicCross();
                $('.products .flex-attributes[data-flex!="true"]').FlexCollapsibleAttributes();
                $('.products .flex-delivery-times[data-flex!="true"]').FlexCollapsibleDeliveryTimes();
                $('.flex-stocks[data-flex!="true"]').FlexStocks();
            }
        });
    }



    getSubordinatedCustomerDetail = function (loadOverlayPlaceholder, customerID, viewType) {
        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/GetSubordinatedCustomerDetail',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "viewType": ' + viewType + ', "customerID": ' + customerID + ', "viewType": ' + viewType + ' }',

            success: function (response) {
                $(loadOverlayPlaceholder).html(response.d);

                $('.flex-tabs').find('a').removeClass('flex-selected');

                if (viewType == 0)
                    $('#InformationsTabButton').addClass('flex-selected');

                if (viewType == 1)
                    $('#DiscountsTabButton').addClass('flex-selected');

                $('.flex-product-groups-tree').FlexProductGroupsTree();
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (getSubordinatedCustomerDetail): ' + errorThrown);
            },

            beforeSend: function () {
                //abortAllRequests();
                // Loading animation.
                $(loadOverlayPlaceholder).FlexShowLoading();
            },

            complete: function () {
                $('.flex-checkbox[data-flex!="true"]').FlexCheckbox();
                $('.flex-drop-down[data-flex!="true"]').FlexDropDown();
            }
        });
    }





    navigateToLaximoParts = function (language, catalog, catalogName, parts, manufacturerID, vehicleID, unitID, ssd) {
        var selectedOEs = [];

        $('.flex-oe-part-table').find('.flex-pinned-items .flex-item').each(function () {
            selectedOEs.push($(this).attr('data-flex-oe'));
        });

        window.location.href = '/' + language + '/' + catalog + '/' + catalogName + '/' + parts + '/' + selectedOEs.join('~') + '/' + manufacturerID + '/' + vehicleID + '/' + unitID + '?ssd=' + ssd;
    }

    navigateToLevamParts = function (language, catalog, catalogName, parts, manufacturerID, vehicleID, unitID, ssd, link) {
        var selectedOEs = [];

        $('.flex-oe-part-table').find('.flex-pinned-items .flex-item').each(function () {
            selectedOEs.push($(this).attr('data-flex-image-code') + ';' + $(this).attr('data-flex-oe'));
        });

        window.location.href = '/' + language + '/' + catalog + '/' + catalogName + '/' + parts + '/' + manufacturerID + '/' + vehicleID + '/' + unitID + '/' + ssd + '/?link=' + link + '&oes=' + selectedOEs.join('~');
    }

    toggleDifferentDeliveryAddress = function (isChecked) {
        if (isChecked) {

            $('.flex-delivery-informations').slideDown({ duration: 600, easing: 'easeOutExpo' });
            $('#OrderFormDeliveryEmail').val($('#RegistrationFormEmail').val());
            $('#OrderFormDeliveryPhone').val($('#RegistrationFormPhone').val());

            if ($(".flex-billing-informations").attr('data-flex-is-logged') != "true") {
                $('#OrderFormDeliveryEmail').val($('#OrderFormEmail').val());
                $('#OrderFormDeliveryPhone').val($('#OrderFormPhone').val());
            }
        }
        else {
            $('.flex-delivery-informations').slideUp({ duration: 400, easing: 'easeInBack' });
        }
    }

    toggleTransportBranches = function () {
        if ($('#RegistrationTransportMethod').find('option:selected').attr('data-flex-is-personal-pick') === "true") {
            $('.personal-pickup-branch-container').slideDown({ duration: 600, easing: 'easeOutExpo' });
        } else {
            $('.personal-pickup-branch-container').slideUp({ duration: 400, easing: 'easeInBack' });
        }
    }


    toggleIAmBuyingOnCompany = function (isChecked, registerMeCheckboxID) {
        if (isChecked) {
            $('.flex-company-informations').slideDown({ duration: 600, easing: 'easeOutExpo' });
        }
        else {
            $('.flex-company-informations').slideUp({ duration: 400, easing: 'easeInBack' });
            $('#OrderFormCompanyName').val('');
            $('#OrderFormIC').val('');
            $('#OrderFormDIC').val('');
            $('#IsPayerOfVAT_FlexCheckbox').removeClass('flex-selected');
        }
        if (isChecked)
            $(registerMeCheckboxID).prop('checked', true).change();
    }

    toggleVisibleSendOrderConfirmationOnEmailField = function (isChecked) {
        if (isChecked) {
            $('.flex-order-email-confirmation').slideDown({ duration: 600, easing: 'easeOutExpo' });
        }
        else {
            $('.flex-order-email-confirmation').slideUp({ duration: 400, easing: 'easeInBack' });
        }
    }

    toggleIsVATPayer = function (sender) {
        if ($(sender).is(':checked')) {
            $('#OrderFormDIC').attr('data-flex-mandatory', 'true');
        } else {
            $('#OrderFormDIC').removeAttr('data-flex-mandatory');
            $('#OrderFormDIC').removeData('flex-mandatory');
            $('#OrderFormDIC').val('');
        }
    }

    prepareOrder = function () {
        var companyName = $('#OrderFormCompanyName').val();
        var name = $('#OrderFormName').val();
        var street = $('#OrderFormStreet').val();
        var city = $('#OrderFormCity').val();
        var zipCode = $('#OrderFormZIPCode').val();
        var stateID = $('#OrderFormState').val();
        var ic = $('#OrderFormIC').val();
        var dic = $('#OrderFormDIC').val();
        var isDeliveryAddressDifferent = $('#IsDeliveryAddressDifferent').is(':checked');
        var registerNow = $('#IWantToRegisterNow').is(':checked');

        var username = $('#OrderFormRegisterUsername').val();
        var password = $('#OrderFormRegisterPassword').val();
        var passwordConfirm = $('#OrderFormRegisterPasswordConfirm').val();

        var deliveryName = $('#OrderFormDeliveryName').val();
        var deliveryStreet = $('#OrderFormDeliveryStreet').val();
        var deliveryCity = $('#OrderFormDeliveryCity').val();
        var deliveryZIPCode = $('#OrderFormDeliveryZIPCode').val();
        var deliveryStateID = $('#OrderFormDeliveryState').val();

        var transportMethod = $('input[name=TransportMethod]:checked').val(); //$('#OrderTransportMethod').val();
        var stockID = $('#OrderFormStock').val();
        var deliveryNotes = $('#OrderFormDeliveryNotes').val();

        var productsNotOnStock = $('#OrderFormProductsNotOnStock').val();
        var paymentType = $('input[name=PaymentMethod]:checked').val(); //$('#OrderFormPayment').val();
        var confirmationEmail = $('#OrderFormEmail').val();

        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/PrepareOrder',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "companyName": "' + companyName + '", "name": "' + name + '", "street": "' + street + '", "city": "' + city + '", "zipCode": "' + zipCode + '", "stateID": "' + stateID + '", "ic": "' + ic + '", "dic": "' + dic + '", "isDeliveryAddressDifferent": ' + isDeliveryAddressDifferent + ', "registerNow": ' + registerNow + ', "username": "' + username + '", "password": "' + password + '", "passwordConfirm": "' + passwordConfirm + '", "deliveryName": "' + deliveryName + '", "deliveryStreet": "' + deliveryStreet + '", "deliveryCity": "' + deliveryCity + '", "deliveryZIPCode": "' + deliveryZIPCode + '", "deliveryStateID": "' + deliveryStateID + '", "transportMethod": "' + transportMethod + '", "stockID": "' + stockID + '", "deliveryNotes": "' + deliveryNotes + '", "productsNotOnStock": "' + productsNotOnStock + '", "paymentType": "' + paymentType + '", "confirmationEmail": "' + confirmationEmail + '" }',

            success: function (response) {
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (prepareOrder): ' + errorThrown);
            },

            beforeSend: function () {
            },

            complete: function () {
            }
        });
    }


    changeDefaultSearchMethod = function (type) {
        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/ChangeDefaultSearchMethod',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "type": ' + type + ' }',

            success: function (response) {
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (changeDefaultSearchMethod): ' + errorThrown);
            },

            beforeSend: function () {
            },

            complete: function () {
            }
        });
    }


    getAllACIManufacturers = function (loadOverlayPlaceholder) {
        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/GetAllACIManufacturers',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{}',

            success: function (response) {
                $(loadOverlayPlaceholder).html(response.d);
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (getAllACIManufacturers): ' + errorThrown);
            },

            beforeSend: function () {
                // Loading animation.
                $(loadOverlayPlaceholder).FlexShowLoading();
            },

            complete: function () {
            }
        });
    }

    getACIManufacturers = function (loadOverlayPlaceholder, name, watermarkText) {
        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/GetACIManufacturers',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "name": "' + name + '", "watermarkText": "' + watermarkText + '" }',

            success: function (response) {
                $(loadOverlayPlaceholder).html(response.d);
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (getACIManufacturers): ' + errorThrown);
            },

            beforeSend: function () {
                //abortAllRequests();
                // Loading animation.
                $(loadOverlayPlaceholder).FlexShowLoading();
            },

            complete: function () {
            }
        });
    }

    addFavoriteACIManufacturer = function (loadOverlayPlaceholder, manufacturerID, searchedName, watermarkText) {
        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/AddFavoriteACIManufacturer',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "manufacturerID": "' + manufacturerID + '", "searchedName": "' + searchedName + '", "watermarkText": "' + watermarkText + '" }',

            success: function (response) {
                var result = jQuery.parseJSON(response.d);

                $(loadOverlayPlaceholder).html(result.HTMLContent);

                if (result.IsValid) {
                    flexShowToastInfo(result.SuccessText, false, '', '');
                } else {
                    flexShowToastError(result.ErrorText);
                }
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (addFavoriteACIManufacturer): ' + errorThrown);
            },

            beforeSend: function () {
                // Loading animation.
                $(loadOverlayPlaceholder).FlexShowLoadingOverlay();
            },

            complete: function () {
            }
        });
    }

    removeFavoriteACIManufacturer = function (loadOverlayPlaceholder, manufacturerID, searchedName, watermarkText) {
        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/RemoveFavoriteACIManufacturer',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "manufacturerID": "' + manufacturerID + '", "searchedName": "' + searchedName + '", "watermarkText": "' + watermarkText + '" }',

            success: function (response) {
                var result = jQuery.parseJSON(response.d);

                $(loadOverlayPlaceholder).html(result.HTMLContent);

                if (result.IsValid) {
                    flexShowToastInfo(result.SuccessText, false, '', '');
                } else {
                    flexShowToastError(result.ErrorText);
                }
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (removeFavoriteACIManufacturer): ' + errorThrown);
            },

            beforeSend: function () {
                // Loading animation.
                $(loadOverlayPlaceholder).FlexShowLoadingOverlay();
            },

            complete: function () {
            }
        });
    }






    validateRegistrationLoginInformations = function (loadOverlayPlaceholder, validationOnly) {
        var loginEmail = $('#OrderFormRegisterLogin').val();
        var password = $('#OrderFormRegisterPassword').val();
        var passwordConfirm = $('#OrderFormRegisterPasswordConfirm').val();

        $(loadOverlayPlaceholder).find('input').removeClass('flex-error');

        return $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/ValidateRegistrationLoginInformations',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            async: false,
            data: '{ "loginEmail": "' + safeUrlEncode(loginEmail) + '", "password": "' + safeUrlEncode(password) + '", "passwordConfirm": "' + safeUrlEncode(passwordConfirm) + '" }',

            success: function (response) {
                var result = jQuery.parseJSON(response.d);

                if (result.IsValid) {
                    if (!validationOnly) {
                        $('#OrderFormEmail').val($('#OrderFormRegisterLogin').val());

                        $('.flex-row.flex-confirm-register-informations-step').slideUp(400, function () {
                            $('.flex-row.flex-confirm-register-informations-step').remove();
                        });

                        $('.flex-registration-step-2').slideDown(600, function () {
                            $('.flex-continue-in-order').show();
                        });
                    }
                } else {
                    flexShowToastError(result.ErrorText);

                    if (result.WrongValue === 'loginEmail')
                        $('#OrderFormRegisterLogin').addClass('flex-error');

                    if (result.WrongValue === 'password')
                        $('#OrderFormRegisterPassword').addClass('flex-error');

                    if (result.WrongValue === 'passwordConfirm')
                        $('#OrderFormRegisterPasswordConfirm').addClass('flex-error');
                }
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (validateRegistrationLoginInformations): ' + errorThrown);
            },

            beforeSend: function () {
                // Loading animation.
            },

            complete: function () {

            }
        });
    }

    searchReturnPart = function (loadOverlayPlaceholder, searchPhraseElement, searchFormResultElement, searchFormResultItemsElement) {
        var searchPhrase = $(searchPhraseElement).val();
        var allreadyExists = false;

        var formValid = validateForm([$(searchPhraseElement)], false);

        if (!allreadyExists && formValid) {
            var dataToSend = {
                'searchPhrase': searchPhrase
            };
            $.ajax({
                type: 'POST',
                url: '/AjaxWS.svc/SearchReturnPart',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                data: JSON.stringify(dataToSend),

                success: function (response) {
                    var result = jQuery.parseJSON(response.d);

                    if (result.IsValid) {
                        //$(searchFormResultItemsElement).empty();
                        $(searchFormResultElement).prepend(result.HTMLContent);
                        if (!$(searchFormResultElement).is('visible')) {
                            $(searchFormResultElement).slideDown();
                            $("#ReturnItemSearchForm").slideUp();
                        }
                        $(searchPhraseElement).val('');

                        $('#ReturnFormProducts').FlexDropDown();
                        $('#ReturnFormReason').FlexDropDown();
                    }
                    else {
                        flexShowToastError(result.ErrorText);
                    }
                },

                error: function (xhr, textStatus, errorThrown) {
                    if (xhr.status != 0 && xhr.statusText != 'abort')
                        alert('There is an error in your request (searchReturnPart): ' + errorThrown);
                },

                beforeSend: function () {
                    // Loading animation.
                    $(loadOverlayPlaceholder).FlexShowLoadingOverlay();
                },

                complete: function () {
                    $(loadOverlayPlaceholder).FlexHideLoadingOverlay();
                }
            });
        }
    };

    searchReturnForm = function (loadOverlayPlaceholder) {
        var formValid = validateForm([$("#ReturnFormProducts")], false);

        if (formValid) {
            var dataToSend = {
                'productID': parseInt($('#ReturnFormProducts option:selected').val())
            };
            $.ajax({
                type: 'POST',
                url: '/AjaxWS.svc/SearchReturnForm',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                data: JSON.stringify(dataToSend),

                success: function (response) {
                    var result = jQuery.parseJSON(response.d);

                    if (result.IsValid) {
                        $('.flex-delivery-note-search').empty();
                        $('.flex-delivery-note-search').prepend(result.HTMLContent);

                        if (result.ErrorText !== "") {
                            $('.flex-return-part-error-text').empty().append(result.ErrorText);
                            $('.flex-return-part-controls').slideUp();
                        } else {
                            $('.flex-return-part-error-text').empty();
                            $('.flex-return-part-controls').slideDown();
                        }
                    }
                    else {
                        flexShowToastError(result.ErrorText);
                    }
                },

                error: function (xhr, textStatus, errorThrown) {
                    if (xhr.status !== 0 && xhr.statusText !== 'abort')
                        alert('There is an error in your request (searchReturnPart): ' + errorThrown);
                },

                beforeSend: function () {
                    // Loading animation.
                    $(loadOverlayPlaceholder).FlexShowLoadingOverlay();
                },

                complete: function () {
                    $(loadOverlayPlaceholder).FlexHideLoadingOverlay();
                }
            });
        }
    };

    showICDPHFieldIfSlovakiaIsSelected = function (dropdownID, divID) {
        var stateID = $(dropdownID).val();
        if (stateID == 371) {
            $(divID).slideDown({ duration: 400, easing: 'easeInBack' });
        } else {
            $(divID).slideUp({ duration: 400, easing: 'easeInBack' });
        }
    }

    setPrivacyConsent = function (loadOverlayPlaceholder, type, state) {
        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/SetPrivacyConsent',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "type": "' + type + '", "state": "' + state + '" }',

            success: function (response) {
                var result = jQuery.parseJSON(response.d);

                $(loadOverlayPlaceholder).html(result);
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (setPrivacyConsent): ' + errorThrown);
            },

            beforeSend: function () {
                // Loading animation.
                $(loadOverlayPlaceholder).FlexShowLoadingOverlay();
            },

            complete: function () {
            }
        });
    }

    getProductGroupNode = function (loadOverlayPlaceholder, customerID, id, type) {
        if (!$(loadOverlayPlaceholder).hasClass('flex-selected')) {
            $.ajax({
                type: 'POST',
                url: '/AjaxWS.svc/GetProductGroupNode',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                data: '{ "customerID": ' + customerID + ', "id": ' + id + ', "type": ' + type + ' }',

                success: function (response) {
                    $(loadOverlayPlaceholder).append(response.d);

                    $(loadOverlayPlaceholder).FlexHideInlineLoadingOverlay();

                    $(loadOverlayPlaceholder).children().not('span:first').not('.flex-folders-count').not('.flex-controls').hide();
                    $(loadOverlayPlaceholder).children().not('span:first').not('.flex-folders-count').not('.flex-controls').slideDown(300);
                },

                error: function (xhr, textStatus, errorThrown) {
                    if (xhr.status != 0 && xhr.statusText != 'abort')
                        alert('There is an error in your request (getProductGroupNode): ' + errorThrown);
                },

                beforeSend: function () {
                    // Loading animation.
                    $(loadOverlayPlaceholder).FlexShowInlineLoadingOverlay();
                },

                complete: function () {
                }
            });
        }
    }


    getRegistrationTransportMethods = function (loadOverlayPlaceholder, token, isRegistrationSubordinatedCustomer) {
        var isDeliveryAddressDifferent = $('#IsDeliveryAddressDifferent').is(":checked");

        var stateID = -1;
        if (isDeliveryAddressDifferent) {
            if (parseInt($('#OrderFormDeliveryState option:selected').val()) > -1) {
                stateID = parseInt($('#OrderFormDeliveryState option:selected').val());
            } else {
                stateID = parseInt($('#RegistrationFormState option:selected').val());
            }
        } else {
            stateID = parseInt($('#RegistrationFormState option:selected').val());
        }

        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/GetRegistrationTransportMethods',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "stateID": "' + stateID + '","token": "' + $(token).val() + '", "isRegistrationSubordinatedCustomer": ' + isRegistrationSubordinatedCustomer + ' }',

            success: function (response) {
                var result = jQuery.parseJSON(response.d);
                $(loadOverlayPlaceholder).html(result.TransportsHTMLContent);
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status !== 0 && xhr.statusText !== 'abort')
                    alert('There is an error in your request (getRegistrationTransportMethods): ' + errorThrown);
            },

            beforeSend: function () {
                //abortAllRequests();
                // Loading animation.
                $(loadOverlayPlaceholder).FlexShowLoading();
            },

            complete: function () {
                $('.flex-drop-down[data-flex!="true"]').FlexDropDown();
            }
        });
    }


    getSelectVehicleWizardSteps = function (loadOverlayPlaceholder, step) {
        var manufacturerID = $('#ManufacturerSelector option:selected').val() ? $('#ManufacturerSelector option:selected').val() : -1;
        var modelID = $('#ModelSelector option:selected').val() ? $('#ModelSelector option:selected').val() : -1;
        var engineID = $('#EngineSelector option:selected').val() ? $('#EngineSelector option:selected').val() : -1;

        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/GetSelectVehicleWizardSteps',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "manufacturerID": "' + manufacturerID + '", "modelID": "' + modelID + '", "engineID": "' + engineID + '" }',

            success: function (response) {
                $(loadOverlayPlaceholder).html(response.d);
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status !== 0 && xhr.statusText !== 'abort')
                    alert('There is an error in your request (getSelectVehicleWizardSteps): ' + errorThrown);
            },

            beforeSend: function () {
                //abortAllRequests();
                // Loading animation.
                //$(loadOverlayPlaceholder).FlexShowLoading();

                if (step === 1) {
                    $('#ManufacturerSelector_FlexDropDown dt .flex-drop-down-link').FlexShowInlineLoadingOverlay();
                }

                if (step === 2) {
                    $('#ModelSelector_FlexDropDown dt .flex-drop-down-link').FlexShowInlineLoadingOverlay();
                }

                if (step === 3) {
                    $('#EngineSelector_FlexDropDown dt .flex-drop-down-link').FlexShowInlineLoadingOverlay();
                }
            },

            complete: function () {

                $('.flex-drop-down[data-flex!="true"]').FlexDropDown();

                if (step === 1) {
                    $('#ModelSelector_FlexDropDown dt .flex-drop-down-link').click();
                }

                if (step === 2) {
                    $('#EngineSelector_FlexDropDown dt .flex-drop-down-link').click();
                }


                if (manufacturerID != -1) {
                    $("#ManufacturerSelector_FlexDropDown").addClass("selected");
                }

                if (modelID != -1) {
                    $("#ModelSelector_FlexDropDown").addClass("selected");
                }

                if (engineID != -1) {
                    $("#EngineSelector_FlexDropDown").addClass("selected");
                }
            }
        });
    }


    getPriceOfferPreview = function (loadOverlayPlaceholder, basketID) {
        var discountCalculationType = $('#DiscountCalculationTypeSelector').val();
        var discount = $('#Discount').val();
        var note = $('#Note').val();

        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/GetPriceOfferPreview',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "basketID": "' + basketID + '", "discountCalculationType": ' + discountCalculationType + ', "discount": "' + discount + '", "note": "' + note + '" }',

            success: function (response) {
                var result = jQuery.parseJSON(response.d);
                $(loadOverlayPlaceholder).html(result.HTMLContent);
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (getPriceOfferPreview): ' + errorThrown);
            },

            beforeSend: function () {
                // Loading animation.
                // $(loadOverlayPlaceholder).FlexShowLoading();
                abortAjaxRequest('/AjaxWS.svc/GetPriceOfferPreview');
            },

            complete: function () {
            }
        });
    }

    getSelectEBCUniversalCarsTreeWizardSteps = function (loadOverlayPlaceholder, step) {
        var manufacturerID = $('#EbcManufacturerSelector option:selected').val() ? $('#EbcManufacturerSelector option:selected').val() : -1;
        var modelID = $('#EbcModelSelector option:selected').val() ? $('#EbcModelSelector option:selected').val() : -1;
        var engineID = $('#EbcEngineSelector option:selected').val() ? $('#EbcEngineSelector option:selected').val() : -1;
        var manufacturedYearID = $('#EbcManufacturedYearSelector option:selected').val() ? $('#EbcManufacturedYearSelector option:selected').val() : -1;
        var categoryID = $('#EbcCategorySelector option:selected').val() ? $('#EbcCategorySelector option:selected').val() : -1;
        var axisID = $('#EbcAxisSelector option:selected').val() ? $('#EbcAxisSelector option:selected').val() : -1;

        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/GetSelectEBCUniversalCarsTreeWizardSteps',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "manufacturerID": "' + manufacturerID + '", "modelID": "' + modelID + '", "engineID": "' + engineID + '", "manufacturedYearID": "' + manufacturedYearID + '", "categoryID": "' + categoryID + '", "axisID": "' + axisID + '" }',

            success: function (response) {
                $(loadOverlayPlaceholder).html(response.d);
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status !== 0 && xhr.statusText !== 'abort')
                    alert('There is an error in your request (getSelectEBCUniversalCarsTreeWizardSteps): ' + errorThrown);
            },

            beforeSend: function () {

                if (step === 1) {
                    $('#EbcManufacturerSelector_FlexDropDown dt .flex-drop-down-link').FlexShowInlineLoadingOverlay();
                }

                if (step === 2) {
                    $('#EbcModelSelector_FlexDropDown dt .flex-drop-down-link').FlexShowInlineLoadingOverlay();
                }

                if (step === 3) {
                    $('#EbcEngineSelector_FlexDropDown dt .flex-drop-down-link').FlexShowInlineLoadingOverlay();
                }

                if (step === 4) {
                    $('#EbcManufacturedYearSelector_FlexDropDown dt .flex-drop-down-link').FlexShowInlineLoadingOverlay();
                }

                if (step === 5) {
                    $('#EbcCategorySelector_FlexDropDown dt .flex-drop-down-link').FlexShowInlineLoadingOverlay();
                }

                if (step === 6) {
                    $('#EbcAxisSelector_FlexDropDown dt .flex-drop-down-link').FlexShowInlineLoadingOverlay();
                }
            },

            complete: function () {

                $('.flex-drop-down[data-flex!="true"]').FlexDropDown();

                if (step === 1) {
                    $('#EbcModelSelector_FlexDropDown dt .flex-drop-down-link').click();
                }

                if (step === 2) {
                    $('#EbcEngineSelector_FlexDropDown dt .flex-drop-down-link').click();
                }

                if (step === 3) {
                    $('#EbcManufacturedYearSelector_FlexDropDown dt .flex-drop-down-link').click();
                }

                if (step === 4) {
                    $('#EbcCategorySelector_FlexDropDown dt .flex-drop-down-link').click();
                }

                if (step === 5) {
                    $('#EbcAxisSelector_FlexDropDown dt .flex-drop-down-link').click();
                }
            }
        });
    }

    getSelectUniversalPartsCategoryWizardStep = function (loadOverlayPlaceholder, categoryID, rootCategoryID, autoFill) {
        var selectedCategoryID = $('#Category_' + categoryID).val();
        var level = $('#CategorySelector_' + categoryID).attr('data-level');

        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/GetSelectUniversalPartsCategoryWizardStep',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "selectedCategoryID": "' + selectedCategoryID + '", "rootCategoryID": "' + rootCategoryID + '", }',

            success: function (response) {
                if (response.d.length > 0) {
                    $('#CategorySelector_' + categoryID).after(response.d);
                    $('#CategorySelector_' + selectedCategoryID).attr('data-level', $('.category-selector').length);
                }
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status !== 0 && xhr.statusText !== 'abort')
                    alert('There is an error in your request (getSelectUniversalPartsCategoryWizardStep): ' + errorThrown);
            },

            beforeSend: function () {
                $('#Category_' + categoryID + '_FlexDropDown dt .flex-drop-down-link').FlexShowInlineLoadingOverlay();

                $('.category-selector').filter(function () {
                    return $(this).attr('data-level') > level;
                }).remove();
            },

            complete: function () {
                $('.flex-drop-down[data-flex!="true"]').FlexDropDown();
                $('#Category_' + categoryID + '_FlexDropDown dt .flex-drop-down-link').FlexHideInlineLoadingOverlay();

                if (!autoFill)
                    $('#Category_' + selectedCategoryID + '_FlexDropDown dt .flex-drop-down-link').click();

                $('#RootCategory_' + rootCategoryID + ' .search-button').prop("disabled", false);

                var idsPath = getUrlHistoryValue('path');

                if (idsPath != false && autoFill) {
                    var idsPathSplitted = idsPath.split('~');

                    var currentCategoryIndex = idsPathSplitted.indexOf(categoryID);

                    $('#Category_' + idsPathSplitted[currentCategoryIndex + 1] + '_FlexDropDown dd .flex-drop-down-link[data-value="' + idsPathSplitted[currentCategoryIndex + 2] + '"]').trigger('click', true);
                }
            }
        });
    }

    addToSearchHistory = function (name, description, searchNumber, classificationID, manufacturerID, modelID, engineID, manufacturerName, modelName, engineName, searchType, searchSubType) {
        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/AddToSearchHistory',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "name": "' + name + '", "description": "' + description + '", "searchNumber": "' + searchNumber + '", "classificationID": "' + classificationID + '", "manufacturerID": "' + manufacturerID + '", "modelID": "' + modelID + '", "engineID": "' + engineID + '", "manufacturerName": "' + manufacturerName + '", "modelName": "' + modelName + '", "engineName": "' + engineName + '", "searchType": "' + searchType + '", "searchSubType": "' + searchSubType + '" }',

            success: function (response) {
                //console.log('History has been written!');
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (addToSearchHistory): ' + errorThrown);
            },

            beforeSend: function () {
            },

            complete: function () {
            }
        });
    }
         

    confirmCookieConsent = function (ev, necessaryOnly) {
        applyCookiesUserSettings(necessaryOnly, ev);

        window.dataLayer = window.dataLayer || [];
        function gtag() { dataLayer.push(arguments); }

        // Set updated Google consent based on values selected by user.
        let marketingConsentState = areMarketingCookiesEnabled ? 'granted' : 'denied';
        let analyticalConsentState = areAnalyticalCookiesEnabled ? 'granted' : 'denied';

        gtag('consent', 'update', {
            'ad_storage': marketingConsentState,
            'ad_user_data': marketingConsentState,
            'ad_personalization': marketingConsentState,
            'analytics_storage': analyticalConsentState
        });

        setCookiesToConfirmCookieBar(false);
        $.cookie('areAnalyticalCookiesEnabled', areAnalyticalCookiesEnabled, { expires: 999, path: '/' });
        $.cookie('areMarketingCookiesEnabled', areMarketingCookiesEnabled, { expires: 999, path: '/' });

        $.ajax({
            type: 'POST',
            url: '/AjaxWS.svc/ConfirmCookieConsent',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{ "areAnalyticalCookiesEnabled": ' + areAnalyticalCookiesEnabled + ', "areMarketingCookiesEnabled": ' + areMarketingCookiesEnabled + ' }',

            success: function (response) {
                console.log('Consent has been written!');
            },

            error: function (xhr, textStatus, errorThrown) {
                if (xhr.status != 0 && xhr.statusText != 'abort')
                    alert('There is an error in your request (confirmCookieConsent): ' + errorThrown);
            },

            beforeSend: function () {
            },

            complete: function () {
            }
        });

        makeCookieBarInvisible();
    }    

}(jQuery));;
/// <reference path="/JScripts/jquery-1.9.1-vsdoc.js" />

(function ($) {

    appSuccess = function (response) {
        try {
            var data = JSON.parse(response.d);
            console.log(data);
            if (data) {
                if (data.notify) {
                    // Notify: text, success, timeout
                    flexShowToastError(data.text);
                    return data.success;
                }
            }
        } catch (error) {
            console.log("JS parse error");
        }

        return true;
    }


    showSearchLoading = function () {
        $('.flex-search .flex-search-button').hide(0);
        $('.flex-search .flex-progress').show(0);
    }

    showInvoiceSearchLoading = function () {
        $('.flex-invoice-search .flex-invoice-search-button').hide(0);
        $('.flex-invoice-search .flex-progress').show(0);
    }

    changeStatePrefix = function (statePlaceholder, phonePrefixPlaceholder, phonePlaceholder) {
        if ($(phonePlaceholder).val() === '') {
            var stateID = $(statePlaceholder).val();
            $(phonePrefixPlaceholder + 'option[selected=selected]').removeAttr('selected');
            $(phonePrefixPlaceholder).val(stateID).attr('selected', 'selected');
            $(phonePrefixPlaceholder + '_FlexDropDown dt .flex-drop-down-link').html('<div class=\"flag\" style=\"background-image: url(/Plugins/FlexView/Images/Flags/' + $(phonePrefixPlaceholder + ' option:selected').attr('data-icon') + '.png);\"></div>' + '<span class=\"flex-text\">' + $(phonePrefixPlaceholder + ' option:selected').text() + '</span>' + '<span class=\"flex-drop-down-value\">' + $(phonePrefixPlaceholder + ' option:selected').val() + '</span>');
        }
    }

    changeNumberPlateCountrySource = function (sender) {
        var countryID = $(sender).parent().find("option").val();
        $(sender).parent().find("span.selected").data("value", countryID);
    }

    rememberUserLogin = function (indicator, loginInput) {
       
        var isRememerLoginChecked = $("#"+indicator).is(":checked");        
        var login = $("#"+loginInput).val();       
        if (isRememerLoginChecked && login)
            localStorage.setItem('RememberedUserLogin', login);
        else
            localStorage.setItem('RememberedUserLogin', '');
    }

    getRememberedUserLogin = function (indicator, loginInput) {
  
        var login = localStorage.getItem('RememberedUserLogin');
      
        if (login !== undefined && login !== '') {
            $("#"+loginInput).val(login);
            $("#"+indicator).prop('checked', true);
        }
        else {
            $("#"+indicator).prop('checked', false);
        }

    }  


    removeAttributeFilter = function (genericArticleKey, attributeKey, attributeType) {
        if (attributeType !== 1) {
            $('.flex-parameters').find('input[type="checkbox"][data-flex-generic-article-key="' + genericArticleKey + '"][data-flex-attribute-key="' + attributeKey + '"]').prop('checked', false);
            $('.flex-parameters').find('input[type="checkbox"][data-flex-generic-article-key="' + genericArticleKey + '"][data-flex-attribute-key="' + attributeKey + '"]').change();
        } else {
            var sliderElement = $('.flex-range-slider[data-flex-generic-article-key="' + genericArticleKey + '"][data-flex-attribute-key="' + attributeKey + '"]');
            var snapSlider = document.getElementById(sliderElement.attr('id'));

            var values = $('.flex-range-slider[data-flex-generic-article-key="' + genericArticleKey + '"][data-flex-attribute-key="' + attributeKey + '"]').attr('data-flex-values').replace('.', ',');

            var valueArray = values.split(';');

            valueArray.sort(function (a, b) {
                return Number(a) - Number(b);
            });

            var minValue = parseFloat(valueArray[0].replace(',', '.'));
            var maxValue = parseFloat(valueArray[valueArray.length - 1].replace(',', '.'));

            snapSlider.noUiSlider.set([minValue, maxValue]);
        }
    }

    removeAllManufacturerFilters = function () {
        $('.products .flex-filter').find('.flex-extended').attr('data-flex-manufacturers-filters-query', '');

        $('.flex-manufacturers').find('input[type="checkbox"]').each(function () {
            $(this).prop('checked', false);
            //Need to be investigated more 
            // $(this).change();
        });
    }

    removeAllAttributeFilters = function () {
        $('.products .flex-filter').find('.flex-extended').attr('data-flex-tecdoc-filters-query', '');

        $('.flex-parameters').find('input[type="checkbox"]').each(function () {
            $(this).prop('checked', false);
            //Need to be investigated more 
            // $(this).change();
        });

        $('.flex-parameters').find('.flex-range-slider').each(function () {
            //var snapSlider = document.getElementById($(this).attr('ID'));

            //var values = $(this).attr('data-flex-values').replace('.', ',');

            //var valueArray = values.split(';');

            //var minValue = parseFloat(valueArray[0].replace(',', '.'));
            //var maxValue = parseFloat(valueArray[valueArray.length - 1].replace(',', '.'));

            //snapSlider.noUiSlider.set([minValue, maxValue]);


            var snapSlider = document.getElementById($(this).attr('id'));

            var values = $(this).attr('data-flex-values').replace('.', ',');

            var valueArray = values.split(';');

            valueArray.sort(function (a, b) {
                return Number(a) - Number(b);
            });

            var minValue = parseFloat(valueArray[0].replace(',', '.'));
            var maxValue = parseFloat(valueArray[valueArray.length - 1].replace(',', '.'));

            snapSlider.noUiSlider.set([minValue, maxValue]);
        });
    }

    setZasilkovnaBranchPosition = function () {
        var inputID = $('input[name=TransportMethod][data-flex-is-zasilkovna=true]').attr("id");

        if (inputID !== undefined) {
            $('li[data-target-input-id="' + inputID + '"]').append($('.flex-zasilkovna-branch'));
        }
    };

    showRegistrationOrderForm = function () {
        $('.flex-first-order-method').slideUp({ duration: 400 });
        $('.flex-registration-step-1').slideDown({ duration: 600 });
    };

    showOrderForm = function () {
        $('.flex-first-order-method').slideUp({ duration: 400 });
        $('.flex-registration-step-2').slideDown(600, function () {
            $('.flex-continue-in-order').show();
        });
    };

    showLostPasswordForm = function () {
        $('.flex-login-form').find('span').first().click();
        $('.flex-login-form').find('span.flex-login-form-lost-password-button').first().click();
    };

    redirectToTecDocConstructionGroup = function (languageRoute, catalogRoute, tecdocRoute, vehicleTypeRoute) {
        var manufacturerID = $('#ManufacturerSelector option:selected').val() ? $('#ManufacturerSelector option:selected').val() : -1;
        var modelID = $('#ModelSelector option:selected').val() ? $('#ModelSelector option:selected').val() : -1;
        var engineID = $('#EngineSelector option:selected').val() ? $('#EngineSelector option:selected').val() : -1;

        var manufacturerRouteName = $('#ManufacturerSelector option:selected').attr('data-flex-route-name');
        var modelRouteName = $('#ModelSelector option:selected').attr('data-flex-route-name');
        var engineRouteName = $('#EngineSelector option:selected').attr('data-flex-route-name');

        window.location.href = '/' + languageRoute + '/' + catalogRoute + '/' + tecdocRoute + '/' + vehicleTypeRoute + '/' + manufacturerRouteName + '/' + modelRouteName + '/' + engineRouteName + '/' + manufacturerID + '/' + modelID + '/' + engineID;
    };

    redirectToUniversalParts = function (baseRoute, categoryID) {
        var ids = categoryID
        var routeName = "";

        $('#RootCategory_' + categoryID + ' .category-selector').each(function () {

            var isSelected = $(this).find('dl dt .flex-drop-down-link .flex-drop-down-value').text() != 'undefined' && $(this).find('dl dt .flex-drop-down-link .flex-drop-down-value').text() != '-1';
            var selectedCategory = $(this).find('option:selected');


            if (isSelected) {
                routeName = selectedCategory.attr('data-route-name');

                ids += '~' + selectedCategory.val();
            }
        });

        window.location.href = baseRoute + '/' + routeName + '/' + ids + '/?path=' + ids;
    };

    closeCustomPopup = function (guid) {

        $('#CustomPopup_' + guid).fadeOut(600, function () {
            $('#CustomPopup_' + guid).remove();
        });

        if ($('.flex-custom-popup').length == 1) {
            $('.flex-custom-popup-container').fadeOut(600);
        }
    };

    closeMergeAccountPopup = function () {

        $('#MergeAccountsPopup').fadeOut(600, function () {
            $('#MergeAccountsPopup').remove();
        });

        $('.merge-accounts-popup-container').fadeOut(600, function () {
            $('.merge-accounts-popup-container').remove();
        });
    };

    copyToClipboard = function (e) {
        e.preventDefault();
        let element = $(e.target);
        let successMessage = element.attr("data-success-text");
        let codeValue = element.attr("data-code-text");
        if (window.clipboardData) { // Internet Explorer
            window.clipboardData.setData("Text", codeValue);
        } else {
            navigator.clipboard.writeText(codeValue);
        }
        flexShowToastInfo(successMessage, false, '', '');
    }

    toggleBreakdownVisibility = function (sender) {
        var breakdownProducts = $(sender).parent().next();
        var buttonIcon = $(sender).find("i");

        if (buttonIcon.hasClass('fa-chevron-up')) {
            breakdownProducts.hide();
            buttonIcon.toggleClass("fa-chevron-up fa-chevron-down");
        } else {
            breakdownProducts.show();
            buttonIcon.toggleClass("fa-chevron-down fa-chevron-up");
        }
    };

    setZasilkovnaBranchPosition();

}(jQuery));

function getUrlHistoryValue(key) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] === key) { return pair[1]; }
    }
    return (false);
}

function getUrlPath() {
    return location.protocol + '//' + location.host + location.pathname;
}

function getParameterFromUrl(name) {

    var url_string = window.location.href;
    var url = new URL(url_string);
    var parameter = url.searchParams.get(name);

    return parameter;

}



function divZoom(min, max, step, initZoom, viewport) {
    $("#SchemeImage").on("load", function () {
        var ua = window.navigator.userAgent;
        var msie = ua.indexOf("MSIE ") > 0;

        //$(viewport).kinetic();

        Draggable.create(viewport, { type: "scroll", edgeResistance: 0.95, throwProps: false });

        var fitWidthScale = 0;
        var fitHeightScale = 0;
        var minScale = 0;

        var fullWidth = $(".Zoom img").width();
        var fullHeight = $(".Zoom img").height();

        fitWidthScale = $(viewport).width() / $(".Zoom img").width();
        fitHeightScale = $(viewport).height() / $(".Zoom img").height();

        if (fitWidthScale < fitHeightScale) {
            minScale = fitWidthScale;
        } else {
            minScale = fitHeightScale;
        }

        var Zoom = fitWidthScale;

        if (!msie) {
            $(".Zoom").width(fullWidth * Zoom);
            $(".Zoom").height(fullHeight * Zoom);
        } else {
            $(".Zoom").width(fullWidth * Zoom);
            $(".Zoom").height(fullHeight * Zoom);
        }

        $(".Zoom").css({
            '-webkit-transform': 'scale(' + Zoom + ')',
            '-moz-transform': 'scale(' + Zoom + ')',
            '-ms-transform': 'scale(' + Zoom + ')',
            '-o-transform': 'scale(' + Zoom + ')',
            'transform': 'scale(' + Zoom + ')'
        });

        customScrollbar(".ViewportWrapper", ".ScrollViewport", ".Zoom");

        $("#ZoomInButton").on("click", function (event) {
            if (Zoom < max) {
                Zoom += step * 2;

                if (Zoom > 1)
                    Zoom = 1;

                $(".Zoom").width(fullWidth * Zoom);
                $(".Zoom").height(fullHeight * Zoom);

                $(".Zoom").css({
                    '-webkit-transform': 'scale(' + Zoom + ')',
                    '-moz-transform': 'scale(' + Zoom + ')',
                    '-ms-transform': 'scale(' + Zoom + ')',
                    '-o-transform': 'scale(' + Zoom + ')',
                    'transform': 'scale(' + Zoom + ')'
                });

                customScrollbar(".ViewportWrapper", ".ScrollViewport", ".Zoom");
            }
        });

        $("#ZoomOutButton").on("click", function (event) {
            if (Zoom > minScale) {
                Zoom -= step * 2;

                if (Zoom < minScale)
                    Zoom = minScale;

                $(".Zoom").width(fullWidth * Zoom);
                $(".Zoom").height(fullHeight * Zoom);

                $(".Zoom").css({
                    '-webkit-transform': 'scale(' + Zoom + ')',
                    '-moz-transform': 'scale(' + Zoom + ')',
                    '-ms-transform': 'scale(' + Zoom + ')',
                    '-o-transform': 'scale(' + Zoom + ')',
                    'transform': 'scale(' + Zoom + ')'
                });

                customScrollbar(".ViewportWrapper", ".ScrollViewport", ".Zoom");
            }
        });

        $("#MinimizeButton").on("click", function (event) {
            Zoom = minScale;

            $(".Zoom").width(fullWidth * Zoom);
            $(".Zoom").height(fullHeight * Zoom);

            $(".Zoom").css({
                '-webkit-transform': 'scale(' + Zoom + ')',
                '-moz-transform': 'scale(' + Zoom + ')',
                '-ms-transform': 'scale(' + Zoom + ')',
                '-o-transform': 'scale(' + Zoom + ')',
                'transform': 'scale(' + Zoom + ')'
            });

            customScrollbar(".ViewportWrapper", ".ScrollViewport", ".Zoom");
        });

        $("#MaximizeButton").on("click", function (event) {
            Zoom = 1;

            $(".Zoom").width(fullWidth * Zoom);
            $(".Zoom").height(fullHeight * Zoom);

            $(".Zoom").css({
                '-webkit-transform': 'scale(' + Zoom + ')',
                '-moz-transform': 'scale(' + Zoom + ')',
                '-ms-transform': 'scale(' + Zoom + ')',
                '-o-transform': 'scale(' + Zoom + ')',
                'transform': 'scale(' + Zoom + ')'
            });

            customScrollbar(".ViewportWrapper", ".ScrollViewport", ".Zoom");
        });

        $(viewport).on("mousewheel", function (event) {
            if (event.deltaY === 1 && Zoom < max) {
                Zoom += step;
                if (Zoom > 1)
                    Zoom = 1;
                $(".Zoom").width(fullWidth * Zoom);
                $(".Zoom").height(fullHeight * Zoom);

                $(".Zoom").css({
                    '-webkit-transform': 'scale(' + Zoom + ')',
                    '-moz-transform': 'scale(' + Zoom + ')',
                    '-ms-transform': 'scale(' + Zoom + ')',
                    '-o-transform': 'scale(' + Zoom + ')',
                    'transform': 'scale(' + Zoom + ')'
                });

                customScrollbar(".ViewportWrapper", ".ScrollViewport", ".Zoom");
            } else if (event.deltaY === -1 && Zoom > minScale) {
                Zoom -= step;

                if (Zoom < minScale)
                    Zoom = minScale;

                $(".Zoom").width(fullWidth * Zoom);
                $(".Zoom").height(fullHeight * Zoom);

                $(".Zoom").css({
                    '-webkit-transform': 'scale(' + Zoom + ')',
                    '-moz-transform': 'scale(' + Zoom + ')',
                    '-ms-transform': 'scale(' + Zoom + ')',
                    '-o-transform': 'scale(' + Zoom + ')',
                    'transform': 'scale(' + Zoom + ')'
                });

                customScrollbar(".ViewportWrapper", ".ScrollViewport", ".Zoom");
            }

            event.preventDefault();
        });


    }).each(function () {
        if (this.complete) $(this).trigger('load');
    });
}

function levamDivZoom(min, max, step, initZoom, viewport) {
    $("#SchemeImage").on("load", function () {
        var ua = window.navigator.userAgent;
        var msie = ua.indexOf("MSIE ") > 0;

        //$(viewport).kinetic();

        Draggable.create(viewport, { type: "scroll", edgeResistance: 0.95, throwProps: false });

        var fitWidthScale = 0;
        var fitHeightScale = 0;
        var minScale = 0;

        var fullWidth = $(".Zoom img").width();
        var fullHeight = $(".Zoom img").height();

        $('.ClickArea').each(function (index) {
            $(this).css('margin-top', (fullHeight / 100 * parseFloat($(this).attr('data-top'))) + 'px');
            $(this).css('margin-left', (fullWidth / 100 * parseFloat($(this).attr('data-left'))) + 'px');
        });

        fitWidthScale = $(viewport).width() / $(".Zoom img").width();
        fitHeightScale = $(viewport).height() / $(".Zoom img").height();

        if (fitWidthScale < fitHeightScale) {
            minScale = fitWidthScale;
        } else {
            minScale = fitHeightScale;
        }

        var Zoom = fitWidthScale;

        if (!msie) {
            $(".Zoom").width(fullWidth * Zoom);
            $(".Zoom").height(fullHeight * Zoom);
        } else {
            $(".Zoom").width(fullWidth * Zoom);
            $(".Zoom").height(fullHeight * Zoom);
        }

        $(".Zoom").css({
            '-webkit-transform': 'scale(' + Zoom + ')',
            '-moz-transform': 'scale(' + Zoom + ')',
            '-ms-transform': 'scale(' + Zoom + ')',
            '-o-transform': 'scale(' + Zoom + ')',
            'transform': 'scale(' + Zoom + ')'
        });

        customScrollbar(".ViewportWrapper", ".ScrollViewport", ".Zoom");

        $("#ZoomInButton").on("click", function (event) {
            if (Zoom < max) {
                Zoom += step * 2;

                if (Zoom > 1)
                    Zoom = 1;

                $(".Zoom").width(fullWidth * Zoom);
                $(".Zoom").height(fullHeight * Zoom);

                $(".Zoom").css({
                    '-webkit-transform': 'scale(' + Zoom + ')',
                    '-moz-transform': 'scale(' + Zoom + ')',
                    '-ms-transform': 'scale(' + Zoom + ')',
                    '-o-transform': 'scale(' + Zoom + ')',
                    'transform': 'scale(' + Zoom + ')'
                });

                customScrollbar(".ViewportWrapper", ".ScrollViewport", ".Zoom");
            }
        });

        $("#ZoomOutButton").on("click", function (event) {
            if (Zoom > minScale) {
                Zoom -= step * 2;

                if (Zoom < minScale)
                    Zoom = minScale;

                $(".Zoom").width(fullWidth * Zoom);
                $(".Zoom").height(fullHeight * Zoom);

                $(".Zoom").css({
                    '-webkit-transform': 'scale(' + Zoom + ')',
                    '-moz-transform': 'scale(' + Zoom + ')',
                    '-ms-transform': 'scale(' + Zoom + ')',
                    '-o-transform': 'scale(' + Zoom + ')',
                    'transform': 'scale(' + Zoom + ')'
                });

                customScrollbar(".ViewportWrapper", ".ScrollViewport", ".Zoom");
            }
        });

        $("#MinimizeButton").on("click", function (event) {
            Zoom = minScale;

            $(".Zoom").width(fullWidth * Zoom);
            $(".Zoom").height(fullHeight * Zoom);

            $(".Zoom").css({
                '-webkit-transform': 'scale(' + Zoom + ')',
                '-moz-transform': 'scale(' + Zoom + ')',
                '-ms-transform': 'scale(' + Zoom + ')',
                '-o-transform': 'scale(' + Zoom + ')',
                'transform': 'scale(' + Zoom + ')'
            });

            customScrollbar(".ViewportWrapper", ".ScrollViewport", ".Zoom");
        });

        $("#MaximizeButton").on("click", function (event) {
            Zoom = 1;

            $(".Zoom").width(fullWidth * Zoom);
            $(".Zoom").height(fullHeight * Zoom);

            $(".Zoom").css({
                '-webkit-transform': 'scale(' + Zoom + ')',
                '-moz-transform': 'scale(' + Zoom + ')',
                '-ms-transform': 'scale(' + Zoom + ')',
                '-o-transform': 'scale(' + Zoom + ')',
                'transform': 'scale(' + Zoom + ')'
            });

            customScrollbar(".ViewportWrapper", ".ScrollViewport", ".Zoom");
        });

        $(viewport).on("mousewheel", function (event) {
            if (event.deltaY === 1 && Zoom < max) {
                Zoom += step;
                if (Zoom > 1)
                    Zoom = 1;
                $(".Zoom").width(fullWidth * Zoom);
                $(".Zoom").height(fullHeight * Zoom);

                $(".Zoom").css({
                    '-webkit-transform': 'scale(' + Zoom + ')',
                    '-moz-transform': 'scale(' + Zoom + ')',
                    '-ms-transform': 'scale(' + Zoom + ')',
                    '-o-transform': 'scale(' + Zoom + ')',
                    'transform': 'scale(' + Zoom + ')'
                });

                customScrollbar(".ViewportWrapper", ".ScrollViewport", ".Zoom");
            } else if (event.deltaY === -1 && Zoom > minScale) {
                Zoom -= step;

                if (Zoom < minScale)
                    Zoom = minScale;

                $(".Zoom").width(fullWidth * Zoom);
                $(".Zoom").height(fullHeight * Zoom);

                $(".Zoom").css({
                    '-webkit-transform': 'scale(' + Zoom + ')',
                    '-moz-transform': 'scale(' + Zoom + ')',
                    '-ms-transform': 'scale(' + Zoom + ')',
                    '-o-transform': 'scale(' + Zoom + ')',
                    'transform': 'scale(' + Zoom + ')'
                });

                customScrollbar(".ViewportWrapper", ".ScrollViewport", ".Zoom");
            }

            event.preventDefault();
        });


    }).each(function () {
        if (this.complete) $(this).trigger('load');
    });
}

function customScrollbar(wrapper, viewport, content) {
    $(viewport).unbind("scroll");

    $(viewport).on("scroll", function (event) {
        var scrollViewport = $(viewport);
        var scrollContent = $(content);

        var sbWidthInPercent = scrollViewport.width() / (scrollContent.width() / 100);
        var sbHeightInPercent = scrollViewport.height() / (scrollContent.height() / 100);

        var sbOffsetXInPercent = scrollViewport.scrollLeft() * 100 / scrollContent.width();
        var sbOffsetYInPercent = scrollViewport.scrollTop() * 100 / scrollContent.height();

        $(".vertical-scrollbar").remove();
        $(".horizontal-scrollbar").remove();

        if (sbWidthInPercent <= 99) {
            $(wrapper).append("<div class=\"horizontal-scrollbar\"></div>");
            $(".horizontal-scrollbar").css({
                "width": scrollViewport.width() * (sbWidthInPercent / 100),
                "left": scrollViewport.width() * (sbOffsetXInPercent / 100)
            });
        }

        if (sbHeightInPercent <= 99) {
            $(wrapper).append("<div class=\"vertical-scrollbar\"></div>");
            $(".vertical-scrollbar").css({
                "height": scrollViewport.height() * (sbHeightInPercent / 100),
                "top": scrollViewport.height() * (sbOffsetYInPercent / 100)
            });
        }

        //$(".scroll-debugger").remove();
        //$("body").append("<div class=\"scroll-debugger\"></div>");
        //$(".scroll-debugger").html("sbHeightInPercent: " + sbHeightInPercent + "<br />HeightInPercent: " + sbHeightInPercent + "<br />scrollViewport.width(): " + scrollViewport.width() + "<br />scrollViewport.height(): " + scrollViewport.height() + "<br />scrollContent.width(): " + scrollContent.width() + "<br />scrollContent.height(): " + scrollContent.height());
    });

    $(viewport).scroll();
}

function selectYqPart(codeOnImage) {
    $(`.flex-laximo .flex-oe-part .flex-item[data-flex-image-code="${codeOnImage}"]`).first().click();
}

$(function () {
    $('#ACIIframe').on('load', function () {
        $(window).scrollTop(0);
    });
});
function setAnchor() {
    var pathname = window.location.href.split('#')[0];
    $('a[href^="#"]').each(function () {
        var $this = $(this),
            link = $this.attr('href');
        $this.attr('href', pathname + link);
    });

    $('a.anchor').on('click', function (e) {
        event.preventDefault();
        let $anchorBrand = $("#" + $.attr(this, 'anchor') + "");

        $('html, body').animate({
            scrollTop: $anchorBrand.offset().top
        }, 500, function () {
            if ($("#sticky-header").hasClass("sticky-header")) {
                let stickyHeaderHeight = $("#sticky-header").height();
                $(window).scrollTop($anchorBrand.offset().top - stickyHeaderHeight);
            }
        })
    });
}
$.fn.FlexBackToTop = function () {

    $(document).on('scroll', function () {
        if ($(document).scrollTop() > $(window).height() / 4) {
            $('.flex-back-to-top').show("fast");
        }
        else {
            $('.flex-back-to-top').hide("fast");
        }
    });

    $(this).on('click', function (e) {
        $("html, body").animate({ scrollTop: 0 }, "slow");
        return false;
    });
}

let childShouldBeHidden = undefined;

$.fn.CollapseBreadCrumbs = function (){
    let shouldCollapse = $("#ShouldCollapseBreadcrumbs");
    if (shouldCollapse.length == 0 && shouldCollapse.val() !== "true"){
        return;
    }
    
    let breadcrumb = $(this);
    if (breadcrumb.width() < shouldCollapse.attr("data-width-value")){
        return;
    }
    
    let childs = breadcrumb.children();
    
    childShouldBeHidden = childs[childs.length - 2].innerHTML;
    $(childs[childs.length - 2]).html("<small id='dashedBreadCrumb' >...</small>")
    $("#dashedBreadCrumb").on("click",  function ($event){
        $event.preventDefault();
        $(this).replaceWith(childShouldBeHidden);
    });
}

$.fn.SetupSeoSettings = function (){
    if($(this).length > 0 && $(this).attr("data-flex-auto-accept") === 'true' && $.cookie("isCookieConsentSetted") !== 'true'){
        confirmCookieConsent();
    }
}

window.addEventListener('message', function (e) {

    if (e.data.indexOf != undefined) {
        if (e.data.indexOf('embedded-aci-add-to-basket') === 0) {
            console.log('ACI add to basket received!');
            var productCode = e.data.split('|')[1];
            var result = { IsValid: 'true', SuccessText: $('#ACIIframe').attr('data-flex-successfully-added-to-basket-text').replace('{0}', productCode) };
            getBasketSummary('', result, false);
        }

        if (e.data.indexOf('embedded-aci-content-height') === 0) {
            console.log('ACI content height received!');
            var height = e.data.split('|')[1];
            $('#ACIIframe').height(height);
        }

        if (e.data.indexOf('embedded-aci-current-url-part') === 0) {
            var currentUrlPart = e.data.split('|')[1];

            $(document).ready(function () {
                $('#ShareFormMessage').html(window.location.href.split('?')[0] + "?target-url=" + btoa(currentUrlPart).replace(new RegExp('=', 'g'), '%3D'));
            });
        }
    }
});

async function initMap(mapId, baseLocation, locations) {
    const { Map } = await google.maps.importLibrary("maps");
    const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");

    map = new Map(document.getElementById(mapId), {
        zoom: 16,
        center: baseLocation,
        mapId: "GoogleMap",
    });

    if (navigator.geolocation)
        navigator.geolocation.getCurrentPosition(function (position) {
            map.setCenter({ lat: position.coords.latitude, lng: position.coords.longitude });
            map.setZoom(16);
        });

    const infoWindow = new google.maps.InfoWindow();

    const markers = locations.map((val, i) => {
        const marker = new google.maps.marker.AdvancedMarkerElement({
            position: { lat: val.lat, lng: val.lng },
            title: val.name
        });

        marker.addListener("click", () => {
            infoWindow.close();
            infoWindow.setContent(marker.title);
            infoWindow.open(marker.map, marker);
            findPickupBranchByMapMarker(marker.title);
        });

        return marker;
    });

    new markerClusterer.MarkerClusterer({ markers, map });
};
