/**
 *  ****************************************************************************
 *  File : design/previmer/javascript/previmer_theme.js
 *  vers : $Revision $
 *  build: 20091103
 *  Author : Virtualys
 *  ****************************************************************************
 **/

/**
 * =============================================================================
 * PrevimerThemeBrowser
 * Objet permettant l'affichage de la liste des thèmes/applications pour un
 *  thème/application donné. 
 * ============================================================================= 
 */
PrevimerThemeBrowser = function(hashThemeList, hashAppConfigList, config) {
	if (hashThemeList.length == 0) return;
		// Configuration
		this._config = config ;
		// Liste des thèmes
		this._themeList = hashThemeList ;
		// Liste des définitions des thèmes
		this._themeDefinitionList = null;
		// Liste des configurations des applications associes
		this._appConfigList = hashAppConfigList ;
		// Informations de version
		this._version = {
			'appID'    : 'previmer-jsthemebrowser',
			'appLabel' : 'Previmer theme browser',
			'version'  : '2.0',
			'build'    : '20091008'
		};
		// Gestionnaire d'IHM
		this._ihmManager = new PrevimerThemeIHM(this);

		// On déclare l'objet dans les instances globales
		this.className = 'PrevimerThemeBrowser';
		PrevimerToolkit.registerGlobalInstance(this);

		// Préparation des paramètres Ajax (serveur et proxy)
		this._config.ajaxServer ='';
		if (this._config.protocol)
		{
			this._config.ajaxServer += this._config.protocol + '://';
		}
		if (this._config.server)
		{
			this._config.ajaxServer += this._config.server;
		}
		if (this._config.port)
		{
			this._config.ajaxServer += ':' + this._config.port;
		}

		this._config.ajaxServer += '/';
		if (this._config.URLPrefix)
		{
			this._config.ajaxServer += this._config.URLPrefix;
		}

		if (this._config.nodeID)
		{
			this._config.ajaxServer += 'nodeid/' + this._config.nodeID + '/' ;
		}

		this._config.ajaxProxy = this._config.proxy ? this._config.proxy : null;
		var ajaxEngine = new VAjaxEngine(this._config,
			'PrevimerToolkit.getGlobalInstance("' + this._objectID +
			'").onThemesLoaded');

		// Préparation de la requête en fonction de la page à afficher
		// Si 1 seul thème présent dans la liste, cala signifie que la page demandé
		// est la pages des thèmes, sinon c'est la page des applications.
		var service='';
		var themeInfosParams={
				'appli': null,
				'w':1000,
				'h':1000,
				'lang':this._config.locale,
				'theme': null,
				'type': new Array(),
				'area': new Array(),
				'var':new Array()
		};
		if (this._themeList.length > 1)
		{
			service='getFilteredApplicationInfos';
			themeInfosParams.appli = this._appConfigList[0].config.appID;
			themeInfosParams.theme = new Array() ;
			for (var i=0 ; i < this._appConfigList.length ; i++)
			{
				themeInfosParams['theme'].push(this._appConfigList[i].config.themeID);
				themeInfosParams['type'].push(this._appConfigList[i].config.themeID + '.' +this._appConfigList[i].config.visu);
				themeInfosParams['area'].push(this._appConfigList[i].config.themeID + '.' +this._appConfigList[i].config.zone);
				themeInfosParams['var'].push(this._appConfigList[i].config.themeID + '.' +this._appConfigList[i].config.variable);
			}
		}else
		{
			service='getFilteredThemeInfos';
			themeInfosParams.theme = this._themeList;
			themeInfosParams.appli = new Array();
			for (var i=0 ; i < this._appConfigList.length ; i++)
			{
				themeInfosParams['appli'].push(this._appConfigList[i].config.appID);
				themeInfosParams['type'].push(this._appConfigList[i].config.appID + '.' +this._appConfigList[i].config.visu);
				themeInfosParams['area'].push(this._appConfigList[i].config.appID + '.' +this._appConfigList[i].config.zone);
				themeInfosParams['var'].push(this._appConfigList[i].config.appID + '.' +this._appConfigList[i].config.variable);
			}
		}
		ajaxEngine.doGet(
				PrevimerToolkit.getService(
						service,
						themeInfosParams));
}
PrevimerThemeBrowser.prototype = {
/**
 * -----------------------------------------------------------------------------
 * Callback appelée sur réception de la trame de description d'un/des thème(s)
 * en provenance de Tomcat
 * @param context l'objet d'accès aux informations Ajax
 */
	'onThemesLoaded' : function(context)
	{
		this._themeDefinitionList = new Array();
		var applicationList = new Array();
		var themesContext = context.lastDocument;
		var that = this;
		$('theme', themesContext).each(function(i){
			that._themeDefinitionList[$(this).attr('id')] = new Theme(this);
		});
		this._ihmManager.initIHM();
	},

	'getTheme' : function(themeID)
	{
		return (this._themeDefinitionList[themeID] != 'undefined')? this._themeDefinitionList[thmeID] : false ;
	},

	'getApplicationConfig' : function(appID,themeID)
	{
		var appCfg = false ;
		for (var i = 0 ; i < this._appConfigList.length ; i++)
		{
			if ((this._appConfigList[i].config.appID == appID) &&
				 (this._appConfigList[i].config.themeID == themeID))
			{
				appCfg = this._appConfigList[i];
				break;
			}
		}
		return appCfg ;
	},
	'getCBManager' : function() {
		return this._ihmManager;
	}
};

