﻿$(document).ready(function() {

    // Set up hover effects for items in filter list
    $(".inSortByList").hover(function() { $(this).addClass("over"); }, function() { $(this).removeClass("over"); });

    // Set up sort by list item click event
    $(".inSortByList").bind("click", filterClick);

    // Set up sort by button click and drop down list visibility
    $("#leftListTopBarDropDownButton").click(function() {
        if ($("#leftListTopBarDropDownList:visible").length == 0) {
            $("#leftListTopBarDropDownList").slideDown();
        }
    });
    $("#leftListTopBarDropDownContainer").hoverIntent({
        timeout: 500,
        over: function() { },
        out: function() {
            if ($("#leftListTopBarDropDownList:visible").length > 0) {
                $("#leftListTopBarDropDownList").slideUp();
            }
        }
    });

    // Set background to large if "See All" option is included
    if ($(".seeAll:visible").length > 0) {
        $("#leftListTopBarDropDownList").addClass("largeDropDown");
    }

});

function filterClick(e) {
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;
    selectFilter(targ.id);
}

function orderFilterControl(cb) {
    // Maintains order of list control items
    for (var i = 0; i < ids.length; i++) {
        var which = $("#" + ids[i] + "Sort");
        $("#leftListTopBarDropDownList").append(which.removeClass("currentSortBy").addClass("inSortByList"));
    }
    $("#leftListTopBarDropDownList").append($(".seeAll:first").removeClass("currentSortBy").addClass("inSortByList"));
    $(".inSortByList").bind("click", filterClick);
    if (cb != null) { cb(); }
}

function selectFilter(id) {
    // Hide the list control
    $("#leftListTopBarDropDownList").slideUp(function() {

        // Rebuild list control
        orderFilterControl(function() {

            var which = $("#" + id);
            if (which.length == 0) {
                id = "forSeniorExecutivesSort";
                which = $("#" + id);
            }

            // Select chosen id
            $("#leftListTopBarDropDown").append(which.removeClass("inSortByList").addClass("currentSortBy").unbind("click", filterClick));

            // Trigger a custom event so that the consuming page can implement custom behavior
            $("#leftListTopBarDropDownContainer").trigger("filterSelected", [id]);
        });
    });
}
