// js/Navigation.js
//
// Created: 01.02.2011 (pj)
///////////////////////////////////////////////////////////////////////////////



var navigation = new function()
{
    this.constructor = pj.core.Object;
    this.constructor("Navigation");

	this.load = function()
	{
		jnavigation = jQuery("#navigation");

		// load navigation tree:
		jsonrpc.callAsync(application.getJsonRpcUrl(), "navigation.load", null, onRpcNavigationLoad);
	};

	this.unload = function()
	{
		jnavigation = null;
		menuItems = null;
	};

	this.loaded = function()
	{
	    that.trace("loaded");

	    // automatically select item "home":
        var startItem = items["Home"];
        if (startItem) onClickItem(jnavigation.children(".navigation-item").first(), startItem);
	};

	this.unloaded = function()
	{
	    that.trace("unloaded");
	};


	/**
	** @param jct
	**     The containing block to which the menu items should be appended.
	** @param items
	**     A map containing the menu items.
	*/
	function createItems(items)
	{
		for (var id in items) {
			var item = items[id];
			if (!item) continue;

			jnavigation.append(sprintf('<span class="navigation-item rounded-corner-small-topleft rounded-corner-small-topright">%s</span>', item.label));

			var viewScript = sprintf("js/pj/view/%s.js", item.name);
			that.trace("createItems", sprintf("Loading script <%s>", viewScript));
			jsonrpc.loadScriptSync(viewScript, function() {
		        views[item.name] = pj.view[item.name];

		        var jitem = jnavigation.children(":last-child");
	            jitem.data("item", item);

	            // bind event handlers:
	            jitem.click(function(jitem, item) {
	                return function() { onClickItem(jitem, item); };
	            }(jitem, item));
			});
		}
	}


	///////////////////////////////////////////////////////////////////////////
	// User Interface Event Handlers:

	function onClickItem(jitem, item)
	{
	    that.trace("onClickItem", sprintf("Item=<%s>", item.name));

	    jnavigation.children(".navigation-item-selected").addClass("navigation-item")
	                                                     .removeClass("navigation-item-selected");
	    jitem.removeClass("navigation-item")
	         .addClass("navigation-item-selected");

	    if (activeView) activeView.unload();
	    var view = views[item.name];
	    if (view) {
	        activeView = view;
	        view.load();
	    }
	}


	///////////////////////////////////////////////////////////////////////////
	// RPC Event Handlers:

	function onRpcNavigationLoad(resp)
	{
	    that.trace("onRpcNavigationLoad", "Navigation tree was loaded successfully");

	    items = resp.items;
	    createItems(resp.items);

	    that.loaded();
	}


	///////////////////////////////////////////////////////////////////////////
	// Private Members:

	var that = this;
    var jnavigation = null;

    var items = { };
    var views = { };
    var activeView = null;
}();


