/* Search box */
function FilterSearch(ID, storedValue)
{
    this.ID = ID;
    this.Initialized = false;
    this.TextField = $("#filter" + ID + "textfield");
    this.TextField[0].value = storedValue;
    this.Loader = $("#filter" + ID + "miniLoader");
    this.Main = $("#filter" + ID);
}

FilterSearch.prototype.Init = function()
{
    if (this.Initialized)
        return;

    this.Initialized = true;
}

FilterSearch.prototype.NonEnterKeyPressed = function()
{
    if(this.OnChange != null)
    {
        this.ShowLoaderIcon();
        this.OnChange(this);
    }
}

FilterSearch.prototype.UpdateEditMode = function(keycode)
{
    if(this.TextField[0].value.length == 0)
        this.Main.removeClass("edited");
    else
        this.Main.addClass("edited");
}

FilterSearch.prototype.Value = function()
{
    // When the filter term is being built, the free text search field always returns nothing as its filter term
    // as it isn't actually a navigator filter.
    return "";
}

FilterSearch.prototype.SearchValue = function()
{
    return this.TextField[0].value;
}

FilterSearch.prototype.Update = function(newValues)
{
    this.HideLoaderIcon();
}

FilterSearch.prototype.ShowLoaderIcon = function()
{
    this.Loader.css("visibility", "visible");
}

FilterSearch.prototype.HideLoaderIcon = function()
{
    window.setTimeout(this.SetHideLoaderCss.bind(this), FilterManager.LoaderHideDelay);
}

FilterSearch.prototype.SetHideLoaderCss = function()
{
    this.Loader.css("visibility", "hidden");
    this.UpdateEditMode();
}

FilterSearch.prototype.ZeroHitSearch = function(sourceFilter)
{
    this.HideLoaderIcon();
    this.Update(null, sourceFilter);
}

FilterSearch.prototype.HideLoader = function()
{
    this.HideLoaderIcon();
}

/* Check box */
function FilterCheckBox(ID, storedValue, currentValue)
{
    this.ID = ID;
    this.Initialized = false;
    this.Loader = $("#filter" + ID + "miniLoader");
    this.CheckBox = $("#filter" + ID + "checkbox");
    this.Main = $("#filter" + ID);
    this.Count = $("#filter" + ID + "count");
    this.StoredValue = storedValue;
    this.CurrentValue = currentValue;
}

FilterCheckBox.prototype.Init = function()
{
    if (this.Initialized)
        return;

    this.Initialized = true;

    if(this.StoredValue == this.CurrentValue)
        this.CheckBox.attr("checked","true");
        
    this.CheckBox.bind("click",function()
    {   
        if(this.CheckBox.attr("checked") == true)
            this.Main.addClass("edited");
        else
            this.Main.removeClass("edited");
            
        if(this.OnChange != null)
        {
            this.ShowLoaderIcon();
            this.OnChange(this);
        }
    }.bind(this));
}

FilterCheckBox.prototype.Value = function()
{
    var value = "";

    if(this.CheckBox.attr("checked") == true)
        value = this.StoredValue;

    return value;
}

FilterCheckBox.prototype.Update = function(newValues)
{
    var map = new HashMap();
    
    if (newValues != null && newValues.V.length > 0)
    {
        for (var i = 0; i < newValues.V.length; i++)
        {
            var newValue = newValues.V[i];
            var filter = newValue.F;
            var count = newValue.C;
            
            map.setItem(filter, count);
        }
    }
    
    var item = map.getItem(this.StoredValue);

    this.Count.text("(" + (item != null ? item : "0") + ")");
    this.HideLoaderIcon();
}

FilterCheckBox.prototype.ShowLoaderIcon = function()
{
    this.Loader.css("visibility", "visible");
}

FilterCheckBox.prototype.HideLoaderIcon = function()
{
    window.setTimeout(this.SetHideLoaderCss.bind(this), FilterManager.LoaderHideDelay);
}

FilterCheckBox.prototype.SetHideLoaderCss = function()
{
    this.Loader.css("visibility", "hidden");
}

FilterCheckBox.prototype.ZeroHitSearch = function(sourceFilter)
{
    this.HideLoaderIcon();
    this.Update(null, sourceFilter);
}

FilterCheckBox.prototype.HideLoader = function()
{
    this.HideLoaderIcon();
}

/* Drop down */
function FilterDropDown(ID, selectedItem, defaultItem, dropdownItems)
{
    this.ID = ID;
    this.Initialized = false;
    this.Main = $("#filter" + ID);
    this.SetupID = 0;
    this.Dropdown = null;
    this.selectedItem = selectedItem;
    this.defaultItem = defaultItem;
    this.dropdownItems = dropdownItems;
}

