if (!AJS.FECRU) {
    AJS.FECRU = {};
}
AJS.FECRU.BROWSE = {};

(function() {
    /**
     * Open a folder, given the node of its span, and then run a post function. Opening the node may mean loading a
     * subtree via Ajax -- if this happens, the post function will be run after the subtree has loaded.
     *
     * @param $node -- a jQuery wrapper around the span tag containing the folder name (which is a sibling of the ul tag containing its children)
     * @param postFn -- a function of no arguments to run after opening the node
     * @param actionName -- an optional string naming the action to call to load a subtree
     * @param ajaxArgsFn -- an optional function to call to provide extra parameters to the subtree load fn
     */
    var toggleFolder = function($node, postFn, pathLinkFn, fileLinkFn, actionName, ajaxArgsFn) {
        if ($node.hasClass("unfilled")) {
            $node.removeClass("unfilled");
            var liId = $node.closest("li.tree-li").attr('id');
            var treeData = AJS.$("#tree-root").data("extraAttrs")[liId];
            var ajaxParameters = {
                path: treeData.path,
                repName: treeData.repname,
                baseUrl: treeData.baseurl,
                noFiles: treeData.nofiles
            };
            var selectedPath = AJS.$("#selectedDirTreeNode").children("input[name='selectedPath']").val();
            if (selectedPath) {
                ajaxParameters.selectedPath = selectedPath;
            }
            if (ajaxArgsFn) {
                var args = ajaxArgsFn($node);
                for (k in args) {
                    ajaxParameters[k] = args[k];
                }
            }
            $node.after(AJS.$("<span class='dirlistSpinner'>&nbsp;</span>").show());
            $node.removeClass("closed").addClass("open");
            var params = AJS.$("#queryStrSuffix").val();
            if (params) {
                ajaxParameters.queryStrSuffix = params;
            }

            if (!actionName) {
                actionName = "loadSubTree";
            }
            AJS.FECRU.AJAX.ajaxDo(fishEyePageContext + "/json/fe/" + actionName + ".do", ajaxParameters, function(resp) {
                if (resp.worked) {
                    // use 'clean' to avoid the regex that jQuery uses to distinguish HTML from ids
                    var replacement = AJS.$.clean([resp.payload], document);
                    $node.parent().replaceWith(replacement);
                    postFn();
                }
            }, false);
        } else {
            var oldClass = "closed";
            var newClass = "open";
            if ($node.hasClass("open")) {
                oldClass = "open";
                newClass = "closed";
            }
            $node.removeClass(oldClass).addClass(newClass);
            $node.siblings("ul." + oldClass).removeClass(oldClass).addClass(newClass);
            postFn();
        }
    };

    var moveSelectedDirTreeIds = function($newLink) {
        AJS.$("#selectedDirTreeNode").attr("id", "");
        AJS.$("#selectedDirTreeLink").attr("id", "");
        $newLink.closest("span").attr("id", "selectedDirTreeNode");
        $newLink.attr("id", "selectedDirTreeLink");
    };

    /**
     * Open the parents of this link and set the selected ids
     * @param $linkNode the link in the directory tree which is selected.
     */
    AJS.FECRU.BROWSE.selectLink = function($linkNode, folderToggledFn, pathLinkFn) {
        var $span = $linkNode.parent();
        var done = function() {
            folderToggledFn($linkNode);
        };
        if ($span.hasClass("closed")) {
            AJS.FECRU.AJAX.startSpin(AJS.$("#filebox"), "", true); // Get's stopped when #fileResults has html() called
            toggleFolder($span, done, pathLinkFn);
        } else {
            done();
        }
        moveSelectedDirTreeIds($linkNode);
    };

    AJS.FECRU.BROWSE.setupDirectoryTree = function(pathLinkFn, fileLinkFn, actionName, ajaxArgsFn) {
        AJS.$("span.tree").live("click", function(event) {
            if (AJS.$(event.target).is("a")) {
                return true; // let the link do its job
            }
            toggleFolder(AJS.$(this), function() {}, pathLinkFn, fileLinkFn, actionName, ajaxArgsFn);
            event.stopPropagation();
            return false;
        });
        if (pathLinkFn) {
            AJS.$("#navigation-tree a.pathLink").live("click", function(event) {
                return pathLinkFn(event);
            });
        }
        if (fileLinkFn) {
            AJS.$("#navigation-tree a.fileLink").live("click", function(event) {
                return fileLinkFn(event);
            });
        }
    };

    AJS.FECRU.BROWSE.initDirectoryTree = function(pathLinkFn, fileLinkFn, actionName, ajaxArgsFn) {
        AJS.FECRU.BROWSE.setupDirectoryTree(pathLinkFn, fileLinkFn, actionName, ajaxArgsFn);
        if (AJS.FE) {
            AJS.FE.setupPanes();
        }
        AJS.$("div.panel-directory","#content-navigation").scrollTo(AJS.$("#selectedDirTreeNode"));
    };
})();
