﻿/// <reference path="jquery-1.4.1-vsdoc.js" />
// this does some basic event tracking - http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html

function InitCommunityGrid(properties, communities) {
    // put the community information object on the div
    for (var i in communities) {
        communities[i].div.data("community", communities[i]);
    }

    // show the slider when the expand button is clicked
    $("#community-grid-filter-expand-button").click(function () {
        var area = $("#community-grid-filter-area");
        area.slideDown('slow');
        $("#community-grid-filter-expand-button a, #community-grid-filter-clear-button a").delay(200).fadeOut('fast');
        _gaq.push(['_trackEvent', 'Community Grid', 'Filter Expand']);
    });

    function CollapseFilter() {
        $('#community-grid-filter-area').slideUp('fast');
        $("#community-grid-filter-expand-button a, #community-grid-filter-clear-button a").fadeIn('fast');
        _gaq.push(['_trackEvent', 'Community Grid', 'Filter Collapse']);
    }

    // hide the filter slider if the user clicks anywhere but in the filter area, or the button that pulls it up
    $('html').click(function (event) {
        if (!$(event.target).closest('#community-grid-filter-area').length && !$(event.target).closest('#community-grid-filter-expand-button').length) {
            CollapseFilter();
        };
    });
    // hide the filter if the user clicks the close button
    $('#community-grid-filter-area-close').click(CollapseFilter);

    // hover effect on the communities
    $(".community-grid-item-container").hover(function () {
        $(this).addClass("community-grid-item-container-hover");
    }, function () {
        $(this).removeClass("community-grid-item-container-hover");
    });

    var defaultAnimateSpeed = 1000;

    // build out the option lists
    BuildOptions(properties.care, $("#community-grid-filter-area-care .options"));
    //BuildOptions(properties.location, $("#community-grid-filter-area-location .options"));
    //BuildOptions(properties.amenities, $("#community-grid-filter-area-amenities .options"), true);
    //BuildOptions(properties.services, $("#community-grid-filter-area-services .options"));
    BuildOptions(properties.states, $("#community-grid-filter-area-state .options"), true);

    // set up handlers for the section-based 'clear selections' links
    $(".community-grid-filter-area-subsection .clear-selections a").click(function () {
        $(this).closest(".community-grid-filter-area-subsection").find(".option-item-selected").removeClass("option-item-selected");
        UpdateVisibleCommunities(defaultAnimateSpeed);
        UpdateHash();
        _gaq.push(['_trackEvent', 'Community Grid', 'Filter Clear', $(this).closest(".community-grid-filter-area-subsection").attr('id')]);
        return false;
    });

    // set up handlers for the global clear links
    $("#community-grid-filter-clear-button a, #community-grid-filter-area-clear a").click(function () {
        $("#community-grid-filter-area").find(".option-item-selected").removeClass("option-item-selected");
        UpdateVisibleCommunities(defaultAnimateSpeed);
        UpdateHash();
        _gaq.push(['_trackEvent', 'Community Grid', 'Filter Clear', 'All']);
        return false;
    });

    // update the hash values passed to the page, select the right set of options and hide the ones that should be
    var hashFilters = document.location.hash.substring(1).split("/");
    for (var hf in hashFilters) {
        $("#option-item-" + hashFilters[hf]).addClass("option-item-selected");
    }
    UpdateVisibleCommunities(0);

    /// Builds the options for an option list, splitting to two columns if indicated by the third parameter
    function BuildOptions(options, div, twoCol) {
        if (twoCol === true) {
            var div1 = $("<div class='options-1'></div>");
            var div2 = $("<div class='options-2'></div>");
            div1.appendTo(div);
            div2.appendTo(div);
            $("<div class='clear'></div>").appendTo(div);
            var total = $.param(options).split('=').length;
            var count = 0;
            for (var i in options) {
                count++;
                var opt = BuildOption(i, options[i]);
                if (count <= total / 2) {
                    opt.appendTo(div1);
                }
                else {
                    opt.appendTo(div2);
                }
            }
        }
        else {
            for (var i in options) {
                var opt = BuildOption(i, options[i]);
                opt.appendTo(div);
            }
        }
    }

    /// Constructs a single option item, and wires in the event handlers (but does not add it to the DOM)
    function BuildOption(id, text) {
        var itemDiv = $("<div class='option-item' id='option-item-" + id + "'><div class='option-item-checkbox'></div><div class='option-item-text'></div><div class='clear'></div></div>");
        itemDiv.children(".option-item-text").text(text);
        itemDiv.click(HandleClick);
        itemDiv.data("optionId", id);
        return itemDiv;
    }

    /// Handles the click even on an item
    function HandleClick() {
        var item = $(this);
        var text = item.children(".option-item-text").text();
        if (item.hasClass("option-item-selected")) {
            item.removeClass("option-item-selected");
            _gaq.push(['_trackEvent', 'Community Grid', 'Filter Remove', text]);
        }
        else {
            item.addClass("option-item-selected");
            _gaq.push(['_trackEvent', 'Community Grid', 'Filter Add', text]);
        }
        UpdateVisibleCommunities(defaultAnimateSpeed);
        UpdateHash();
    }

    function UpdateHash() {
        var ids = [];
        var filter = function (c) { return true; };
        $(".community-grid-filter-area-subsection .option-item-selected").each(function () {
            var optId = $(this).data("optionId");
            ids.push(optId);
        });

        var baseUrl = document.location.href;
        if (baseUrl.indexOf("#") > 0) {
            baseUrl = baseUrl.substring(0, baseUrl.indexOf("#"));
        }

        // leave the lonely # there when empty -- without it, the browser navigates to the new URL
        var url = "#" + ids.join("/");
        document.location.replace(url);
        // give the updated URL to AddToAny
        UpdateAddToAnyButton();
    }

    /// Builds up a function to evaluate a community to determine if it should be shown or not
    function BuildFilter() {
        function chainAnd(func1, func2) {
            return function (c) {
                return func1(c) && func2(c);
            };
        }
        function chainOr(func1, func2) {
            return function (c) {
                return func1(c) || func2(c);
            };
        }

        // all care, ammenties, and services options must match
        var filter = function (c) { return true; };
        $("#community-grid-filter-area-care .option-item-selected,#community-grid-filter-area-amenities .option-item-selected,#community-grid-filter-area-services .option-item-selected").each(function () {
            var optId = $(this).data("optionId");
            console.log("Adding standard filter for: " + optId);
            filter = chainAnd(filter, function (c) { return c[optId] == 1; });
        });

        // if a location filter is supplied, at least one must match
        var locationOptions = $("#community-grid-filter-area-location .option-item-selected")
        if (locationOptions.size() > 0) {
            var locationFilter = function (c) { return false; };
            locationOptions.each(function () {
                var optId = $(this).data("optionId");
                console.log("Adding location filter for: " + optId);
                locationFilter = chainOr(locationFilter, function (c) { return c[optId] == 1; });
            });
            filter = chainAnd(filter, locationFilter);
        }

        // if a state filter is supplied, at least one must match
        var stateOptions = $("#community-grid-filter-area-state .option-item-selected")
        if (stateOptions.size() > 0) {
            var stateFilter = function (c) { return false; };
            stateOptions.each(function () {
                var optId = $(this).data("optionId");
                console.log("Adding state filter for: " + optId);
                stateFilter = chainOr(stateFilter, function (c) { return c[optId] == 1; });
            });
            filter = chainAnd(filter, stateFilter);
        }

        return filter;
    }

    function UpdateVisibleCommunities(animateSpeed) {
        var filter = BuildFilter();
        var visibleCount = 0;

        UpdateLastItem(".community-grid-left", filter);
        UpdateLastItem(".community-grid-right", filter);

        // Go through each community, hide or show based on filter choice
        for (var i in communities) {
            var c = communities[i];
            var isVisible = c.div.filter(":visible").size() > 0;
            var isAnimating = c.div.filter(":animated").size() > 0;
            var shouldBeVisible = filter(c);

            // if the element is currently animated, we can't tell if it will be visible or hidden at the end, so always queue the new one up
            if (isVisible != shouldBeVisible || isAnimating) {
                if (shouldBeVisible) {
                    c.div.slideDown(animateSpeed);
                } else {
                    c.div.slideUp(animateSpeed);
                }
            }

            // Tally visibles
            if (shouldBeVisible) visibleCount++;
        }

        // Fix text for sIFR
        //var needSifr = $(".community-grid-item h3").filter(":not(.sIFR-replaced)");
        //if (needSifr.size() > 0) {
        //    DoH3Replace({ elements: needSifr.toArray() });
        //}

        // Show "no results" text if filter is too specific
        var noresults = $(".community-grid-noresults div");
        if (visibleCount == 0) { $(noresults).show(); }
        else { $(noresults).hide(); }
    }

    /// given the selector for a container with community-grid-items, makes sure only the last one matched by 'filter' 
    function UpdateLastItem(selector, filter) {
        var items = $(selector).find(".community-grid-item");
        items.removeClass("community-grid-item-last");
        items = items.filter(function () {
            return filter($(this).parent().data("community"));
        });
        items.last().addClass("community-grid-item-last");
    }
}