FilterDropDown.prototype.Init = function()
{
    if (this.Initialized)
        return;

    this.Initialized = true;

    this.Dropdown = new FilterAjaxDropdown("Dropdown-" + this.ID);
    
    if (this.defaultItem != null)
        this.Dropdown.addItem(this.defaultItem);
        
    this.dropdownItems.each(function(item)
    {
        this.Dropdown.addItem(item);
    }.bind(this));
    
    // true = initialize late.
    this.Dropdown.initializeFromHtmlItems(true);
    this.Dropdown.addOnChangeListener(this.OnDropdownChange.bind(this));
    
    if (this.selectedItem != null)
        this.Dropdown.currentItem = this.selectedItem;
    else
        this.Dropdown.currentItem = this.defaultItem;
            
    // Override dropdown showChildren method.
    this.Dropdown.showChildren = function()
    {
        this.dropdownShowChildren();
    }.bind(this);
}

FilterDropDown.prototype.dropdownShowChildren = function()
{
    if (this.SetupID != FilterManager.SetupID && this.OnChangeSingle != null)
    {
        this.Dropdown.showLoader();
        this.Dropdown.initializeLate();
        this.OnChangeSingle(this, true);
    }
    else
    {
        this.Dropdown.showChildrenInternal();
    }
}

FilterDropDown.prototype.OnDropdownChange = function()
{
    this.Dropdown.showLoader();
    
    if (this.Dropdown.getValue().length == 0)
        this.Main.removeClass("edited");
    else
        this.Main.addClass("edited");
    
    if (this.OnChange != null)
    {
        this.OnChange(this);
        showLoader = true;
    }
}

FilterDropDown.prototype.Value = function()
{
    return this.Dropdown.getValue();
}

FilterDropDown.prototype.UpdateSingle = function(newValues, options)
{
    this.UpdateAll(newValues != null && newValues.F.length > 0 ? newValues.F[0] : null);
    this.SetupID = FilterManager.SetupID;
            
    if (options)
        this.Dropdown.showChildrenInternal();
}

FilterDropDown.prototype.Update = function(newValues, sourceFilter)
{
    var currentValue = this.Value();

    if (currentValue.length == 0)
        return;

    var map = new HashMap();

    if (newValues != null)
    {
        for (var i = 0; i < newValues.V.length; i++)
        {
            var newValue = newValues.V[i];
            map.setItem(newValue.F, newValue.C);
        }
    }

    var lookup = map.getItem(currentValue);
    this.Dropdown.currentItem.count = (lookup != null ? lookup : 0);
    this.Dropdown.updateSelectedText();
}

FilterDropDown.prototype.UpdateAll = function(newValues, sourceFilter)
{
    var map = new HashMap();

    if (newValues != null)
    {
        for (var i = 0; i < newValues.V.length; i++)
        {
            var newValue = newValues.V[i];
            map.setItem(newValue.F, newValue.C);
        }
    }

    for (var i = 0; i < this.Dropdown.items.length; i++)
    {
        var item = this.Dropdown.items[i];
        
        if (item.value.length == 0)
            continue;
        
        var div = this.Dropdown.itemMapping.getItem(item);
        var jDiv = $(div);
        
        var count = map.getItem(item.value);
        
        if (count == null)
        {
            jDiv.addClass("off");
            jDiv.text(item.text + " (0)");
            item.count = 0;
        }
        else
        {
            jDiv.removeClass("off");
            jDiv.text(item.text + " (" + count + ")");
            item.count = count;
        }
        
        jDiv.attr("alt", item.getDisplayText());
        jDiv.attr("title", item.getDisplayText());
    }
    
    this.Dropdown.updateSelectedText();
    this.Dropdown.hideLoader();
}

FilterDropDown.prototype.ZeroHitSearch = function(sourceFilter)
{
    this.Dropdown.hideLoader();
    this.Update(null, sourceFilter);
}

FilterDropDown.prototype.HideLoader = function()
{
    this.Dropdown.hideLoader();
}

/* Drop down range toggle */
function FilterDropDownRangeToggle(ID, fieldNameNumeric, fieldNameNumericMax,
    selectedRangeItem, rangeDropdownItems,
    selectedItem, defaultItem, dropdownItems)
{
    this.ID = ID;
    this.Initialized = false;
    this.Main = $("#filter" + ID);
    this.FieldNameNumeric = fieldNameNumeric;
    this.FieldNameNumericMax = fieldNameNumericMax;
    
    this.SetupID = 0;
    this.Dropdown = null;
    this.RangeDropdown = null;
    
    this.currentSelectedRangeDropdownItem = selectedRangeItem;
    this.selectedRangeDropdownItem = selectedRangeItem;
    this.rangeDropdownItems = rangeDropdownItems;
    
    this.selectedDropdownItem = selectedItem;
    this.defaultDropdownItem = defaultItem;
    this.dropdownItems = dropdownItems;
}

