/* Minification failed. Returning unminified contents.
(873,65-66): run-time error JS1195: Expected expression: >
(890,14-15): run-time error JS1195: Expected expression: )
(927,10-11): run-time error JS1004: Expected ';': )
(928,5-6): run-time error JS1002: Syntax error: }
 */
var ParametricSearch = (function () {

    var ctor = function (options) {
        var self = this;

        options = options || {};
        
        self.updateing = false;
        self.updatingSearchString = false;
        // delegate functions provided by the caller
        self.updateProductsCallback = options.updateProductsCallback;
        self.getValidFilterValues = options.getValidFilterValues;
        self.startLoading = options.startLoading;
        self.stopLoading = options.stopLoading;
        self.indexSpecs = {};
        self.trackSpecs = [];
        self.landingCode = options.landingCode;
        self.searchString = options.landingCode;
        self.categoryID = options.categoryID;

        function updateProducts() {
            //updateSearchString();
            self.updateProductsCallback();
            AssignGrouping();
            ResizeFilters();
            self.stopLoading();
        }

        function updateFilters(skipDisableSpecOn) {
            self.startLoading();
            //Update the filters
            self.updateing = true;
            $('.MinMaxSelect').prop('disabled', true);

            $('#PageToShow').val(1);
            $('#PageToShow2').val(1);
            self.getValidFilterValues(function (data) {
                //console.log(data);
                var $specsToDisable = $('.para-search-option')
                    .not($('.para-search-option').hasClass('selected'))
                    .not('[id^="specvalue-OperatingTempMAX"]')
                    .not('[id^="specvalue-OperatingTempMIN"]');

                if (skipDisableSpecOn != null) {
                    //Disable everything except this
                    var specName = 'specvalue-' + skipDisableSpecOn;

                    //If the option is not like the name of the parent, disable
                    $specsToDisable = $specsToDisable.not('[id^="' + specName + '"]');

                    var noSpecFilter = specName + '-No' + skipDisableSpecOn;

                    //$('#spec-' + skipDisableSpecOn).find('.para-search-option').removeClass('disabled');
                    //If No Spec Filter is enabled disable other filter, else disable no spec filter 
                    if ($('#spec-' + skipDisableSpecOn).find('#' + noSpecFilter).find('.selected').length !== 0) {

                        $('#spec-' + skipDisableSpecOn).find('.para-search-option').not('[id^="' + noSpecFilter + '"]').addClass('disabled');
                    } else if ($('#spec-' + skipDisableSpecOn).find('.para-search-option').not('[id^="' + noSpecFilter + '"]').find('.selected').length !== 0) {
                        $('#spec-' + skipDisableSpecOn).find('#' + noSpecFilter).addClass('disabled');
                    }
                }

                $specsToDisable.addClass('disabled');

                //Loop through the result, and enable
                jQuery.each(data.ValidValues, function (i, val) {
                    var specName = i.replace(/[^a-zA-Z0-9_-]+/g, "");

                    jQuery.each(val, function (speci, spec) {
                        var specValue = spec.replace(/[^a-zA-Z0-9_.-]+/g, "");
                        specValue = specValue.replace(/[.]+/g, "_");

                        var element = $('#specvalue-' + specName + '-' + specValue);
                        //console.log(element);
                        element.removeClass('disabled');
                       
                        //IF a min/max exists, enable the input
                        $('#specvalue-' + specName + '-' + specValue)
                            .parents('.para-search-content')
                            .find('.MinMaxSelect option[value="' + parseFloat(spec) + '"]')
                                .prop('disabled', false)
                        ; //.show();

                        //Reset the option list

                    });
                });


                //Enable and show all options in min/max
                $('.para-search-option.disabled').each(function () {
                    var thisSpecValue = $(this).attr('data-option-value');


                    $(this).parents('.para-search-content')
                            .find('.MinMaxSelect option[value="' + thisSpecValue + '"]')
                                .prop('disabled', true)
                    ; //.hide();
                    //Hide the options that are disabled
                });

                //Remove all the disabled
                $('.para-search-selected-spec.disabled').removeClass('disabled');

                //If a selected option is disabled, uncheck it
                $('.para-search-option.disabled').find('.para-search-option-box.selected').each(function () {
                    var specID = $(this).parents('.para-search-option').attr('id');
                    $('#selected-' + specID).addClass('disabled');
                });

                //Clean up all the non selectable filters
                $('.para-search-content').removeClass('ignore');
                $('.para-search-button').removeClass('ignore');
                $('.para-search-options').each(function () {
                    if ($(this).find('.para-search-option:not(.disabled)').length == 0) {
                        $(this).find('.para-search-content').addClass('ignore');
                        $(this).find('.para-search-button').addClass('ignore');
                    }
                });

                ResizeFilters();

                self.updateing = false;
                $('.MinMaxSelect').prop('disabled', false);
            });
        }

        var hasBeenAssigned = false;
        function AssignGrouping() {
            //hasBeenAssigned = true;

            //Resize everything
            var rows = [];
            $('.para-search-options').each(function () {
                $(this).removeClass('resizeGroup-' + $(this).data('group'));
                var index = Math.floor($(this).position().top)

                $(this).addClass('resizeGroup-' + index);
                $(this).data('group', index);
            });


        }

        function ResizeFilters() {
            if (!hasBeenAssigned) AssignGrouping();

            var groupIndxs = [];
            $("div[class*=' resizeGroup-']").each(function () {
                var nInd = $(this).attr('class').match(/\bresizeGroup-(\d+)\b/)[1];
                if (!groupIndxs.indexOf(nInd)>-1) {
                    groupIndxs.push(nInd);
                }
            });
            for (var i = 0; i < groupIndxs.length; i++) {
                var t;
                resizeElementsToSameHeight(".resizeGroup-" + groupIndxs[i], ".resizeGroup-" + groupIndxs[i], t);
            }
            if ($('.ie').length == 0)
                $('.main-marketing').height($('#tab-container').height());
        }

        $(document).ready(function () {
            $(window).resize(function () {
                AssignGrouping();
                ResizeFilters()
            });
        });

        //On page load, clean up the filters so everything looks right
        function preloadFilters() {
            //If this is a page back button, or this is a saved search
            if ($('.para-search-option-box.selected').length > 0) {
                $('.para-search-option-box.selected').each(function () {
                    
                    // determine if this option should be implicitly selected
                    var implicit = false;
                    var valueType = $(this).closest('.para-search-option').attr('data-value-type');
                    
                    var minVal = null;
                    var maxVal = null;
                    $(this).closest('.para-search-option-list').find('.para-search-option-box.selected').each(function() {
                        var value = parseFloat($(this).parents('.para-search-option').attr('data-option-value'));
                        maxVal = (maxVal == null || value > maxVal) ? value : maxVal;
                        minVal = (minVal == null || value < minVal) ? value : minVal;
                    });

                    var val = parseFloat($(this).find('input').val());
                    if ((valueType == 'MINRATING' && val < maxVal) ||
                        (valueType == 'MAXRATING' && val > minVal)) {
                        implicit = true;
                    }

                    checkOption($(this).parents('.para-search-option'), implicit);
                });
                $('.para-search-selected-spec').show();

                // Commented out 20240613 because it was causing the SubmitFilters method to fire twice on page load - Rory
                //setTimeout(function () { updateProducts(); }, 300);
            }


            $('.para-search-content').each(function () {
                showOverflowOptions($(this), true);
            });
        }
        function untrackSpec(specid) {
            var spec = $('#' + specid).find(':input').attr('name');
            var val = $('#' + specid).find(':input').attr('value');
            spec = spec.replace('spec.', '');
            console.log('untrack ' + spec + ' : ' + val);
            if (!self.trackSpecs[self.indexSpecs[spec]]) return;
            self.trackSpecs[self.indexSpecs[spec]].Values = self.trackSpecs[self.indexSpecs[spec]].Values.filter(function (value, idx, arr) { return value != val });
            //pretend that untracking a spec always breaks range 
            delete self.trackSpecs[self.indexSpecs[spec]].MinValue;
            delete self.trackSpecs[self.indexSpecs[spec]].MaxValue; 
        }
        function uncheckOption(paraSearchOption) {
            paraSearchOption.find('.para-search-option-box').removeClass('selected implicit');
            $('#selected-' + paraSearchOption.attr('id')).remove();
        }

        function trackSpec(specid) {
            var spec = $('#' + specid).find(':input').attr('name');
            var val = $('#' + specid).find(':input').attr('value');
            spec = spec.replace('spec.', '');
            if (!(spec in self.indexSpecs)) {
                self.trackSpecs.push({ SpecificationName: spec, Values: [] });
                self.indexSpecs[spec] = self.trackSpecs.length - 1;
            }
            self.trackSpecs[self.indexSpecs[spec]].Values.push(val);
            
        }
        function trackSpecRange(spec, minVal, maxVal) {
            spec = spec.replace('spec.', '');
            if (!(spec in self.indexSpecs)) {
                self.trackSpecs.push({ SpecificationName: spec, Values: [] });
                self.indexSpecs[spec] = self.trackSpecs.length - 1;
            }
            self.trackSpecs[self.indexSpecs[spec]].Values = [];
            self.trackSpecs[self.indexSpecs[spec]].MaxValue = maxVal;
            self.trackSpecs[self.indexSpecs[spec]].MinValue = minVal;
        }
        //function updateSearchString() {
        //    var json = JSON.stringify(self.trackSpecs);
        //    json = json.replace("&", "..AND..").replace("#", "..HASH..").replace("<", "..LT..");
        //    var da = { query: json };
        //    //updateUrl("");
        //    self.updatingSearchString = true;
        //    $.ajax({
        //        url: '/search-encode',
        //        type: 'POST',
        //        data: {
        //            categoryID: self.categoryID,
        //            query: json
        //        },
        //        success: function (d) {
        //            //updateUrl(d);
        //            self.searchString = d;
        //            self.updatingSearchString = false;
        //            self.updateProductsCallback();
        //        }, error: function (textStatus, errorThrown) {
        //            console.log(textStatus);
        //            console.log(errorThrown);
        //        }
        //    });
            
        //}
        
        //function updateUrl(searchString) {
            
        //    var surl = window.location.href;
        //    self.searchString = searchString;
        //    surl = surl.split('?')[0];
        //    if (searchString) {
        //        surl = surl + "?q=" + searchString;
        //    }   
        //    if (surl != window.location.href) {
        //        window.history && window.history.pushState && history.pushState({ searchString: searchString }, null, surl);
        //    }

        //}
        //Do all actions for the checked row
        function checkOption(row, implicit) {

            var checkbox = $(row).find('.para-search-option-box');
            var spectext = $(row).attr('data-option-text');
            var specGroupLabel = $(row).attr('data-spec-group-label');
            var specid = $(row).attr('id');
            var selectedSpec = $('#selected-' + specid);
            checkbox.removeClass('selected implicit');
            checkbox.addClass('selected');
            if (!implicit) {
                trackSpec(specid);
            }
            if (implicit) {
                selectedSpec.remove();
                checkbox.addClass('implicit');
            }
            else {
                if (selectedSpec.length > 0 || $(row).hasClass('disabled')) {
                    return;
                }
                //Build up the new HTML
                var newNode =
                    $('<div>')
                        .addClass('para-search-selected-spec')
                        .attr('id', 'selected-' + specid)
                        .attr('data-spec-group-label', specGroupLabel || "")
                        .append(
                            $('<div>').addClass('para-search-selected-spec-label').text(spectext)
                        )
                        .append(
                            $('<div>').addClass('para-search-selected-spec-x').html("X")
                        )
                        .append($('<div>').css('clear', 'both'))
                        .css('display', 'none')
                    ;

                //Reset button
                $(newNode).find('.para-search-selected-spec-x').click(function (e) {
                    if (!self.updateing) {
                        const newNodeId = newNode[0].id;
                        console.log(newNodeId);
                        //Remove the selected
                        const clear = e.currentTarget.closest(".para-search-content");
                        //Remove the selected
                        $(clear).find('.para-search-selected-spec').each(function () {
                            let id = $(this).attr('id');
                            if (newNodeId == id) {
                                id = id.replace('selected-', '');
                                $(this).remove();
                                $('#' + id).find('.para-search-option-box').removeClass('selected');
                                untrackSpec(id);
                            }
                        });
                        if ($(clear).find('.para-search-selected-spec').length == 0) {
                            $(clear).find('.para-search-selected-spec-options').remove();

                        }

                        $.when(updateProducts()).then(updateFilters());
                    }
                });

                //Attach it to the correct spot
                if ($(row).parents('.para-search-option-list-wrapper').siblings(".para-search-selected-spec-wrapper").length == 0) {
                    var newwrapper = $('<div>').addClass('para-search-selected-spec-wrapper');
                    $(row).parents('.para-search-option-list-wrapper').before(newwrapper);
                }
                var attached = false;
                $(row).parents('.para-search-option-list-wrapper').siblings(".para-search-selected-spec-wrapper").children(".para-search-selected-spec").each(function () {
                    if (+spectext < +$(this).find(".para-search-selected-spec-label").text()) {
                        $(this).before(newNode);
                        attached = true;
                        return false;
                    }
                });

                if (!attached) {
                    $(row).parents('.para-search-option-list-wrapper').siblings(".para-search-selected-spec-wrapper").append(newNode);
                }
            }
        } 
        //Shift Click actions
        var lastSelected = null;
        function shiftClick(row) {

            var checkbox = $(row).find('.para-search-option-box');
            var optionList = $(row).parents('.para-search-option-list');
            var parentSpec = $(optionList).attr('id');

            //If this is the first one, or the parents don't line up, clear it out and start over
            if (lastSelected == null || $(lastSelected).parents('.para-search-option-list').attr('id') != parentSpec) {
                checkbox.addClass('partialselected');
                lastSelected = row;
            }
            else {
                var minVal = parseFloat($(lastSelected).attr('data-option-value'));
                var maxVal = parseFloat($(row).attr('data-option-value'));

                //Backwards or forward, flip to always forwards
                if (minVal > maxVal) {
                    var temp = minVal;
                    minVal = maxVal;
                    maxVal = temp;
                }

                $('.partialselected').removeClass('partialselected');

                checkOptionsFromMinMax(optionList, minVal, maxVal, true);

                lastSelected = null;
            }
        }

        //toggle the arrow direction
        function toggleArrow(obj, setToDown) {
            var content = $(obj).parents('.para-search-content');

            if (setToDown) {
                $('.para-search-content').each(function () {
                    showOverflowOptions($(this), true);
                });

                //Remove the old option
                content.find('.para-search-selected-spec-options').remove();

                $(obj).find('.para-search-arrow').css("background-position", "0 -9px");
                content.find('.para-search-selected-spec-group-label').remove();
                content.find('.para-search-selected-spec').hide();
                content.css('z-index', '1000');
                content.addClass('open');
            }
            else {
                $(obj).find('.para-search-arrow').css("background-position", "0 1px");
                content.find('.para-search-selected-spec').show();
                content.css('z-index', '100');
                content.removeClass('open');

                showOverflowOptions(content);
                ResizeFilters();
            }

            
        }

        //Manage the show more link
        function showOverflowOptions(obj, forceClose) {
            var isAllVisible = $('.para-search-selected-spec-options.visible').length != 0;
            if (forceClose)
                isAllVisible = false;

            //Hide everything past three in the list
            var selectedSpecs = $(obj).find('.para-search-selected-spec');
            selectedSpecs.show();
            

            //Append the drop down link that has clear.  Place it at the third spot or the last one if less than three
            var count = selectedSpecs.length;
            if ($('.para-search-option-list-wrapper').is(':visible')) return;
            //Build up the new HTML
            var newNode =
						$('<div>')
							.addClass('para-search-selected-spec-options reset')
							.append(
								$('<div>').addClass('para-search-selected-spec-label').text('')
							)
							.append(
								$('<div>').addClass('para-search-selected-spec-x para-search-selected-spec-x-label').text("Reset")
							)
							.append($('<div>').css('clear', 'both'))
                ;

            //Reset button
            $(newNode).find('.para-search-selected-spec-x').click(function () {
                if (!self.updateing) {
                    //Remove the selected
                    $(this).parents('.para-search-content').find('.MinMaxSelect').val('--');
                    $(this).parents('.para-search-content').find('.inputrange').val('');
                    $(this).parents('.para-search-content').find('.para-search-option-box').removeClass('selected implicit');
                    $(this).parents('.para-search-content').find('.para-search-selected-spec').each(function () {
                        var id = $(this).attr('id').replace('selected-', '');
                        $(this).remove();
                        untrackSpec(id);
                    });
                    $(this).parents('.para-search-content').find('.para-search-selected-spec-group-label').remove();
                    $(this).parents('.para-search-selected-spec-options').remove();

                    
                    
                    $.when(updateProducts()).then(updateFilters());

                }
            });

            //Down arrow
            if (count > 0) {
                $(newNode).find('.para-search-selected-spec-label').css('background', 'none');
                $(obj).append(newNode);
            }

            // for grouped specs, insert labels between each spec's elements.
            var groupedSelections = groupBy(selectedSpecs, function (selectedSpec) {
                return $(selectedSpec).attr('data-spec-group-label');
            });

            $(obj).find('.para-search-selected-spec-group-label').remove();
            var wrapper = $(obj).find('.para-search-option-list-wrapper');
            if (wrapper.find('.para-search-group-selectors').length) {
                $.each(groupedSelections, function (i, group) {
                    var labelText = $(group[0]).attr('data-spec-group-label');
                    var label = $('<div />')
                            .html(labelText)
                            .addClass('para-search-selected-spec-group-label');

                    wrapper.before(label);                    
                    $.each(group, function (j,item) {
                        label.after(item);
                    });
                });
            }
        }

        function groupBy(array, f) {
            var groups = {};
            array.each(function (index, value) {
                var group = JSON.stringify(f(value));
                groups[group] = groups[group] || [];
                groups[group].push(value);
            });
            return Object.keys(groups).map(function (group) {
                return groups[group];
            })
        }

        //Close open row
        function shutOpenRow() {
            var elm = $(".open").find('.para-search-button');
            if (elm.length) {
                var id = getSpecForButton($(elm));
                $("#spec-" + id).hide();
                $("#specminmax-" + id).hide();
                var $paraSearchContent = $(elm).parents('.para-search-content');
                $paraSearchContent.find(".para-search-option-list-wrapper").toggle();

                toggleArrow(elm, false);
                $(".open").removeClass('open');
            }            
        }

        // 1. Disable the options that are invalid
        // 2. Check all options that are still valid
        function checkOptionsFromMinMax(optionList, minVal, maxVal, keepCurrent) {
            var valueType = optionList.find("[data-value-type]").attr('data-value-type');
            var specID = optionList.find('.para-search-option-box :input').first().attr('name');             
            trackSpecRange(specID, minVal, maxVal);
            optionList.find('.para-search-option').each(function () {

                var val = parseFloat($(this).find('input').val());
                // determine if this option should be implicitly selected based on original selection
                var implicit = false;
                if ((valueType == 'MINRATING' && val < maxVal) ||
                    (valueType == 'MAXRATING' && val > minVal)) {
                    implicit = true;
                }

                if ($(this).hasClass('disabled')) {
                    return true;
                }

                if (minVal == null && maxVal == null) {
                    //Remove it if its already there
                    uncheckOption($(this).attr('id'));
                    return true;
                }

                var valid = true;
                
                if (minVal != null && val < minVal) {
                    valid = false;
                }
                if (maxVal != null && val > maxVal) {
                    valid = false;
                }

                if (valid) {
                    
                    //check the box
                    checkOption($(this), implicit);
                }
                else {
                    if (keepCurrent !== true) {
                        
                        uncheckOption($(this));
                    }
                }
            });
            //updateSearchString();

            
            
            $.when(updateProducts()).then(updateFilters($(optionList).attr('id').replace("spec-", "")));
        }

        function getSpecForButton($button) {
            var id = null;

            // if this is a spec group, look at radio buttons to determine which spec to show. otherwise look at the button's id to get the spec.
            var $radio = $button.closest('.para-search-content').find('input[type=radio]:checked');
            var isSpecGroup = $radio.length > 0
            if (isSpecGroup) {
                id = $radio.attr('data-toggle').replace('spec-', '');
           } else {
                id = $button.attr('id').replace('spectitle-', '');
            }
            
            return id;
        }

        //Jquery reverse
        jQuery.fn.reverse = [].reverse;

        $(document).ready(function () {

            //Toggle the drop down box.  This is the main white box for each spec that shows and hides with but gray button
            $(".para-search-button").click(function (e) {
                //Trigger for autoclose
                e.stopPropagation();

                var $paraSearchContent = $(this).parents('.para-search-content');

                if ($(this).hasClass('ignore')) {
                    return;
                }
                else if ($paraSearchContent.hasClass('open')) {
                    shutOpenRow();
                    return;
                }

                shutOpenRow();

                var id = getSpecForButton($(this));

                $("#spec-" + id).show();
                $("#specminmax-" + id).show();
                $paraSearchContent.find(".para-search-option-list-wrapper").show();
               
                
                if ($("#spec-" + id).is(":visible")) {
                    $('.para-search-option-list').hide();
                    $('.para-search-minmax').hide();
                    $('.para-search-content').css('z-index', 'auto');

                    $("#spec-" + id).show();
                    $("#specminmax-" + id + ':not(.MinMaxHidden)').show();

                    //Scroll to first option selectable
                    var firstOpt = $("#spec-" + id).find('.para-search-option:not(.disabled)').first();
                    if (firstOpt != null && firstOpt.length) {
                        $("#spec-" + id).find('.para-search-option-options').scrollTop(0);
                        $("#spec-" + id).find('.para-search-option-options').scrollTop($(firstOpt).position().top - 10);
                    }
                    
                    toggleArrow(this, true);
                }
                else {
                    toggleArrow(this, false);
                }

            });

            //Toggle the individual spec values
            $(".para-search-option").click(function (e) {
                e.stopPropagation();
                if (self.updateing)
                    return;

                var id = $(this).attr('id').replace('specvalue-', '');
                var checkbox = $(this).find('.para-search-option-box');
                var valueType = $(this).attr('data-value-type');
                
                //Shift Key
                //Remove the pending marker
                $('.partialselected').removeClass('partialselected');

                if (e.shiftKey && !(valueType == 'MINRATING' || valueType == 'MAXRATING')) {
                    shiftClick(this);
                    return;
                }

                //If it is selected and not implicitly, uncheck it
                if (checkbox.hasClass('selected') && !checkbox.hasClass('implicit')) {
                    untrackSpec($(this).attr('id'));
                    checkbox.removeClass('selected');
                    $('#selected-specvalue-' + id).remove();
                    showOverflowOptions($(this).parents('.para-search-content'));

                    if ($(this).parents('.para-search-content').hasClass('open'))
                        $(this).parents('.para-search-content').find('.para-search-selected-spec').hide();

                    if (valueType == 'MINRATING' || valueType == 'MAXRATING') {
                        $(this).parents('.para-search-option-list')
                               .find('.para-search-option')
                            .each(function () {
                                   uncheckOption($(this));
                                   $(this).removeClass('disabled');
                               });
                    }

                }
                    //If its not selected, and it is disabled, do nothing
                else if ($(this).hasClass('disabled')) {
                    return;
                }
                    //If its not selected, and is not disabled, check it
                else {
                    if (valueType == 'MINRATING') {
                        var optionList = $(this).parents('.para-search-option-list');
                        checkOptionsFromMinMax(optionList, null, parseFloat($(this).attr('data-option-value'))); 
                        lastSelected = this;
                        return;
                    }
                    else if (valueType == 'MAXRATING') {
                        var optionList = $(this).parents('.para-search-option-list');
                        checkOptionsFromMinMax(optionList, parseFloat($(this).attr('data-option-value')), null); 
                        lastSelected = this;
                        return;
                    }
                    else {
                        
                        checkOption(this);
                    }
                    
                }

                //Set the new last clicked
                lastSelected = this;

                var parentSpec = $(this).parents('.para-search-option-list').attr('id').replace('spec-', '');

                $.when(updateProducts()).then(updateFilters(parentSpec));
            });

            //Filter for min and max
            // 1. Disable the invalid options is the oposite box
            $('.MinMaxSelect.minselect').change(function (e) {
                if (self.updateing) {
                    e.preventDefault();
                    return;
                }

                var parent = $(this).parents('.para-search-content');
                var optionlist = $(parent).find('.para-search-option-list');

                var minVal = $(this).val();
                var maxVal = $(this).parents('.para-search-minmax').find('.maxselect').val();

                if (minVal == '--')
                    minVal = null;
                else
                    minVal = parseFloat(minVal);

                if (maxVal == '--')
                    maxVal = null;
                else
                    maxVal = parseFloat(maxVal);

                //Disable the invalid options is the oposite box
                var maxOptions = $(this).parents('.para-search-minmax').find('.maxselect').find('option');
                $(maxOptions).each(function () {
                    
                    if (minVal == null || ($(this).val() != '--' && parseFloat($(this).val()) >= minVal)) {
                        $(this).prop('disabled', false);
                        //$(this).show();
                        $(this).css('color', 'Black');
                    }
                    else if ($(this).val() != '--') {
                        $(this).prop('disabled', true);
                        //$(this).hide();
                        $(this).css('color', '#D0D0D0');
                    }
                });

                checkOptionsFromMinMax(optionlist, minVal, maxVal);
            });

            $('.MinMaxSelect.minselect, .MinMaxSelect.maxselect').click(function (e) {
                //Update colors
                $('option[disabled]').css('color', '#D0D0D0');
                $('option:not([disabled])').css('color', 'black');
            });

            $('.MinMaxSelect.maxselect').change(function (e) {
                var parent = $(this).parents('.para-search-content');
                var optionlist = $(parent).find('.para-search-option-list');

                var maxVal = $(this).val();
                var minVal = $(this).parents('.para-search-minmax').find('.minselect').val();

                if (maxVal == '--')
                    maxVal = null;
                else
                    maxVal = parseFloat(maxVal);

                if (minVal == '--')
                    minVal = null;
                else
                    minVal = parseFloat(minVal);

                //Disable the invalid options is the oposite box
                var minOptions = $(this).parents('.para-search-minmax').find('.minselect').find('option').reverse();
                $(minOptions).each(function () {                    
                    if (maxVal == null || ($(this).val() != '--' && parseFloat($(this).val()) <= parseFloat(maxVal))) {
                        $(this).prop('disabled', false);
                        //$(this).show();
                        $(this).css('color', 'Black');
                    }
                    else if ($(this).val() != '--') {

                        $(this).prop('disabled', true);
                        //$(this).hide();
                        $(this).css('color', '#D0D0D0');
                    }
                });

                checkOptionsFromMinMax(optionlist, minVal, maxVal);
            });

            //Minmax text input, only numbers 
            $(".para-search-minmax.text-input .inputrange").keydown(function (e) {                
                // Allow: backspace, delete, tab, escape, enter and .
                if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190, 189, 109]) !== -1 ||
                    // Allow: Ctrl/cmd+A
                    (e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                    // Allow: Ctrl/cmd+C
                    (e.keyCode == 67 && (e.ctrlKey === true || e.metaKey === true)) ||
                    // Allow: Ctrl/cmd+X
                    (e.keyCode == 88 && (e.ctrlKey === true || e.metaKey === true)) ||
                    // Allow: home, end, left, right
                    (e.keyCode >= 35 && e.keyCode <= 39)) {
                    // let it happen, don't do anything
                    return;
                }
                // Ensure that it is a number and stop the keypress
                if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                    e.preventDefault();
                }
            });
            $(".para-search-minmax.text-input .inputrange").keyup(function (e) {
                if (e.keyCode == 13) {
                    var parent = $(this).parents('.para-search-content');
                    var optionlist = $(parent).find('.para-search-option-list');

                    var maxVal = $(this).parents('.para-search-minmax.text-input').find('.inputrange.max').val();
                    var minVal = $(this).parents('.para-search-minmax.text-input').find('.inputrange.min').val();

                    if (maxVal == '--' || maxVal == '')
                        maxVal = null;
                    else
                        maxVal = parseFloat(maxVal);

                    if (minVal == '--' || minVal == '')
                        minVal = null;
                    else
                        minVal = parseFloat(minVal);

                    checkOptionsFromMinMax(optionlist, minVal, maxVal);
                }
            });

            //Minmax text input, click submit
            $(".para-search-minmax.text-input .minmaxbox.go").click(function (e) {
                var parent = $(this).parents('.para-search-content');
                var optionlist = $(parent).find('.para-search-option-list');

                var maxVal = $(this).parents('.para-search-minmax.text-input').find('.inputrange.max').val();
                var minVal = $(this).parents('.para-search-minmax.text-input').find('.inputrange.min').val();

                if (maxVal == '--' || maxVal == '')
                    maxVal = null;
                else
                    maxVal = parseFloat(maxVal);

                if (minVal == '--' || minVal == '')
                    minVal = null;
                else
                    minVal = parseFloat(minVal);

                checkOptionsFromMinMax(optionlist, minVal, maxVal);
            });

            $(".para-search-selected-spec-x-option").click((e) => {
                const clear = e.currentTarget.closest(".para-search-content");
                //Remove the selected
                    $(clear).find('.MinMaxSelect').val('--');
                    $(clear).find('.inputrange').val('');
                    $(clear).find('.para-search-option-box').removeClass('selected implicit');
                    $(clear).find('.para-search-selected-spec').each(function () {
                        var id = $(this).attr('id').replace('selected-', '');
                        $(this).remove();
                        untrackSpec(id);
                    });
                    $(clear).find('.para-search-selected-spec-group-label').remove();
                    $(clear).parents('.para-search-selected-spec-options').remove();



                    $.when(updateProducts()).then(updateFilters());
            });

            //Stop the parent onclick
            $('.para-search-option-list-wrapper').click(function (e) {
                e.stopPropagation();
            });

            //Close top if click is outside
            $(window).click(
				function (e) {
				    shutOpenRow();
				}
			);

            $(window).resize(ResizeFilters);

            preloadFilters();
            window.onload = function () {
                if (typeof history.pushState === "function") {
                    window.onpopstate = function () {
                        // Handle the back (or forward) buttons here
                        // Will NOT handle refresh, use onbeforeunload for this.
                        window.location.href = window.location.href;
                    };
                }
                else {
                    var ignoreHashChange = true;
                    window.onhashchange = function () {
                        if (!ignoreHashChange) {
                            ignoreHashChange = true;
                        }
                        else {
                            ignoreHashChange = false;
                        }
                    };
                }
            }
        });
    }
    
    return ctor;
})()

;
