if (!AJS.FE) {
    AJS.FE = {};
}

(function() {

    /**
     * Bind a callback that fires when resizing is completed on matching elements.
     *
     * A resize is considered complete after completionDelay ms have passed since
     * the last resize event.
     *
     * This prevents firing the resize event handler multiple times before the resize
     * is actually complete.
     */

    var hasSetupPageFillHeight = false;
    AJS.FE.setupPageFillHeight = function () {
        if (hasSetupPageFillHeight) {
            return;
        }
        hasSetupPageFillHeight = true;
        var onResize = function() {
            var windowHeight = AJS.$(window).height();
            var footerHeight = AJS.$("#footer").outerHeight();
            var offset = 34; //factor
            AJS.$("#atlas").css('height', windowHeight - footerHeight - offset);
        };
        onResize();
        AJS.FECRU.UI.setCompletedResizeTimeout(window, onResize);
    };

    var hasSetupSearchPageFillHeight = false;
    AJS.FE.setupSearchPageFillHeight = function () {
        if (hasSetupSearchPageFillHeight) {
            return;
        }
        hasSetupSearchPageFillHeight = true;

        var onResize = function() {
            var view = AJS.$(window).height();
            var above = AJS.$("#content-search").offset().top + AJS.$(".search-control").outerHeight() + AJS.$(".search-console").outerHeight();
            var below = AJS.$("#footer").outerHeight();

            var diff = AJS.$("#search-content").outerHeight() - parseFloat(AJS.$("#search-content").height());//padding, border, etcetera on content
            diff = parseInt(diff + 0.8, 10);//round up

            AJS.$("#search-content").height(
                view - below - above - diff
            );
        };
        onResize();
        AJS.FECRU.UI.setCompletedResizeTimeout(window, onResize);
    };

    /**
     * setup column height maintenance for the page -- does the initial setup and binds a resize handler to maintain it
     */
    var hasSetupColumnFillHeight = false;
    var setupColumnFillHeight = function () {
        if (hasSetupColumnFillHeight) {
            return;
        }
        hasSetupColumnFillHeight = true;

        var onResize = function() {
            var head = AJS.$("#content").offset().top;
            var foot = AJS.$('#footer').outerHeight();
            var windowHeight = AJS.$(window).height();
            var contentHeight = windowHeight - head - foot - 1.3; //window - masthead - roundingerrorhack
            AJS.$("#content").css({
                paddingBottom: 0,
                height: contentHeight
            });

            AJS.$("#content-resizable,#content-shield").css({
                height: contentHeight
            });

            AJS.$("#content-navigation-panel").css({
                height: contentHeight - 2
            });

            AJS.$("#content-navigation").css({
                width: "100%"
            });
            AJS.$("#content-column").css({
                height: contentHeight,
                marginRight: "auto",
                marginLeft: "auto"
            });

            if(AJS.$.browser.msie){
                if (AJS.$.browser.version < 8) {
                    AJS.$("#content-column-panel, #file-view-source-content").css({
                        height: Math.max(0, windowHeight - AJS.$("#content-column-panel").offset().top - foot - 4)
                    });
                } else {
                    AJS.$("#content-column-panel, #file-view-source-content").css({
                        height: Math.max(0, windowHeight - AJS.$("#content-column-panel").offset().top - foot - 2)
                    });
                    if (AJS.$("#section-iframe").length === 1) {
                        AJS.$("#content-column-panel").css({ top: "0" });
                    }
                }
            } else {
                AJS.$("#content-column-panel, #file-view-source-content").css({
                    height: Math.max(0, windowHeight - AJS.$("#content-column-panel").offset().top - foot - 3.3)
                });
            }

        };
        onResize();

        AJS.FECRU.UI.setCompletedResizeTimeout(window, onResize);
    };

    var columnResize = function (min) {
        AJS.$("#content-resizable").resizable({
            start: function(event, ui) {
                collapseReact(event, ui);
            },
            handles: "e",
            maxWidth: 600,
            minWidth: min || 0
        });
        var collapseReact = function (){
            if (AJS.$(".collapsed-sidebar #content-resizable").css("width") !== undefined) {
                AJS.log(AJS.$(".collapsed-sidebar #content-resizable #content-navigation").attr("style"));
            }
        };
        AJS.$("#content-resizable .ui-resizable-handle, #content-shield").live("mousedown",function(){
            AJS.$("#content-shield").show();
        }).live("mouseup",function(){
            AJS.$("#content-shield").hide();
        });
    };

    var hasSetupColumnFoot = false;
    var setupColumnFoot = function () {
        if (hasSetupColumnFoot) {
            return;
        }
        hasSetupColumnFoot = true;
        var hasContent = AJS.$("#panel-foot").children("div.holder").children().length > 0;

        if (hasContent) {
            var onResize = function() {
                var height = AJS.$("#content-column-panel").height();
                var panel = Math.floor(height * 0.55);
                var foot = height - panel;

                AJS.$("#content-column-panel").css({
                   height: panel - 6
                });

                AJS.$("#panel-foot").css({
                   height: foot,
                   display: "block"
                });
            };
            onResize();
            AJS.FECRU.UI.setCompletedResizeTimeout(window, onResize);
        }
    };

    var reloadFilePaneAndHeader = function(href, extractionFn) {
        var origUrl = AJS.$("#origUrl").val();
        var $spinner = AJS.$("#file-table-spinner");
        $spinner.show();
        AJS.FECRU.AJAX.ajaxDo(fishEyePageContext + "/json/fe/loadFilePane.do", {href: href, origUrl: origUrl}, function(resp) {
            if (resp.worked) {
                var replacement = AJS.$.clean([resp.fileTable], document);
                AJS.$("#browse-table").replaceWith(replacement);
                AJS.$("#cone").replaceWith(resp.coneDiv);
                AJS.$("#dirlist-taskbar-bar").replaceWith(resp.taskBarBar);
                AJS.$(".content-fixed").replaceWith(resp.contentFixed);
                AJS.FE.resetupTable("browse", null, extractionFn);
                AJS.FECRU.RSS.setupRSSDialog();
                AJS.FECRU.UI.setupQuicksearch();
            }
            $spinner.hide();
        }, false);
    };

    /**
     * Find a link in the directory tree by its href
     */
    var $findLink = function(href) {
        return AJS.$("#navigation-tree").find("a.pathLink[href='" + href + "']");
    };

    AJS.FE.browseDirectoryPathLinkFunction = function(event) {
        var $node = AJS.$(event.target);
        var href = $node.attr("href");
        var toggled = function () { };
        var self = AJS.FE.browseDirectoryPathLinkFunction;
        if ($node.hasClass("browse-directory")) {
            // find the node in the tree with the same href as us
            var $selectedLink = $findLink(href);
            AJS.FECRU.BROWSE.selectLink($selectedLink, toggled, self);
        } else {
            AJS.FECRU.BROWSE.selectLink($node, toggled, self);
        }
        reloadFilePaneAndHeader(href, AJS.FE.extractRevisionDetailsSortKeys);
        return false;
    };

    AJS.FE.setupTable = function(prefix, rowClickFn, extractionFn) {
        AJS.FE.resetupTable(prefix, extractionFn);
        AJS.FECRU.UI.tableRowClick(prefix, rowClickFn);

    };
    AJS.FE.resetupTable = function(prefix, extractionFn) {
        columnResize();
        setupColumnFillHeight();
        setupColumnFoot();
        AJS.FECRU.UI.tableSort(prefix, extractionFn);
    };

    AJS.FE.toggleTabs = function () {
        AJS.$(".tearout-tabs li").live("click", function () {
            var active = AJS.$(this).hasClass("tearout-active") ? true : null;
            var tab = AJS.$(this).attr("class").split("-")[1];
            var panel = "#panel-" + tab;

            AJS.$(".tearout-tabs li").each(function () {
                AJS.$(this).removeClass("tearout-active");
                AJS.$(this).children("a").unbind();
            });

            AJS.$(".panel-tearout","#content-navigation").each(function () {
                AJS.$(this).addClass("hidden");
            });
            // preference will be null if we are ignoring preferences
            var preference = AJS.$(this).children("input").val();
            if (active) {
                AJS.$('#content').addClass('collapsed-sidebar');
                // hiding everything
                if (preference) {
                    AJS.FECRU.PREFS.setPreference("shp", "N");
                }
            }
            else{
                AJS.$(this).addClass("tearout-active");
                AJS.$('#content').removeClass('collapsed-sidebar');
                AJS.$(panel).removeClass("hidden");
                if (preference) {
                    AJS.FECRU.PREFS.setPreferences({slp: preference, shp: "Y"});
                }
            }
            // resize the pane when in changeset view
            if (AJS.$('#section-changeset-view').length > 0) {
                AJS.$(window).resize();
            }
        });
    };

    AJS.FE.toggleWatch = function(val) {

    };

    var hasSetupPanes = false;

    AJS.FE.setupPanes = function() {
        if (!hasSetupPanes) {
            columnResize(100);
            setupColumnFillHeight();
            setupColumnFoot();
            hasSetupPanes = true;
        }
    };

    AJS.FE.streamMoreFocus = function () {
        AJS.$("#stream a.more").live("click", function(){
            AJS.$(this).closest(".stream").addClass("stream-focus");
            AJS.$("body").one("click",function(){
                AJS.$("#stream").find(".stream").removeClass("stream-focus");
            });
        });
    };

    AJS.$(document).ready(function () {
        // Give a warning if firebug is running
        AJS.FECRU.UI.warnAboutFirebug(function() {
            AJS.$(window).resize();
        });

        //setup the watch links
        var $watchform = AJS.$("form#watchform");
        if ($watchform.length > 0) {
            var $input = $watchform.children("input");
            AJS.$(".watch-on", $watchform).click(function(evnt) {
                evnt.preventDefault();
                $input.val('off');
                $watchform.submit();
            });
            AJS.$(".watch-off", $watchform).click(function(evnt) {
                evnt.preventDefault();
                $input.val('on');
                $watchform.submit();
            });
        }

        if (!AJS.$.support.opacity) {
            AJS.FE.streamMoreFocus();
        }
    });
})();