FilterDropDownRangeToggle.prototype.Init = function()
{
    if (this.Initialized)
        return;

    this.Initialized = true;

    // Range dropdown.
    this.RangeDropdown = new Dropdown("Dropdown-" + this.ID + "-range");
    
    this.rangeDropdownItems.each(function(item)
    {
        this.RangeDropdown.addItem(item);
    }.bind(this));
    
    // true = initialize late.
    this.RangeDropdown.initializeFromHtmlItems(true);
    this.RangeDropdown.addOnChangeListener(this.OnRangeDropdownChange.bind(this));
    this.RangeDropdown.currentItem = this.selectedRangeDropdownItem;   
    
    // Value dropdown
    this.Dropdown = new FilterAjaxDropdown("Dropdown-" + this.ID + "-values");
    
    if (this.defaultDropdownItem != null)
        this.Dropdown.addItem(this.defaultDropdownItem);
        
    this.dropdownItems.each(function(item)
    {
        this.Dropdown.addItem(item);
    }.bind(this));

    // true = initialize late.
    this.Dropdown.initializeFromHtmlItems(true);
    this.Dropdown.addOnChangeListener(this.OnDropdownChange.bind(this));
    
    if (this.selectedDropdownItem != null)
        this.Dropdown.currentItem = this.selectedDropdownItem;
    
    if (this.selectedDropdownItem == null && this.defaultDropdownItem != null)
        this.Dropdown.currentItem = this.defaultDropdownItem
        
    // Override dropdown showChildren method.
    this.Dropdown.showChildren = function()
    {
        this.dropdownShowChildren();
    }.bind(this);
}

FilterDropDownRangeToggle.prototype.dropdownShowChildren = function()
{
    if (this.SetupID != FilterManager.SetupID && this.OnChangeSingle != null)
    {
        this.Dropdown.showLoader();
        this.OnChangeSingle(this, true);
    }
    else
    {
        this.Dropdown.showChildrenInternal();
    }
}

FilterDropDownRangeToggle.prototype.OnRangeDropdownChange = function()
{    
    var value = this.Dropdown.getValue();

    this.ToggleEditIndicator();
    
    if (value.length == 0)
        return;
  
    if(this.OnChange != null)
    {
        this.OnChange(this);
        this.Dropdown.showLoader();
        this.SetupID = FilterManager.SetupID;
    }
}

FilterDropDownRangeToggle.prototype.OnDropdownChange = function()
{
    this.Dropdown.showLoader();
    this.ToggleEditIndicator();
    
    var showLoader = false;

    if(this.OnChange != null)
    {
        this.OnChange(this);
        showLoader = true;
    }
}

FilterDropDownRangeToggle.prototype.ToggleEditIndicator = function()
{
    if (this.Dropdown.getValue().length > 0)
        this.Main.addClass("edited");
    else
        this.Main.removeClass("edited");
}
    
FilterDropDownRangeToggle.prototype.Value = function()
{
    var value = this.Dropdown.getValue();               
    var filterTerm = "";
    
    if (value != "")
    {
        var rangeType = this.RangeDropdown.getValue();
        var innerRange = "";
            
        switch(rangeType)
        {
            case "min":
                // Get the first last item which have a count other than 0.
                var dropdownItem = null;
                
                for (var i = this.Dropdown.items.length - 1; i > -1; i--)
                {
                    if (this.Dropdown.items[i].count > 0)
                    {
                        dropdownItem = this.Dropdown.items[i];
                        break;
                    }
                }
            
                filterTerm = this.FieldNameNumericMax + ":range(" + value + ", max, from=\"GE\", to=\"LE\")";
                break;
            case "max":
                filterTerm = this.FieldNameNumeric + ":range(min, " + value + ", from=\"GE\", to=\"LE\")";
                break;
            case "equal":
                filterTerm = this.ID + ":" + this.Dropdown.currentItem.filterTerm;
                break;
        }
    }
    
    return filterTerm;
}

FilterDropDownRangeToggle.prototype.UpdateSingle = function(newValues, options)
{
    this.UpdateAll(newValues != null && newValues.F.length > 0 ? newValues.F[0] : null);
    this.SetupID = FilterManager.SetupID;
    
    if (options)
        this.Dropdown.showChildrenInternal();
}

FilterDropDownRangeToggle.prototype.Update = function(newValues, sourceFilter)
{
    var map = new HashMap();
    
    // newValues is null on 0 hit searches.
    if (newValues != null)
    {
        for (var i = 0; i < newValues.V.length; i++)
        {
            var newValue = newValues.V[i];
            var filter = newValue.S;
            var count = newValue.C;
            
            map.setItem(filter, count);
        }
    }

    if (this.Dropdown.currentItem.value.length == 0)
        return;

    var item = map.getItem(this.Dropdown.currentItem.value);
    this.Dropdown.currentItem.count = (item == null ? 0 : item);
    this.Dropdown.updateSelectedText();
}

