if(typeof contextPath == "undefined" || contextPath == null) {
    contextPath = "";
}

var studioData = {jiraUrl: ""};

AJS.toInit(function () {
	
	var confluenceUrl = AJS.$("#confluence-base-url").attr("content");

	// Remove Confluence DropDown Handlers
	AJS.$("#com-atlassian-confluence .user-menu *, .topnav *").unbind();

	// Setup the projects dropdown
	initMenuDropdowns();

    // Setup admin menu dropdowns (if they exist)
    initAdminMenuDropdowns();
    
    // Initialize User Menu (dynamic parts)
//    AJS.$(".js-user").one("click", function() {
//    	AJS.$.getScript(confluenceUrl + "/plugins/servlet/studio/currentuser?callback=confluenceUserCallback");
//    });

	// Initialize History Menu
    AJS.$(".js-history").one("click", function () {
        AJS.$.getScript(studioData.jiraUrl + "/plugins/servlet/studio/browsehistory?callback=historyCallback");
    });

    // Initialize JIRA Filter menu Menu
    AJS.$(".js-filter").one("click", function () {
        AJS.$.getScript(studioData.jiraUrl + "/plugins/servlet/studio/studiofavouritejirafilters?callback=filtersCallback")
    });
});

// === initialize dropdown menus ===

function initMenuDropdowns()
{
    if (AJS.dropDown.Standard && AJS.$("#com-atlassian-confluence").length == 0) {
		AJS.dropDown.Standard({
			selector:".ajs-menu-item",
			dropDown:".ajs-drop-down",
			trigger:".trigger",
			selectionHandler: function (e, selected) {
				selected.focus();
			}
		});
		AJS.$(".ajs-drop-down").mousedown(function (e) {
			e.stopPropagation();
		});
		AJS.$(".trigger").mousedown(function (e) {
			if (AJS.$(this).parent(".ajs-menu-item.active").size() > 0) {
				e.stopPropagation();
			}
		});
	} else {
	    AJS.$(".studio-header .ajs-menu-item").each(function () {
	        var dd = AJS.dropDown(AJS.$(".ajs-drop-down", this))[0];
	        dd.hide();
	        AJS.$(".trigger", this).click(function (e) {
				if (AJS.dropDown.current == dd) dd.hide();
				else
				{
					dd.show();
				    adjustPositionIfRequired(dd.$);
				}
				return false;
	        });
	    });
	}
}

function initAdminMenuDropdowns()
{
    AJS.$(".studio-admin-menu-section-hide, .studio-admin-menu-section-show").click(function(event){
        var thisElement = AJS.$(this);
        var sectionUl = thisElement.nextAll("ul");
        if (sectionUl.hasClass("studio-admin-menu-section-displayed"))
        {
            sectionUl.removeClass("studio-admin-menu-section-displayed");
            thisElement.removeClass("studio-admin-menu-section-hide");
            thisElement.addClass("studio-admin-menu-section-show");
        }
        else
        {
            // Hide all sections
            AJS.$(".studio-admin-menu li ul").removeClass("studio-admin-menu-section-displayed");
            AJS.$(".studio-admin-menu-section-hide").removeClass(".studio-admin-section-hide")
                    .addClass("studio-admin-menu-section-show");
            sectionUl.addClass("studio-admin-menu-section-displayed");
            thisElement.removeClass("studio-admin-menu-section-show");
            thisElement.addClass("studio-admin-menu-section-hide");
        }
    });
}

function confluenceUserCallback(confluenceUser) {
	var userMenuDropDown = AJS.$(".js-user").next();
	var prefUl = AJS.$("ul.section-user-preferences", userMenuDropDown);
	var s = "";
	if (confluenceUser.personalSpaceUrl) {
		s = '<li><a href="' + confluenceUser.personalSpaceUrl + '">Personal Space</a></li>';
	}
	if (confluenceUser.createPersonalSpaceUrl) {
		s = '<li><a href="' + confluenceUser.createPersonalSpaceUrl + '">Create Personal space</a></li>';
	}
	prefUl.html(s);
	adjustPositionIfRequired(userMenuDropDown);
}

function historyCallback(historyData) {
	function trimString(string, length) {
		return (string.length>length) ? string.substring(0,length-1)+"&hellip;" : string;
	}
	function addTitle(string, length) {
		return (string.length>length) ? 'title="'+string+'"':'';
	}
    var history = AJS.$(".js-history");
    var dropDown = AJS.$(history.nextAll(".ajs-drop-down")[0]);
    var ul = AJS.$("ul", dropDown);
    var s = "";
	if (!historyData.length) {
        s = "<li><a><span><i>&lt;No history yet&gt</i></span></a></li>";
    }

	for (var i = 0, ii = historyData.length; i < ii; i++) {
        var it = historyData[i];
        s = '<li><a class="' + it.iconType + '" href="' + it.url + '"><span class="history-item"><span class="history-left"'+addTitle(it.title,35)+'>' + trimString(it.title,35) + '</span><span class="history-right"'+addTitle(it.projectKey,6)+'>' + trimString(it.projectKey,6) + '</span></span></a></li>' + s;
    }
    ul.html(s);

    adjustPositionIfRequired(dropDown);
}

function filtersCallback(filterData) {
    var s = "";
    var filter = AJS.$(".js-filter");
    var dropDown = filter.nextAll(".ajs-drop-down");
    var ul = AJS.$("ul", dropDown);

    if(!filterData.length) {
        s = "<li><a><span><i>&lt;No filters found&gt</i></span></a></li>";
    }
    for (var i = 0, ii = filterData.length; i < ii; i++) {
        var it = filterData[i];
        s = s +'<li><a href="' + it.url + '"><span>' + it.name + "</span></a></li>";
    }

    ul.html(s);
    adjustPositionIfRequired(dropDown);
}

function adjustPositionIfRequired(dropDown) {
	// get hold of shimmming iframe for IE. no shimming iframe if not IE
	var shims = AJS.$(dropDown.siblings(".dropdown-shim"));
	var shim = (shims.size() > 0) ? AJS.$(shims[0]) : null;
    dropDown.css("marginLeft", 0);
	// may need to do this to the shadows as well.
    if (shim) {
    	shim.css("marginLeft", 0);
    	shim.width(dropDown.width());
    }

    var windowWidth = AJS.$(window).width();

    var region = dropDown.offset();
    var offset = 12 + region.left + dropDown.width() - windowWidth;
    if (offset > 0) {
        dropDown.css("marginLeft", "-" + offset + "px");
        if (shim) {
        	shim.css("marginLeft", "-" + offset + "px");
        }
    }
}


/* Search input box */
AJS.$("#quick-search-query").focus(function () {
    this.style.color = "#000";
    if (this.defaultValue == this.value) {
        this.value = "";
    }
}).blur(function () {
    this.style.color = "#ccc";
    if (this.value.replace(/\s+/g, "") == "") {
        this.value = this.defaultValue;
    }
});

// load fisheye search results (on search page)
if (typeof fisheyeAsynchronousSearchUrl != "undefined") {
	AJS.$("#fisheye_search_results").load(fisheyeAsynchronousSearchUrl);
}		       
 