﻿/*/*
----------------------------------------------------------------------------------------------------------------
Sitemap tools: 
> Adds hide/show toggles to the <ul class='tree'> elements
> Remember which nodes were open/closed
----------------------------------------------------------------------------------------------------------------
*/

$(document).ready(function () {
    var opts = { expandRootNode: true };

    lhc.sitemaptree('ul.tree', opts);
    lhc.sitemaptree('.treeContainer > ul', opts);
});

(function () {
    lhc.sitemaptree = function (selector, options) {
        var o = $.extend({
            expandRootNode: false
        }, options);

        var id = window.location.pathname;

        return $(selector).each(function (i) {
            var $this = $(this),
				cookieName = id + i,
				openIndex = new Array();

            $this.addClass('tree');

            bindMenu();

            function bindMenu() {
                loadCookie();

                $this.find('span[rel="hook"]').each(function (index) {
                    var hook = $(this),
						li = hook.parent('li'),
						children = li.find('li').length > 0;

                    if (openIndexContains(index) || index == 0 && o.expandRootNode)
                        li.addClass("open");

                    if (!children)
                        li.addClass('inactive');

                    hook.click(function (i) {
                        li.toggleClass('open').hasClass('open') ? add(index) : remove(index);
                    });
                });
            }

            function loadCookie() {
                var cookieValue = Cookie.Read(cookieName);
                var cookieValue = '';
                if (null != cookieValue && cookieValue.length > 0) {
                    var indexs = cookieValue.split(',');
                    for (var i = 0; i < indexs.length; i++)
                        openIndex.push(indexs[i]);
                }
            }

            function openIndexContains(index) {
                for (var i = 0; i < openIndex.length; i++) {
                    if (openIndex[i] == index)
                        return true;
                }
                return false;
            }

            function remove(index) {
                for (var i = 0; i < openIndex.length; i++) {
                    if (openIndex[i] == index)
                        openIndex.splice(i, 1);
                }
                Cookie.Create(cookieName, openIndex, 30);
            }

            function add(index) {
                for (var i = 0; i < openIndex.length; i++) {
                    if (openIndex[i] == index)
                        return;
                }
                openIndex.push(index);
                Cookie.Create(cookieName, openIndex, 30);
            }
        });
    };
})();