FilterDropDownRangeToggle.prototype.UpdateAll = function(newValues, sourceFilter)
{
    var map = new HashMap();
    
    // newValues is null on 0 hit searches.
    if (newValues != null)
    {
        for (var i = 0; i < newValues.V.length; i++)
        {
            var newValue = newValues.V[i];
            var filter = newValue.S;
            var count = newValue.C;
            
            map.setItem(filter, count);
        }
    }
        
    for (var i = 0; i < this.Dropdown.items.length; i++)
    {
        var dropdownItem = this.Dropdown.items[i];
        
        if (dropdownItem.value.length == 0)
            continue;

        var div = this.Dropdown.itemMapping.getItem(dropdownItem);
        var jDiv = $(div);
                    
        var item = map.getItem(dropdownItem.value);
        var count = 0;
                    
        if (item == null)
        {
            jDiv.text(dropdownItem.text + " (" + count + ")");
            jDiv.addClass("off");
        }
        else
        {
            count = item;
            jDiv.text(dropdownItem.text + " (" + item + ")");
            jDiv.removeClass("off");
        }
        
        if (dropdownItem.value == this.Dropdown.getValue())
            displayCount = count;

        dropdownItem.count = count;
        jDiv.attr("alt", dropdownItem.getDisplayText());
        jDiv.attr("title", dropdownItem.getDisplayText());
    }

    this.Dropdown.updateSelectedText();
    this.Dropdown.hideLoader();
}

FilterDropDownRangeToggle.prototype.ZeroHitSearch = function(sourceFilter)
{
    this.Dropdown.hideLoader();
    this.Update(null, sourceFilter);
}

FilterDropDownRangeToggle.prototype.HideLoader = function()
{
    this.Dropdown.hideLoader();
}

/* Multi select light box */
function MultiselectItem(value, text, count, divID, spanID, checkBoxOneID, checkBoxTwoID)
{
    this.value = value;
    this.text = text;
    this.count = count;
    this.divID = divID;
    this.spanID = spanID;
    this.checkBoxOneID = checkBoxOneID;
    this.checkBoxTwoID = checkBoxTwoID;
}

function FilterMultiSelectLightBox(ID, items, includeItems, excludeItems)
{
    this.ID = ID;
    this.Initialized = false;
    this.Loader = $("#filter" + this.ID + "miniLoader");
    this.Main = $("#filter" + this.ID);
    this.ItemHolder = $("#lightbox" + this.ID + "inner");
    this.Selections = $("#filter" + this.ID + "selections");
    this.MouseOverInfo = $("#filter" + this.ID + "mouseoverinfo");
    this.HoverBox = $("#filter" + this.ID + "hoverbox");
    this.HoverBoxClose = $("#filter" + this.ID + "hoverboxclose");
    this.HoverSelections = $("#filter" + this.ID + "hoverselections");
    this.OpenHoverTimer = null;
    this.CloseHoverTimer = null;
    this.SetupID = 0;
    this.items = items;
    this.selectedItems = [];
    this.IDtoItemMapping = new HashMap();
    
    this.initializedLate = false;
    this.includeItems = includeItems;
    this.excludeItems = excludeItems;
}

