$(document).ready(function(){
	partial(BASE_URL);
	
	// Append show hide thing for sidebar
	addSidebarHandle();
	activateSidebarHandle();
	// read and set state
	var state = readCookie("agilo-sidebar");
	setSidebarState(state);
	
	// whiteboard exception
	handleWhiteboard();
});

function partial(url) {
    // With Firefox 3.0.7 we need to strip the url if it ends with a '/' because
    // Firefox will try to load http://report/ if we call load('//...') which
    // triggers the 'Same Origin' protection.
    // Opera+Safari work fine without this fix though...
    if (url.charAt(url.length-1) == '/') {
        url = url.substr(0, url.length-1);
    }
	// TICKETS
	$(".tree.tickets").load(url + "/report .listing.reports td.title a:lt(10)", function() {
		$(".tree.tickets a").wrap("<li></li>");
	});
	// TIMELINE
	//$(".tree.timeline").load(url + "/timeline #content");
	// WIKI
	$(".tree.wiki").load(url + "/wiki/TitleIndex .wikipage.searchable a:lt(10)", function() {
		$(".tree.wiki a").wrap("<li></li>");
	});
};

function addSidebarHandle() {
	$("body").append('<div class="sidebarHandle"></div>');
	sidebarPosition();
};

function sidebarPosition() {
	var left = $(".sidebar").width();
	$(".sidebarHandle").css("left", left+"px");
}

function activateSidebarHandle() {
	$(".sidebarHandle").click(function(){
		toggleSidebar();
	});
};

function toggleSidebar(state) {
	var anchor = $(".main").css("left").slice(0,-2);
	
	if (anchor == 0) {
		openSidebar();
	} else {
		closeSidebar();
	};
};

function openSidebar() {
	var width = $(".sidebar").width();
	// open the panel
	$(".sidebar").animate({marginLeft: "0px"}, {queue: false});
	$(".main, .sidebarHandle").css("width", "").animate({left: width+"px"}, {queue: false});
	$(".sidebarHandle").css("cursor", "w-resize");
	// set the cookie to open
	createCookie("agilo-sidebar","open",365);
};

function closeSidebar() {
	var width = $(".sidebar").width();
	// close the panel
	$(".sidebar").animate({marginLeft: "-"+width+"px"}, {queue: false});
	$(".main, .sidebarHandle").css("width", "").animate({left: "0"}, {queue: false});
	$(".sidebarHandle").css("cursor", "e-resize");
	// set the cookie to closed
	createCookie("agilo-sidebar","closed",365);
};

function setSidebarState(state) {
	var width = $(".sidebar").width();
	
	if (state == 'closed') {
		$(".sidebar").css({marginLeft: "-"+width+"px"});
		$(".main, .sidebarHandle").css({left: "0"});
	};
	if (state == 'open') {
		$(".sidebar").css({marginLeft: "0px"});
		$(".main, .sidebarHandle").css({left: width+"px"});
	};
};


/* REFACT: Why is this done in open?*/
function handleWhiteboard() {
	if (checkForWhiteboard()) {
		$(".sidebar, .sidebarHandle").hide();
		$(".main").css({
			'padding': "10px 0",
			'left': "0"
		});
	};
};

function checkForWhiteboard() {
	var location = window.location.pathname;

	if (location.lastIndexOf('whiteboard') != -1) {
		return true;
	};
	
	return false;
};