﻿/// <reference path="jquery-1.3.2-vsdoc2.js" />

$.fn.treeMenu = function(settings) {
    return $(this).each(function() {

        var root = $(this);
        root.Settings = jQuery.extend({}, { CookieName: "TreeMenu_" + settings.Id }, settings);

        root.find("A").each(function() {
            var current = $(this);
            var subTree = current.next();
            if (subTree != null && subTree.attr("tagName") == "UL") {
                if (current.attr("href") == null) {
                    current.attr("href", "#");
                }

                current.click(function(event) {
                    $(this).parent().toggleClass("closed", !$(this).is(":visible"));
                    $(this).next().toggle("slow", function() {
                        $.fn.treeMenu.serialize(root);
                        $(this).parent().toggleClass("closed", !$(this).is(":visible"));
                    });
                    if (typeof (event.preventDefault) != "undefined") event.preventDefault();
                    return false;
                });
            }
        });

        $.fn.treeMenu.deserialize(root);

    });
};

$.fn.treeMenu.serialize = function(root) {
    if ($.cookie == null) return;
    var data = [];
    root.find("UL").each(function(i, obj) {
        data[i] = $(obj).is(":visible") ? 1 : 0;
    });

    $.cookie(root.Settings.CookieName, data.join(""));
};

$.fn.treeMenu.deserialize = function(root) {
    if ($.cookie != null) {
        var stored = $.cookie(root.Settings.CookieName);
        if (stored) {
            var data = stored.split("");
            root.find("UL").each(function(i, obj) {
                $(obj).toggle(data[i] == 1 ? true : false);
                if (!$(obj).is(":visible")) {
                    $(obj).parent().addClass("closed");
                }
            });
            return;
        }
    }

    root.find("UL").each(function(i, obj) {
        $(obj).hide();
        $(obj).parent().addClass("closed");
    });
};