FilterMultiSelectLightBox.prototype.Init = function()
{
    if (this.Initialized)
        return;

    this.Initialized = true;

    // ID (value) to item mapping
    this.items.each(function(item)
    {
        this.IDtoItemMapping.setItem(item.value, item);
    }.bind(this));
    
    var sourceFilter = this;
    
    // Bind click to open the lightbox.
    $("#filter" + this.ID + "clicktext").bind("click", function()
    {
        if(sourceFilter.SetupID != FilterManager.SetupID && sourceFilter.OnChangeSingle != null)
        {
            sourceFilter.ShowLoaderIcon();
            sourceFilter.InitializeLate();
            sourceFilter.OnChangeSingle(sourceFilter);
        }
        else
        {
            sourceFilter.InitializeLate();
            $("#lightbox" + sourceFilter.ID).dialog("open");
        }
    });
    
    $(window).resize(function()
    {
        // Close all displaying hover selections
        $("div.filter div.hoverbox").slideUp("fast");
    });

    this.Selections.bind("mousemove mouseenter", this, function(e)
    {
        var sourceFilter = e.data;

        if (sourceFilter.selectedItems.length > 0)
        {
            window.clearTimeout(sourceFilter.OpenHoverTimer);
            sourceFilter.OpenHoverTimer = window.setTimeout(sourceFilter.OpenHover.bind(sourceFilter), 400);
        }
    });

    this.Selections.bind("mouseleave", this, function(e)
    {
        var sourceFilter = e.data;
        window.clearTimeout(sourceFilter.OpenHoverTimer);
    });
    
    this.MouseOverInfo.click(function()
    {
        window.clearTimeout(sourceFilter.OpenHoverTimer);
        window.clearTimeout(sourceFilter.CloseHoverTimer);
        sourceFilter.OpenHover();
    });

    this.MouseOverInfo.bind("mousemove mouseenter", this, function(e)
    {
        var sourceFilter = e.data;

        if (sourceFilter.selectedItems.length > 0)
        {
            window.clearTimeout(sourceFilter.OpenHoverTimer);
            sourceFilter.OpenHoverTimer = window.setTimeout(sourceFilter.OpenHover.bind(sourceFilter), 400);
        }
    });

    this.MouseOverInfo.bind("mouseleave", this, function(e)
    {
        var sourceFilter = e.data;
        window.clearTimeout(sourceFilter.OpenHoverTimer);
    });
    
    this.HoverBox.mouseenter(function()
    {
        window.clearTimeout(sourceFilter.CloseHoverTimer);
    });
    
    this.HoverBox.mouseleave(function()
    {
        sourceFilter.CloseHoverTimer = window.setTimeout(sourceFilter.CloseHover.bind(sourceFilter), 600);
    });
    
    this.HoverBoxClose.click(function()
    {
        sourceFilter.HoverBox.slideUp("normal");
    });
    
    $("#lightbox" + this.ID + "select").bind("click",function()
    {
        sourceFilter.ItemHolder.find("div.item input:even").attr("checked", true);
        sourceFilter.ItemHolder.find("div.item input:odd").attr("checked", false);
        sourceFilter.DrawAllSelections(true);
        
        if (sourceFilter.OnChange != null)
        {
            sourceFilter.OnChange(sourceFilter);
        }
        
        sourceFilter.Main.addClass("edited");
        sourceFilter.MouseOverInfo.css("visibility", "visible");
    });
    
    $("#lightbox" + this.ID + "unselect").bind("click",function()
    {
        sourceFilter.ItemHolder.find("div.item input:even").attr("checked", false);
        sourceFilter.ItemHolder.find("div.item input:odd").attr("checked", true);
        sourceFilter.DrawAllSelections(false);
        
        if (sourceFilter.OnChange != null)
        {
            sourceFilter.OnChange(sourceFilter);
        }
        
        sourceFilter.Main.addClass("edited");
        sourceFilter.MouseOverInfo.css("visibility", "visible");
    });
    
    $("#lightbox" + this.ID + "clear").bind("click",function()
    {
        sourceFilter.ItemHolder.find("div.item input").attr("checked", false);
        sourceFilter.Selections.children("span").remove();
        sourceFilter.HoverSelections.children("span").remove();

        sourceFilter.selectedItems.clear();
        
        if (sourceFilter.OnChange != null)
        {
            sourceFilter.OnChange(sourceFilter);
        }
        
        sourceFilter.Main.removeClass("edited");
        sourceFilter.MouseOverInfo.css("visibility", "hidden");
    });
    
    $("#lightbox" + this.ID + "close").bind("click",function()
    {
        $("#lightbox" + sourceFilter.ID).dialog("close");
    });
        
    for(var i = 0; i < this.includeItems.length; i++)
    {
        var multiSelectItem = this.includeItems[i];
        this.selectedItems.push(multiSelectItem);
        var value = multiSelectItem.value;
        var checkBoxOne = $("#" + multiSelectItem.checkBoxOneID);
        
        checkBoxOne.attr("checked", true);
        
        var text = multiSelectItem.text;
        var span = $("<span></span>");
        span.attr("id", value);
        span.text(text);
                            
        this.Selections.append(span);
        
        if (this.includeItems.length > 1 && i > 0)
        {
            var comma = $("<span></span>");
            comma.attr("id", "comma" + value);
            comma.text(", ");
            span.before(comma);
        }
        
        var hoverText = multiSelectItem.text;
        var hoverSpan = $("<span></span>");
        hoverSpan.attr("id", value);
        hoverSpan.text(hoverText);
                            
        this.HoverSelections.append(hoverSpan);
    }
    
    var includeSize = this.Selections.children("span").size();
            
    for(var i = 0; i < this.excludeItems.length; i++)
    {
        var multiSelectItem = this.excludeItems[i];
        this.selectedItems.push(multiSelectItem);
        var checkBoxTwo = $("#" + multiSelectItem.checkBoxTwoID);
        
        checkBoxTwo.attr("checked", true);
        
        var text = multiSelectItem.text;
        var span = $("<span></span>");
        span.attr("class", "disregard");
        span.attr("id", value);
        span.text(text);
                             
        this.Selections.append(span);
        
        if (includeSize > 0 || (this.excludeItems.length > 1 && i > 0))
        {
            var comma = $("<span></span>");
            comma.attr("id", "comma" + value);
            comma.text(", ");
            span.before(comma);
        }
        
        var hoverText = multiSelectItem.text;
        var hoverSpan = $("<span></span>");
        hoverSpan.attr("class", "disregard");
        hoverSpan.attr("id", "hover" + value);
        hoverSpan.text(hoverText);
                             
        this.HoverSelections.append(hoverSpan);
    }
}