function XSY () {
    var defaultAnimateSpeed = 500;
    var area = $("#community-grid-filter-area");
    var activeArea = $("#community-grid-active-filter-area");

    var filters = {};

    // setup any filters indicated by the hash (no animation)
    var hashFilters = document.location.hash.substring(1).split("/");
    for (var hf in hashFilters) {
        AddFilter(hashFilters[hf], 0);
    }

    RebuildCommunityGridPropertyList(properties, filters);

    $("#community-grid-filter-add").click(function () {
        var filterVal = $("#community-grid-filter-list").val();
        AddFilter(filterVal, defaultAnimateSpeed);
        UpdateHash();
    });

    $("#community-grid-filter-clear").click(function () {
        for (var filter in filters) {
            var filterDiv = filters[filter];
            filterDiv.fadeOut(defaultAnimateSpeed, function () { filterDiv.detach(); });
        }
        filters = {}
        RebuildCommunityGridPropertyList();
        UpdateVisibleCommunities(defaultAnimateSpeed);
        UpdateHash();
    });

    /*
    $(".community-grid-item").click(function () {
        var a = $(this).find("div.community-grid-item-text > h3 > a")
        window.location = a.attr("href");
    });
    */

    function AddFilter(filterVal, animateSpeed) {
        if (null != filterVal && null != properties[filterVal]) {
            var filterName = properties[filterVal];
            var filterDiv = $("<div class='community-grid-filter-item' style='display: none'><span></span></div>");
            filterDiv.children("span").text(filterName);
            filterDiv.prependTo("#community-grid-active-filter-area");
            filterDiv.click(function () {
                filterDiv.fadeOut(animateSpeed, function () { filterDiv.detach(); });
                delete filters[filterVal];
                RebuildCommunityGridPropertyList();
                UpdateVisibleCommunities(defaultAnimateSpeed);
                UpdateHash();
            });
            filters[filterVal] = filterDiv;
            RebuildCommunityGridPropertyList();
            UpdateVisibleCommunities(animateSpeed);
            filterDiv.fadeIn(animateSpeed);
        }
    }


    function UpdateHash() {
        var keys = [];
        for (var k in filters) {
            keys.push(k);
        }

        var baseUrl = document.location.href;
        if (baseUrl.indexOf("#") > 0) {
            baseUrl = baseUrl.substring(0, baseUrl.indexOf("#"));
        }

        // leave the lonely # there when empty -- without it, the browser navigates to the new URL
        var url = "#" + keys.join("/");
        document.location.replace(url);
        // give the updated URL to AddToAny
        UpdateAddToAnyButton();
    }

    function UpdateVisibleCommunities(animateSpeed) {
        for (var i in communities) {
            var c = communities[i];
            var isVisible = c.div.filter(":visible").size() > 0;
            var shouldBeVisible = IsVisible(c);
            if (isVisible != shouldBeVisible) {
                c.div.slideToggle(animateSpeed);
            }
        }
    }

    function IsVisible(c) {
        for (var filter in filters) {
            if ("1" != c[filter]) {
                return false;
            }
        }
        return true;
    }

    function RebuildCommunityGridPropertyList() {
        var select = $("#community-grid-filter-list");
        select.html("");

        for (var a in properties) {
            if (null == filters[a]) {
                var opt = $("<option value='" + a + "'></option>");
                opt.text(properties[a]);
                opt.appendTo("#community-grid-filter-list");
            }
        }
    }
}