/**
 * =============================================================================
 * Theme
 * Theme Previmer
 * ============================================================================= 
*/
Theme = function(domNode)
{
	// Identifiant du theme
	this._id = $(domNode).attr('id');
	// Construction de la liste des applications
	this._applicationList = new Array();
	var that = this;
	$('application', domNode).each(function(i){
		that._applicationList[$(this).attr('id')] = new Application(this,true);
	});
}
Theme.prototype ={
	'getApplication' : function( appID ) 
	{
		return (this._applicationList[appID] != 'undefined')? this._applicationList[appID] : false ;
	}
};

/**
 * =============================================================================
 * PrevimerThemeIHM
 * =============================================================================
*/
PrevimerThemeIHM = function(browser){
	this._componentSuffix = {
		'IMG'   : 'CoverageMapImg',
		'MAP'   : 'CoverageMap',
		'AREA'  : 'AreaListDiv',
		'GEOITEM'  : 'GeoitemListDiv'
	};
	this._componentList = null;
	this._browser = browser ;

	// initialise la liste des composants
	this.initComponents(this._browser._themeList, this._browser._appConfigList);
}
PrevimerThemeIHM.prototype = {
/**
 * -----------------------------------------------------------------------------
 * Initialise la liste des composants à utilisé pour construire l'interface
 * @param themeList liste des thèmes
 * @param applicationList liste des configuration des applications  
 */
	'initComponents' : function(themeList, applicationList)
	{
		this._componentList = new Array();
		for (var i = 0 ; i < themeList.length ; i ++)
		{
			this._componentList[themeList[i]] = new Array();
		}
		for (var i = 0 ; i < applicationList.length ; i++)
		{
			var themeID = applicationList[i].config.themeID;
			var appID = applicationList[i].config.appID;
			var themeArray = this._componentList[themeID] ;
			themeArray.push({
				'appID' : appID,
				'IMG' : $('#' + applicationList[i].config.prefixID + this._componentSuffix['IMG']),
				'MAP' : $('#' + applicationList[i].config.prefixID + this._componentSuffix['MAP']),
				'AREA' : $('#' + applicationList[i].config.prefixID + this._componentSuffix['AREA']),
				'GEOITEM' : $('#' + applicationList[i].config.prefixID + this._componentSuffix['GEOITEM'])
			});
		}
	},
/**
 * -----------------------------------------------------------------------------
 * Initialise l'interface lorsque tout les éléments sont présent pour
 * l'affichage
 */
	'initIHM' : function()
	{
		var themeList = this._browser._themeDefinitionList ;
		var appList=null, area=null, appCfg=null, params = null, image = null, map = null;
		for (var theme in  themeList)
		{
			appList = themeList[theme]._applicationList ;
			for (var appli in appList)
			{
				appCfg = null;
				if (typeof appList[appli] != 'function')
				{
					appCfg = this._browser.getApplicationConfig(appli,theme);
					if (!appCfg) continue;
					image = this.getComponent(theme,appli,'IMG');
					// recherche de l'aire voulu
					area = appList[appli].getArea(appCfg.config.zone);
					if (!area) continue;
					// Construction de l'URL pour l'image
					params = {
							'theme' : themeList[theme]._id ,
							'appli' : appList[appli]._id,
							'type' : appCfg.config.visu,
							'area' : area._id,
							'var'  : appCfg.config.variable,
							'w' : image.width(),
							'h' : image.height(),
							'lang' : this._browser._config.locale
					};
					var url = this._browser._config.ajaxServer +
									PrevimerToolkit.getService('getBackground', params);
					// Affichage de l'image
					image.attr('src', url);
					// Construction du map
					ratio = [ image.width() / 1000, image.height() / 1000 ];
					map = this.getComponent(theme,appli,'MAP');
					switch (appCfg.config.visu)
					{
						case 'map' :
							//recherche de l'emprise par défaut
							var defaultRootArea = appList[appli].getArea(appCfg.config.zone);
							// Trie des areas par zIndex
							var areaList = defaultRootArea._areas;
							var orderedAreas = new Array();
							for (var i = 0; i < areaList.length; ++i)
							{
								var changed = false;
								for (var j = 0; j < orderedAreas.length; ++j)
								{
									if (orderedAreas[j]._zIndex > areaList[i]._zIndex)
									{
										orderedAreas.splice(j, 0, areaList[i]);
										changed = true;
										break;
									}
								}
								if (!changed)
								{
									orderedAreas.push(areaList[i]);
								}
							}
							// Création de la map
							for (var i = orderedAreas.length; i-- > 0; )
							{
								$(orderedAreas[i].getAreaMap(ratio, null,appCfg)).appendTo(map);
							}
							// Ajout de l'emprise globale
							$(defaultRootArea.getAreaMap(image,null,appCfg)).appendTo(map);
							
							// Construction des liens textes
							var areaDiv = this.getComponent(theme,appli,'AREA');
							var areaCombo = areaDiv.find('.select');
							var areaOptions = new Array();
							this.fillAreaOptions(theme, appli, areaOptions );
							areaCombo.vSelect(areaOptions);
							areaCombo.change(function(){
								window.location = this.selValue
								return false;
							});
							break;
						case 'spectrum':
						case 'temporal':
							// Création de la map
							var coverageList = appList[appli].getGeoItemList(appCfg.config.variable,appCfg.config.visu);
							for (var coverage in coverageList)
							{
								$(coverageList[coverage].getAreaMap(ratio,null,appCfg)).appendTo(map);
							}
							// Construction des liens textes des emprises
							var areaDiv = this.getComponent(theme,appli,'AREA');
							var areaCombo = areaDiv.find('.select');
							var areaOptions = new Array();
							this.fillAreaOptions(theme, appli, areaOptions );
							areaCombo.vSelect(areaOptions);
//							$.vSelect.select( areaCombo, ':first' );
							areaCombo.change(function(){
								window.location = this.selValue
								return false;
							});
							
							// Construction de la liste des geoitems
							var geoitemDiv = this.getComponent(theme, appli, 'GEOITEM');
							var combo = geoitemDiv.find('.select');
							var geoitemOptions = new Array();
							for (var geoItemID in coverageList)
							{
							   if (coverageList[geoItemID]._area == appCfg.config.zone )
							   {
							      geoitemOptions.push({
							         value    : coverageList[geoItemID]._computeLink(null, this._browser.getApplicationConfig( appli, theme ) ),
							         text     : HtmlDecode( 
							               coverageList[geoItemID]._label.replace( 
							                     new RegExp( " [\(][^\(]*[\)]$" ),
							                     '' 
					                     )
			                     ),
			                     selected : appCfg.config.geoItem == coverageList[geoItemID]._id ? appCfg.config.geoItem : coverageList[geoItemID]._default 
							      });
						      }
						   }
				         combo.vSelect(geoitemOptions);
				         combo.change(function(){
				            window.location = this.selValue
				            return false;
				         });
				         if( geoitemOptions.length > 0 )
				         {
				            geoitemDiv.css('display', 'block' );
				         }
							break;
						case 'section' :
						case 'profile' :
							break;
					}
				}
			}
		}
	},
	'fillAreaOptions' : function( theme, application, options )
	{
		var fillOptions = function(areaNode, applicationConfig, index, opts)
		{
			var option = {
				value		: areaNode._computeLink(null, applicationConfig),
				text		: areaNode._label,
				selected	: applicationConfig.config.zone == areaNode._id,
				children	: []
			};
			for (var i = 0; i < areaNode._areas.length; ++i)
			{
				fillOptions(areaNode._areas[i],applicationConfig, index + 1, option.children);
			}
			opts.push(option);
		};
		var rootArea = this._browser._themeDefinitionList[theme].getApplication(application).getRootArea();
		var appCfg = this._browser.getApplicationConfig(application,theme);
		fillOptions( rootArea, appCfg, 0, options);
	},
/**
 * -----------------------------------------------------------------------------
 * Recherche un composants dans la liste des composants
 * @param theme identifiant du theme
 * @param application identifiant de l'application
 * @param suffix suffixe du conteneur
 */
	'getComponent' : function(theme,application,suffix)
	{
		var themeComponentList = this._componentList[theme] ;
		for (var i = 0 ; i < themeComponentList.length ; i++)
		{
			if (themeComponentList[i].appID == application)
				return themeComponentList[i][suffix] ;
		}
		return false ;
	},
/**
 * -----------------------------------------------------------------------------
 * Construit la liste des liens vers les résultats d'application
 * @param theme identifiant du theme
 * @param application identifiant de l'application
 */
	'getAreasLinks' : function(theme, application)
	{
		var rootArea = this._browser._themeDefinitionList[theme].getApplication(application).getRootArea();
		var appCfg = this._browser.getApplicationConfig(application,theme);
		var areaList = $('<ul/>');
		$(this.getTextAreaLink(rootArea,appCfg)).appendTo(areaList) ;
		return areaList;
	},
/**
 * -----------------------------------------------------------------------------
 * Construction récurcive des liens textes vers les résultats
 * @param area noeud area
 * @param applicationConfig configuration de l'application
 */
	'getTextAreaLink' : function(area,applicationConfig)
	{
		var list = $('<li/>');
		var linkArea = $('<a/>');
		linkArea.attr('href', area._computeLink(null, applicationConfig));
		linkArea.html(area._label + '\n');
		linkArea.appendTo(list);
		if (area._areas.length > 0)
		{
			var childList = $('<ul/>');
			for (var i = 0 ; i < area._areas.length ; i++)
				$(this.getTextAreaLink(area._areas[i],applicationConfig)).appendTo(childList);
			$(childList).appendTo(list);
		}
		return list;
	}
};
