﻿
// --------------------------------------------- //
// SYNCING LOWER BOUND/UPPER BOUND SELECT LISTS  //
// --------------------------------------------- //

// Takes two html <select> lists that represent a set of lower and upper bound values in a range. e.g. one
// list that contains lower bound values for price, and another that contains upper bound values for price
// Ensures their values are synched i.e. when a value is selected in the lower bound list,
// only values greater than that lower bound are shown in the upper bound list, and vica versa
function rangeListSynchroniser(lowerBoundList, upperBoundList) {
    this.lowerBoundList = lowerBoundList;
    this.upperBoundList = upperBoundList;

    this.init = function() {
        var comparer = this;
        // When lower bound list changed
        this.lowerBoundList.change(function() {
            // only show values greater than this in the upper bound list
            determineSelectListValuesToDisplay(lowerBoundList,
                        upperBoundList,
                        function(lowerVal, upperVal) { return lowerVal >= upperVal; });
        });
        // When upper bound list changed
        this.upperBoundList.change(function() {
            // only show values less than this in the lower bound list
            determineSelectListValuesToDisplay(upperBoundList,
                        lowerBoundList,
                        function(upperVal, lowerVal) { return lowerVal >= upperVal; });
        });
    }

    this.init();
}

// Gets the selected value specified in the first html <select> list and compares against
// every value in the second list.  Values in the second list are hidden depending on
// logic contained in function specified by parameter determineIfShouldHide
function determineSelectListValuesToDisplay(firstList, secondList, determineIfShouldHide) {
    var firstListValue = parseInt(firstList.val());
    if (!isNaN(firstListValue)) {
        secondList.children().each(function() {
            var secondListValue = parseInt($(this).val());
            if (!isNaN(secondListValue)) {
                if (determineIfShouldHide(firstListValue, secondListValue)) {
                    $(this).hide();
                    $(this).attr("disabled", "disabled");
                }
                else {
                    $(this).show();
                    $(this).attr("disabled", "");
                }
            }
        });
    }
    // Select value in first list is not a number
    else {
        // Show everything in the second list
        secondList.children().each(function() {
        $(this).show();
        $(this).attr("disabled", "");
         });
    }
}