FilterMultiSelectLightBox.prototype.InitializeLate = function()
{
    if (this.initializedLate)
        return;

    this.initializedLate = true;
    var sourceFilter = this;

    $("#lightbox" + this.ID).dialog
    ({
        bgiframe: true,
        autoOpen: false,
        width: 450,
        modal: false,
        close:function()
        {
        }
    });
    
    // Set the close text.
    $(document).find("#ui-dialog-title-lightbox" + this.ID).siblings("a").children("span").html("<img src=\"/gfx/common/compareClose.gif\" />");

    // Bind checkbox change.
    for (var i = 0; i < this.items.length; i++)
    {
        var item = this.items[i];

        this.bindCheckBoxChange(item.checkBoxOneID, item.value);
        this.bindCheckBoxChange(item.checkBoxTwoID, item.value);
    }
}

FilterMultiSelectLightBox.prototype.bindCheckBoxChange = function(id, value)
{
    var sourceFilter = this;

    $("#" + id).bind("click", value, function(e)
    {
        var multiSelectItem = sourceFilter.IDtoItemMapping.getItem(e.data);
        var value = multiSelectItem.value;

        var jSourceCheckBox = $(this);
        var jCheckBoxOne = $("#" + multiSelectItem.checkBoxOneID);
        var jCheckBoxTwo = $("#" + multiSelectItem.checkBoxTwoID);

        if(sourceFilter.OnChange != null)
            sourceFilter.ShowLoaderIcon();

        if(jSourceCheckBox.attr("checked") == true)
        {
            sourceFilter.selectedItems.push(multiSelectItem);

            // Uncheck other checkbox if it is checked.
            if (jSourceCheckBox[0] == jCheckBoxOne[0])
                jCheckBoxTwo.attr("checked", false)
            else
                jCheckBoxOne.attr("checked", false)
            
            var css = jSourceCheckBox.attr("pos") == 2 ? "disregard" : "";
            
            if(sourceFilter.Selections.children("span[id=" + value + "]").length < 1)
            {
                var text = multiSelectItem.text;
                var span = $("<span></span>");
                span.attr("class", css);
                span.attr("id", value);
                span.text(text);
                sourceFilter.Selections.append(span);

                var jSpans = sourceFilter.Selections.children("span");
                
                if (jSpans.size() > 1)
                {
                    var comma = $("<span></span>");
                    comma.attr("id", "comma" + value);
                    comma.text(", ");
                    span.before(comma);
                }
                
                var hoverText = multiSelectItem.text;
                var hoverSpan = $("<span></span>");
                hoverSpan.attr("class", css);
                hoverSpan.attr("id", "hover" + value);
                hoverSpan.text(hoverText);
                sourceFilter.HoverSelections.append(hoverSpan);
                
                sourceFilter.Main.addClass("edited");
                sourceFilter.MouseOverInfo.css("visibility", "visible");
            }
            else
            {
                sourceFilter.Selections.children("span[id=" + value + "]").attr("class", css);
                sourceFilter.HoverSelections.children("span[id=hover" + value + "]").attr("class", css);
            }
        }
        else
        {
            sourceFilter.selectedItems.remove(multiSelectItem);

            sourceFilter.Selections.children("span[id=comma" + value + "]").remove();
            sourceFilter.Selections.children("span[id=" + value + "]").remove();
            sourceFilter.HoverSelections.children("span[id=hover" + value + "]").remove();
            sourceFilter.Selections.children("span:eq(0)").filter("[id^=comma]").remove();
            
            // Get input element counts
            var column1Count = $("#lightbox"+ sourceFilter.ID + " div.inner div.item input[checked=true][pos=1]").size();
            var column2Count = $("#lightbox"+ sourceFilter.ID + " div.inner div.item input[checked=true][pos=2]").size();
            
            if (column1Count == 0 && column2Count == 0)
            {
                sourceFilter.Main.removeClass("edited");
                sourceFilter.MouseOverInfo.css("visibility", "hidden");
            }
        }
        
        if(sourceFilter.OnChange != null)
            sourceFilter.OnChange(sourceFilter);
    });
}

FilterMultiSelectLightBox.prototype.OpenHover = function()
{
    var selectionOffset = this.Selections.offset();
    var parentOffset = this.Selections.offsetParent().offset();
    
    this.HoverBox.css( { top: (selectionOffset.top - parentOffset.top - 4) + "px", left: (selectionOffset.left - parentOffset.left) + "px" } );
    this.HoverBox.slideDown("normal");
    
    // Close all other displaying hover selections
    $("div[id!=filter" + this.ID + "].filter .hoverbox").slideUp("fast");
}

