/// <reference path="jquery-1.7.1.min.js" />
if (jQuery) (function ($) {
    $.extend($.fn, {
        fileTree: function (o, h) {
            /// <summary>
            /// 用法: $('.fileTreeDemo').fileTree( options, callback )
            /// </summary>
            /// <param name="o" type="Object">
            /// 配置参数
            /// <para>        root           - 根节点参数值; 默认值为：/</para>
            /// <para>        script         - AJAX 请求的服务端地址; 默认值 = jqueryFileTree.aspx</para>
            /// <para>        folderEvent    - 触发展开/收起的事件名称; 默认值 = click</para>
            /// <para>        expandSpeed    - 动态展开的速度; 默认值 = 500 (毫秒); -1 则没有动画</para>
            /// <para>        collapseSpeed  - 动态收起的速度; 默认值 = 500 (毫秒); -1 则没有动画</para>
            /// <para>        expanded       - 展开后执行的函数（可选）</para>
            /// <para>        collapsed      - 收起后执行的函数（可选）</para>
            /// <para>        multiFolder    - 是否限制同一时间展开多个节点; 默认值 = true</para>
            /// <para>        loadMessage    - 节点加载的时候需要显示的信息(可以是HTML); 默认值 = Loading...</para>
            /// <para>        postParam      - AJAX提交服务器的参数名称（可选）</para>
            /// <para>        postBack       - AJAX提交服务器后的回调函数（可选）</para>
            /// </param>
            /// <param name="h" type="Function">展开/收起事件的回调函数</param>
            if (!o) var o = {};
            if (o.root == undefined) o.root = '/';
            if (o.script == undefined) o.script = 'jqueryFileTree.aspx';
            if (o.folderEvent == undefined) o.folderEvent = 'click';
            if (o.expandSpeed == undefined) o.expandSpeed = 500;
            if (o.collapseSpeed == undefined) o.collapseSpeed = 500;
            if (o.expanded == undefined) o.expanded = null;
            if (o.collapsed == undefined) o.collapsed = null;
            if (o.multiFolder == undefined) o.multiFolder = true;
            if (o.loadMessage == undefined) o.loadMessage = 'Loading...';
            if (o.postParam == undefined) o.postParam = 'dir';
            if (o.postBack == undefined) o.postBack = null;
            if (o.expandValue == undefined || !$.isArray(o.expandValue)) o.expandValue = [];
            var _rootEl = this;
            if (typeof o.expanded == "function") {
                $(this).bind("expanded", o.expanded);
            }
            if (typeof o.collapsed == "function") {
                $(this).bind("collapsed", o.collapsed);
            }
            $(this).each(function () {
                function showTree(c, t) {
                    $(c).addClass('wait');
                    $(".jqueryFileTree.start").remove();
                    var postdata = {};
                    postdata[o.postParam] = t;
                    $.post(o.script, postdata, function (data) {
                        $(c).find('.start').html('');
                        $(c).removeClass('wait').append(createTreeNode(data));

                        if (o.root == t) {
                            $(c).find('UL:hidden').show();
                        }
                        else {
                            $(c).find('UL:hidden').slideDown(o.expandSpeed);
                            $(_rootEl).trigger("expanded", [c, t]);
                        }
                        bindTree(c);
                        if (typeof o.postBack == "function") {
                            o.postBack(c, t);
                        }
                    });
                }

                function createTreeNode(data) {
                    var html = "<ul class=\"jqueryFileTree\" style=\"display: none;\">";
                    for (var i = 0; i < data.length; i++) {
                        var hasChild = " haschild=\"true\"";
                        var className = " directory";
                        if (data[i].isLeaf == 0) {
                            hasChild = " haschild=\"false\"";
                            className = " file";
                        }
                        if (i == 0) {
                            className += " expanded";
                        }
                        html += "<li class=\"collapsed" + className + "\"><a href=\"#\" " + hasChild + " rel=\"" + data[i].HelpId + "\" title=\"" + data[i].Title + "\">" + data[i].Title + "</a></li>";
                    }
                    html += "</ul>";
                    return html;
                }

                function bindTree(t) {
                    $(t).find('LI A').bind(o.folderEvent, function () {
                        var action = "click";
                        if ($(this).parent().hasClass('directory')) {
                            if ($(this).parent().hasClass('collapsed') && $(this).attr('haschild') !== "false") {
                                action = "expand";
                                // Expand
                                $(this).trigger("expand");
                            } else {
                                // Collapse
                                action = "collapse";
                                $(this).trigger("collapse");
                            }
                        }
                        h(this, action);
                        return false;
                    }).bind("expand", function () {
                        if (!o.multiFolder) {
                            $(this).parent().parent().find('UL').slideUp(o.collapseSpeed);
                            $(this).parent().siblings(".directory").removeClass('expanded').addClass('collapsed');
                        }
                        $(this).parent().find('UL').remove(); // cleanup
                        showTree($(this).parent(), $(this).attr('rel'));
                        $(this).parent().removeClass('collapsed').addClass('expanded');
                    }).bind("collapse", function () {
                        $(this).parent().find('UL').slideUp(o.collapseSpeed);
                        $(this).parent().removeClass('expanded').addClass('collapsed');
                        $(_rootEl).trigger("collapse", [$(this).parent(), $(this).attr('rel')]);
                    });
                    $(t).find('LI A').each(function () {
                        if ($.inArray($(this).attr("rel"), o.expandValue) > -1) {
                            $(this).trigger("expand");
                        }
                    });
                    $(t).find('LI.expanded A').each(function () {
                        $(this).trigger("expand");
                    });

                    // 如果不是通过click触发展开/收起事件，则取消Click事件
                    if (o.folderEvent.toLowerCase != 'click') $(t).find('LI A').bind('click', function () { return false; });
                }
                //显示加载信息
                $(this).html('<ul class="jqueryFileTree start"><li class="wait">' + o.loadMessage + '<li></ul>');
                //展开根节点
                showTree($(this), escape(o.root));
            });
        }
    });
})(jQuery);