/**
 * The "menubar" object is the single global object used by CARGO Library.  It
 * contains utility function for setting up the superior menubar of cargo interface.
 * @title  CARGO
 * @module menubar
 * @author Jose Manuel Rodriguez CNIO-INB (jmrodriguez@cnio.es)
 * @version 2.0
 */

/**
 * menubar is an abstract base class. It is defined by means of
 * list of menu items that composed by itself.
 * @constructor
 * @param {String} sContainerName Name of "div" container
 * @param {Array} oServices The list of service objects
 */
function menubar(sDivContainerName, oServices)
{
	this._createElementContainer(sDivContainerName, this.sDivMenuBar, "cargo-menu-bar"); // Create "cargoMenuBar" Element

	this._initMenuBar(oServices); // Initialize menu bar from cargo widgets
};

menubar.prototype = {

/* ATTRIBUTES */

	/**
	* The Div name of menu bar
	* @type String
	*/
	sDivMenuBar: "cargoMenuBar",
	/**
	* The name of menu bar
	* @type String
	*/
	sMenuBarName: "menubar",
	/**
	* MenuBar YAHOO object
	* @type Object
	*/
	menu: null,

/* Private METHODS */

	/**
	* Create "div" element
	* @private
	* @param {String} sContainerName Name of "div" container
	*/
	_createElementContainer: function (sDivContainerName, sDivId, sDivClass)
	{
		var oDivElement = document.createElement("div");
		oDivElement.setAttribute("id", sDivId);
		oDivElement.setAttribute("class", sDivClass);
		document.getElementById(sDivContainerName).appendChild(oDivElement);
	},
	/**
	* Initialize MenuBar and
	* add click events into Widget SubMenu (to create widget "windows")
	* @private
	* @param {Array} oServices The list of service objects
	*/
	_initMenuBar: function (oServices)
	{
		var oCargoMenu = {
				id: "cargoMenuId",
				text: "<em id=\"cargolabel\">CARGO</em>",
				url: "../docs/aboutCargo.html",
				target: "_blank"
				};
		var oWidgetMenu = this._getWidgetSubMenu(oServices);
/*
		var oHelpMenu = {
				id: "helpMenuId",
				text: "Help",
				url: "../index.html"
	// 			helptext: "Ctrl + H"
				// disabled: true
				};
*/
		var oHelpMenu = this._getHelpSubMenu(oServices);

		var aItemData = [ oCargoMenu, oWidgetMenu, oHelpMenu ];
	
		this.menu = new YAHOO.widget.MenuBar(this.sMenuBarName, { lazyload: true, itemdata: aItemData });
		this.menu.render(document.getElementById(this.sDivMenuBar));
	},
	/**
	* Create a MenuItem structure that contains the widget information.
	* The structure looks like:
	* WidgetMenu = {
			id: "widgetMenuId", // Identifier of "widget" menu
			text: "Widgets",
			submenu: {
				id: "widgetSubMenuId", // Identifier of "widget" submenu
				itemdata: [
					{
					id: "Type Widget" + "WidgetMenuId", // Identifier of "type widget" menu
					text: "Name of Type Widget",
					submenu: {
						id: "Type Widget" + "WidgetSubMenuId", // Identifier of "type widget" submenu
						itemdata: [ // Array of MenuItem
							{
							name: "widget name"
							value: "widget name"
							}...
							]
						}
					}...
					]
				}
	* @private
	* @param {Array} oServices The list of service objects
	* @return {JSON} oWidgetMenu Structure of widget menu
	*/
	_getWidgetSubMenu: function (oServices)
	{
		var aWidgetSubMenu = new Array();
		for (var iWidgetId in oServices)
		{
			var oWidgetInfo = oServices[iWidgetId];
			if (typeof(oWidgetInfo) == 'object')
			{
				var sWidgetName = oWidgetInfo.name;
				var aWidgetTypes = oWidgetInfo.types;

				for ( var iIndex = 0; iIndex < aWidgetTypes.length; iIndex ++)
				{
					var sWidgetType = aWidgetTypes[iIndex].name;
					var iIndexType = this._getWidgetIndexIfTypeExists(aWidgetSubMenu, sWidgetType);
					if ( eval(typeof(aWidgetSubMenu) != 'undefined') && (iIndexType == -1) )
					{
						var oWidgetMenuItem = new YAHOO.widget.MenuItem(sWidgetName);
						oWidgetMenuItem.value = sWidgetName;
						oWidgetMenuItem.text = sWidgetType;
						oWidgetMenuItem.clickEvent.subscribe(this._onWidgetMenuClick, iWidgetId);
						var oStrucSubMenu = {
								id: sWidgetType + "WidgetMenuId",
								text: sWidgetType,
								submenu: {
									id: sWidgetType + "WidgetSubMenuId",
									itemdata: [ oWidgetMenuItem ]
								}
						};
						aWidgetSubMenu.push(oStrucSubMenu);
					}
					else
					{
						var aWidgetNames = aWidgetSubMenu[iIndexType].submenu.itemdata;
						var oWidgetMenuItem = new YAHOO.widget.MenuItem(sWidgetName);
						oWidgetMenuItem.value = sWidgetName;
						oWidgetMenuItem.text = sWidgetType;
						oWidgetMenuItem.clickEvent.subscribe(this._onWidgetMenuClick, iWidgetId);
						aWidgetNames.push(oWidgetMenuItem);
					}
				}
			}
		}
		var oWidgetMenu = {
				id: "widgetMenuId",
				text: "Widgets",
				submenu: {
					id: "widgetSubMenuId",
					text: '',
					itemdata: aWidgetSubMenu
				}
		};
		return oWidgetMenu;
	},
	/**
	* If menu of widget type does not exist yet return -1.
	* Otherwise Returns the index of array of "widget type submenu"
	* @private
	* @return {Integer} iIndex Index of array of widget submenu describing the type of widget
	*/
	_getWidgetIndexIfTypeExists: function (aWidgets, sType)
	{
		for ( var iIndex = 0; iIndex < aWidgets.length; iIndex ++)
		{
			if ( aWidgets[iIndex].text == sType ) { return iIndex; }
		}
		return -1;
	},
	/**
	* Every time user clicks on MenuItem of Widget,
	* we create "widget" object.
	* If the widget (window) already exists, we add widget object into array of cargo.service
	* @private
	* @param {Integer} iServiceId Identifier of service (widget)
	*/
	_onWidgetMenuClick: function (p_sType, p_aArguments, iServiceId)
	{
		var sWidgetType = this.text; // MenuBar instance contains the name of type
		var oWidgetInfo = new Array();
		if (!cargo.services[iServiceId].widgets)
		{
			cargo.services[iServiceId].widgets = new Array();
			oWidgetInfo['name'] = cargo.services[iServiceId].name;
		}
		else
		{
			oWidgetInfo['name'] = cargo.services[iServiceId].name +'-'+ cargo.services[iServiceId].widgets.length;
		}
		oWidgetInfo['width'] = cargo.services[iServiceId].windowWidth;
		oWidgetInfo['height'] = cargo.services[iServiceId].windowHeight;
		var sURL = '';
		var oNewWidget = new widget(
					iServiceId, // widget id ( == service id )
					oWidgetInfo['name'], // "widget name" || "widget name" + "-" + "number id"
					sWidgetType,
					oWidgetInfo['width'],
					oWidgetInfo['height'],
					sURL,
					cargo.dashboard
					);
		// If input already has been inserted then the new widget receives the last input
		sURL = (cargo.history.length > 0) ?
		cargo.services[iServiceId].url +'?'+
			'cargo_ticket='+cargo.id+
			'&widget_name='+oWidgetInfo['name']+
			'&'+cargo.history[cargo.history.length-1].ns+'='+cargo.history[cargo.history.length-1].id
		:
		cargo.services[iServiceId].url;

		oNewWidget.reloadMainFunction(sURL);
		oNewWidget.destroy.subscribe(cargo.destroyWidget);
		oNewWidget.minimize.subscribe(cargo.minimizeWidget);
		cargo.services[iServiceId].widgets.push(oNewWidget);
		cargo.dashboard.setFocus(oNewWidget); // Set focus on new widget
	},
	/**
	* Create a MenuItem structure that contains the help documents.
	* The structure looks like:
	* HelpMenu = {
			id: "helpMenuId", // Identifier of "help" menu
			text: "Help",
			submenu: {
				id: "helpSubMenuId", // Identifier of "help" submenu
				itemdata: [
					{
					id: "cargoHelpSubMenuId", // Identifier of "help" menu
					text: "Cargo Help",
					url: "../docs/cargoHelp.html",
					target: "_blank"
					}...
					]
				}
	* @private
	* @param {Array} oServices The list of service objects
	* @return {JSON} oHelpMenu Structure of help menu
	*/
	_getHelpSubMenu: function (oServices)
	{
		var oWidgetDescHelpMenuItem = new YAHOO.widget.MenuItem("Widgets Help");
		oWidgetDescHelpMenuItem.value = "Widgets Help";
		oWidgetDescHelpMenuItem.clickEvent.subscribe(this._onWidgetDescHelpMenuClick, oServices);

		var oHelpMenu = {
				id: "helpMenuId",
				text: "Help",
				submenu: {
					id: "helpSubMenuId",
					itemdata: [
						{
							id: "cargoHelpSubMenuId",
							text: "Cargo Help",
							url: "../docs/cargoHelp.html",
							target: "_blank"
						},
						oWidgetDescHelpMenuItem,
						{
							id: "genesHelpSubMenuId",
							text: "Search widget Help",
							url: "../docs/searchHelp.html",
							target: "_blank"
						},
						{
							id: "createHelpSubMenuId",
							text: "How to create new widget",
							url: "../docs/widgetHelp.html#create-widget",
							target: "_blank"
						},
						{
							id: "registerHelpSubMenuId",
							text: "How to register your widget",
							url: "../docs/widgetHelp.html#register-widget",
							target: "_blank"
						}
					]
				}
		};
		return oHelpMenu;
	},
	/**
	* Every time user clicks on MenuItem of Widget Help,
	* we create web page describing all widgets.
	* @private
	* @param {Array} oServices The list of service objects
	*/
	_onWidgetDescHelpMenuClick: function (p_sType, p_aArguments, oServices)
	{
		var sWidgetDescBodyHTML = '';
		for ( var iWidgetId in oServices )
		{
			var oWidgetInfo = oServices[iWidgetId];
			if (typeof(oWidgetInfo) == 'object')
			{
				sWidgetDescBodyHTML += "<h3>"+oWidgetInfo.name+"</h3>\n";
	
				if (oWidgetInfo.icon && oWidgetInfo.icon != null & oWidgetInfo.icon != 'NULL') {
					sWidgetDescBodyHTML += "<img src='"+oWidgetInfo.icon+"'></img>\n";
				}
				sWidgetDescBodyHTML += "<p><b>Description</b>: "+oWidgetInfo.description+"</p>\n";
				if (oWidgetInfo.documentation && oWidgetInfo.documentation != null & oWidgetInfo.documentation != 'NULL') {
					sWidgetDescBodyHTML += "<p><b>Online documentation</b>: <a href='"+oWidgetInfo.documentation+"' target='_blank'>"+oWidgetInfo.documentation+"</a></p>\n";
				}
				// IMP: We print the first provider
				sWidgetDescBodyHTML += "<p><b>Organization</b>: "+oWidgetInfo.providers[0].organization+"</p>\n"; // The first provider
				sWidgetDescBodyHTML += "<p><b>Org. Link</b>: "+oWidgetInfo.providers[0].orglink+"</p>\n"; // The first provider
				sWidgetDescBodyHTML += "<p><b>Author</b>: "+oWidgetInfo.providers[0].name+"</p>\n"; // The first provider
				sWidgetDescBodyHTML += "<p><b>Email</b>: "+oWidgetInfo.providers[0].email+"</p>\n"; // The first provider
			}
		}
		var sHTMLTemplate = '' +
				"<html>\n"+
				"<head>\n"+
					"<meta http-equiv='Content-Type' content='text/html; charset=ISO-8859-1'></meta>\n"+
					"<title>CARGO: Widgets description</title>\n"+
					"<link rel='stylesheet' type='text/css' href='../index-files/welcome.css'></link>\n"+
				"</head>\n"+
				"<body>\n"+
					"<div class='main'>\n"+
						"<div class='container'>\n"+
							"<div class='contentTop' onClick=\"javascript: window.open(\'http://cargo2.bioinfo.cnio.es/\', \'_parent\');\">\n"+
								"<img src='../index-files/new_cargo2.gif' alt='Cancer And Related Genes Online' height='95' width='395' border='0'/>\n"+
							"</div>\n"+
							"<div class='contentCenter'>\n"+
								"<h2>Widgets description</h2>\n"+
								"<div class='item0'>\n"+
									sWidgetDescBodyHTML+
								"</div>\n"+
							"</div>\n"+
							"<div class='footer'>\n"+
								"| <a title='Bioinformatics Unit' href='http://www.cnio.es/es/grupos/plantillas/presentacion.asp?grupo=50004300' target='_blanck'>Bioinformatics Unit</a> | <a title='Structural &amp; Computational Biology Group' href='http://www.cnio.es/es/grupos/plantillas/programa-grupos.asp?pag=660' target='_blanck'>Structural &amp; Computational Biology Group</a> | <a title='CNIO' href='http://www.cnio.es' target='_blanck'>CNIO</a> |\n"+
							"</div>\n"+
						"</div>\n"+
					"</div>\n"+
				"</body>\n"+
				"</html>\n";
		var newDoc = window.open('', '_blank');
		newDoc.document.write(sHTMLTemplate);
		newDoc.document.close();
	}
};