FilterMultiSelectLightBox.prototype.CloseHover = function()
{
    this.HoverBox.slideUp("normal");
}

FilterMultiSelectLightBox.prototype.DrawAllSelections = function(include)
{
    this.Selections.children("span").remove();
    this.HoverSelections.children("span").remove();
    var css = (include ? "" : "disregard");
    
    for(var i = 0; i < this.items.length; i++)
    {
        var multiSelectItem = this.items[i];
        var value = multiSelectItem.value;

        var text = multiSelectItem.text;
        var span = $("<span></span>");
        span.attr("class", css);
        span.attr("id", value);
        span.text(text);
                    
        this.Selections.append(span);
        
        if (items.length > 1 && i > 0)
        {
            var comma = $("<span></span>");
            comma.attr("id", "comma" + value);
            comma.text(", ");
            span.before(comma);
        }
        
        var hoverText = multiSelectItem.text;
        var hoverSpan = $("<span></span>");
        hoverSpan.attr("class", css);
        hoverSpan.attr("id", "hover" + value);
        hoverSpan.text(hoverText);
        
        this.HoverSelections.append(hoverSpan);
        this.selectedItems.push(multiSelectItem);
    }
}

FilterMultiSelectLightBox.prototype.Value = function()
{
    if (this.selectedItems.length == 0)
        return "";

    var filterTerm = "";
    var fieldName = this.ID + ":";

    for (var i = 0; i < this.selectedItems.length; i++)
    {
        var item = this.selectedItems[i];

        var checkBoxOne = $("#" + item.checkBoxOneID);
        var checkBoxTwo = $("#" + item.checkBoxTwoID);

        if(checkBoxOne.attr("checked") == true)
        {
            filterTerm += item.value + FilterManager.MultiValueSeparator;
        }
        else if(checkBoxTwo.attr("checked") == true)
        {
            filterTerm += "not(" + item.value + ")" + FilterManager.MultiValueSeparator;
        }
    }
    
    if (filterTerm == "")
        return "";
    
    return fieldName + filterTerm;
}

FilterMultiSelectLightBox.prototype.UpdateSingle = function(newValues)
{
    this.UpdateAll(newValues != null && newValues.F.length > 0 ? newValues.F[0] : null);
    $("#lightbox" + this.ID).dialog("open");
}

FilterMultiSelectLightBox.prototype.Update = function(newValues, sourceFilter)
{
    this.HideLoaderIcon();
}

FilterMultiSelectLightBox.prototype.UpdateAll = function(newValues, sourceFilter)
{
    var map = new HashMap();
    
    if (newValues != null)
    {
        for (var i = 0; i < newValues.V.length; i++)
        {
            var newValue = newValues.V[i];
            var filter = newValue.F;
            var count = newValue.C;   
            var filter = filter.substring(filter.indexOf(":") + 1);
            
            map.setItem(filter, count);
        }
    }

    for (var i = 0; i < this.items.length; i++)
    {
        var item = this.items[i];
        var lookup = map.getItem(item.value);
        var jDiv = $("#" + item.divID);
        var jSpan = $("#" + item.spanID);

        if (lookup == null && this != sourceFilter)
        {                    
            jDiv.addClass("off");
            jSpan.text(item.text + " (0)");
        }
        else if (lookup != null)
        {
            jDiv.removeClass("off");
            jSpan.text(item.text + " (" + lookup + ")");
        }
    }
    
    this.HideLoaderIcon();
}

FilterMultiSelectLightBox.prototype.ShowLoaderIcon = function()
{
    this.Loader.css("visibility", "visible");
}

FilterMultiSelectLightBox.prototype.HideLoaderIcon = function()
{
    window.setTimeout(this.SetHideLoaderCss.bind(this), FilterManager.LoaderHideDelay);
}

FilterMultiSelectLightBox.prototype.SetHideLoaderCss = function()
{
    this.Loader.css("visibility", "hidden");
}

FilterMultiSelectLightBox.prototype.ZeroHitSearch = function(sourceFilter)
{
    this.HideLoaderIcon();
    this.Update(null, sourceFilter);
}

FilterMultiSelectLightBox.prototype.HideLoader = function()
{
    this.HideLoaderIcon();
}

/* Slider range */
function FilterSliderRange(ID, defaultMinValue, defaultMaxValue, currentMinValue, currentMaxValue)
{
    this.ID = ID;
    this.Initialized = false;
    this.defaultMinValue = defaultMinValue;
    this.defaultMaxValue = defaultMaxValue;
    this.currentMinValue = currentMinValue;
    this.currentMaxValue = currentMaxValue;
    
    this.Loader = $("#filter" + ID + " .control img.miniLoader");
    this.Main = $("#filter" + ID);
    this.FromBox = $("#frominputfield");
    this.ToBox = $("#toinputfield");
    this.Slider = $("#filter" + ID + " .control .slider");
}

FilterSliderRange.prototype.Init = function()
{
    if (this.Initialized)
        return;

    this.Initialized = true;
	
    this.Slider.slider(
    {
		animate:true, 
        range:true, 
        min:this.defaultMinValue, 
        max:this.defaultMaxValue, 
        values:[this.currentMinValue, this.currentMaxValue]
    });
	
	var minValue = this.currentMinValue;
	if (minValue < this.defaultMinValue) {
		minValue = this.defaultMinValue;
	}
	var maxValue = this.currentMaxValue;
	if (maxValue > this.defaultMaxValue) {
		maxValue = this.defaultMaxValue;
	}
	this.Slider.slider("values", 0, minValue);
	this.Slider.slider("values", 1, maxValue);
	this.currentMinValue = minValue;
	this.currentMaxValue = maxValue;
    
    var sourceFilter = this;
    
    this.Slider.bind("slide",function(event, ui)
    {
        sourceFilter.SetTextBoxValues(ui.values[0], ui.values[1]);
    });
    
    this.Slider.bind("slidestop",function(event, ui)
    {
        sourceFilter.ToggleEditIndicator(); 
            
        if(sourceFilter.OnChange != null)
        {
            sourceFilter.ShowLoaderIcon();
            sourceFilter.OnChange();
        }
    });
    
    this.SetTextBoxValues(this.currentMinValue, this.currentMaxValue);
}

FilterSliderRange.prototype.ToggleEditIndicator = function()
{
    if (this.FromBox.val() == this.defaultMinValue && this.ToBox.val() == this.defaultMaxValue)
        this.Main.removeClass("edited");
    else
        this.Main.addClass("edited");
}

FilterSliderRange.prototype.NonEnterKeyPressedInFromBox = function()
{
    this.TextBoxValueChanged(0, this.FromBox);
}

FilterSliderRange.prototype.NonEnterKeyPressedInToBox = function()
{
    this.TextBoxValueChanged(1, this.ToBox);
}
    
FilterSliderRange.prototype.SetTextBoxValues = function(min, max)
{
    this.FromBox.val(min);
    this.ToBox.val(max);
}

FilterSliderRange.prototype.TextBoxValueChanged = function(valueIndex, elm)
{
    var isMin = valueIndex == 0;
    
    var values = this.Slider.slider("option", "values");
    
    var currentValue = values[valueIndex];
    
    var newValue = parseInt(elm.val());
    
    if(isNaN(newValue))
    {
        this.UpdateInvalidValidCss(valueIndex);
        return;
    }
    
    var validValue = true;
	
    if(isMin == true)
    {
        if(newValue > values[1])
        {
            validValue = false;
        }
    }
    else
    {
        if(newValue < values[0])
        {
            validValue = false;
        }
    }
    
    this.UpdateInvalidValidCss(valueIndex);
    
    elm.val(newValue);
    
	if (validValue)
	{
		this.Slider.slider("values", valueIndex, newValue);
    
		if(this.OnChange != null)
		{
			this.ShowLoaderIcon();
			this.OnChange(this);
		}
	}
    
    this.ToggleEditIndicator();
}

FilterSliderRange.prototype.UpdateInvalidValidCss = function(currentField)
{
    var values = this.Slider.slider("option", "values");
    
    // Assume everything is valid
    this.FromBox.removeClass("invalid");
    this.ToBox.removeClass("invalid");
	
    var fromValue = parseInt(this.FromBox.val());
    var toValue = parseInt(this.ToBox.val());
    
    if (currentField == 0 && (fromValue > toValue || isNaN(fromValue)))
    {
        this.FromBox.addClass("invalid");
    }
    
    if (currentField == 1 && (toValue < fromValue || isNaN(toValue)))
    {
        this.ToBox.addClass("invalid");
    }
}

FilterSliderRange.prototype.Value = function()
{
    var values = this.Slider.slider("option", "values");
    
    if (values[0] != this.defaultMinValue || values[1] != this.defaultMaxValue)
        return this.ID + ":[" + values[0] + ";" + values[1] + "]";
  
    return "";
}

FilterSliderRange.prototype.Update = function(newValues)
{
    this.HideLoaderIcon();
}

FilterSliderRange.prototype.ShowLoaderIcon = function()
{
    this.Loader.css("visibility", "visible");
}

FilterSliderRange.prototype.HideLoaderIcon = function()
{
    window.setTimeout(this.SetHideLoaderCss.bind(this), FilterManager.LoaderHideDelay);
}

FilterSliderRange.prototype.SetHideLoaderCss = function()
{
    this.Loader.css("visibility", "hidden");
}

FilterSliderRange.prototype.ZeroHitSearch = function(sourceFilter)
{
    this.HideLoaderIcon();
}

FilterSliderRange.prototype.HideLoader = function()
{
    this.HideLoaderIcon();
}
