/**
 *  ****************************************************************************
 *  File : design/previmer/javascript/previmer_helptopics.js
 *  vers : 1.1
 *  build: 20070731
 *  Author : Virtualys
 *  ****************************************************************************
 **/

/**
 * ============================================================================= 
 * HelpTopics
 * Gestion des pages d'aides ez en fonction du contexte
 * ============================================================================= 
 */ 
HelpTopics = function()
{
	// On déclare l'objet dans les instances globales
	this.className = 'HelpTopics';
	PrevimerToolkit.registerGlobalInstance(this);

	// Types d'aide disponible
	this._helpTypes = [ ];
	// Config
	this._config = null;
	this._cache = { };
}
HelpTopics.prototype = {
/**
 * Déclare un topic d'aide.
 * @param type le type d'aide
 * @param name le nom du topic
 * @param topicID l'identifiant ezPublish de l'aide associée
 */  
	'addTopic' : function(type, name, topicID)
	{
		if (this['htype_' + type] == undefined)
		{
			this['htype_' + type] = { };
			this._helpTypes.push(type);
		}
		this['htype_' + type][name] = topicID;
	},
/**
 * Demande l'affichage si possible d'un topic d'aide.
 * @param type le type d'aide à afficher
 * @param state l'état sélectionné par l'utilisateur
 */  
	'displayTopic' : function(type, state, lang)
	{
		// On recherche l'identifiant de l'élément concerné par la demande d'infos
		if (type != 'bulletin' && type != 'analyse' && type != 'result_infos')
		{
			switch (type)
			{
				case 'variable' :
					var name = state.variable.id;
					break;
				case 'emprise' :
					var name = state.area._id;
					break;
				case 'visualisation_type' :
					var name = state.resultType.id;
					break;
				default :
					var name = null;
					break;
			}
			if (this['htype_' + type] == undefined
					|| this['htype_' + type][name] == undefined)
			{
				// Pas d'aide disponible
				$('.result > .infos > .topic_tab.' + type).css('display', 'none');
				$('.topic.' + type).css('display','none');
				var types = [ 'bulletin', 'analyse', 'visualisation_type', 'variable', 'emprise', 'result_infos' ];
				for (var i = 0; i < types.length; ++i)
				{
					if ($('.result > .infos > .topic_tab.' + types[i]).css('display') == 'block')
					{
						return;
					}
				}
				return;
			}
			var id = this['htype_' + type][name];
		}
		
		// Création de la requête
		var request = new HelpRequest(type, id, state, this._config, lang);
		var requestHash = request.getHashcode();
		// La demande de bulletin n'est gérée que pendant la période de forecast
		if (type == 'bulletin')
		{
			var today = new Date();
			today.setHours(0);
			today.setMinutes(0);
			today.setSeconds(0);
			today.setMilliseconds(0);
			var seldate = new Date(state.date.getTime());
			seldate.setHours(0);
			seldate.setMinutes(0);
			seldate.setSeconds(0);
			seldate.setMilliseconds(0);
			if (seldate.getTime() < today.getTime())
			{
				// On masque le bulletin
				request.display();
				return;
			}
		}

		// On recherche en cache
		if (this._cache[requestHash])
		{
			if (type == 'analyse')
			{
				var previous = this._cache[requestHash];
				var timestamp = state.date.getTime();
				if (previous.startRange <= timestamp && previous.endRange > timestamp)
				{
					// La requête en cache couvre la date demandée, on l'affiche
					this._cache[requestHash].display();
				}
				else
				{
					// ... sinon on recharge les nouvelles informations
					request.load();
					this._cache[requestHash] = request;
				}
			}
			else
			{
				// Requête trouvée en cache, on l'affiche direct
				this._cache[requestHash].display();
			}
		}
		else
		{
			// On charge les infos
			request.load();
			// Mise en cache
			if ( type != 'result_infos')
				this._cache[requestHash] = request;
		}
	}
}

/**
 * ============================================================================= 
 * HelpRequest
 * Demande d'affichage d'un article d'aide en cours.
 * =============================================================================
 */  
HelpRequest = function(type, id, state, config, lang)
{
	// On déclare l'objet dans les instances globales
	this.className = 'HelpRequest';
	PrevimerToolkit.registerGlobalInstance(this);
	this.type = type;
	this.title = null;
	this.shortTitle = null;
	this.content = null;
	this.url = null;
	this.lang = lang;
	this.isAlone = state.isAlone ? state.isAlone : false;
	
	// Requête Ajax
	switch(type)
	{
		case 'bulletin' :
			// Chargement bulletin
			this.service = PrevimerToolkit.getService(
				'getBulletin',
				state.getRequestParams(CurrentState.TYPE_BULLETIN, config));
			this.server = config;
			this.hash = type;
			break;
		case 'analyse' :
			// Chargement bulletin d'analyse
			this.service = PrevimerToolkit.getService(
				'getBulletin',
				state.getRequestParams(CurrentState.TYPE_ANALYSIS, config));
			this.server = config;
			this.hash = type;
			break;
		case 'result_infos' :
			// Chargement Information sur le résultat
			this.service = PrevimerToolkit.getService(
					'getResultInfos',
					state.getRequestParams(CurrentState.TYPE_RESULT, config));
				this.server = config;
				this.hash = type + '_' + state.resultType.id + '_' + config.calendar.date.getTime();
				break;
		default :
			// Chargement aide sur un élément
			// On charge l'identifiant de l'élément concerné
			this.service = config.helpURLPrefix + '/' + id;
			this.server = { ajaxServer : '' };
			this.hash = type + '_' + id;
			break;
	}
}
HelpRequest.prototype = {
/**
 * -----------------------------------------------------------------------------
 * Obtient un code identifiant de manière unique la requête.
 */ 
	'getHashcode' : function()
	{
		return this.hash;
	},
/**
 * -----------------------------------------------------------------------------
 * Charge les informations depuis le serveur.
 */ 
	'load' : function()
	{
		// Accès Ajax
		var ajaxEngine = new VAjaxEngine(this.server,
			'PrevimerToolkit.getGlobalInstance("' + this._objectID + '")._onTopicLoaded',
			'PrevimerToolkit.getGlobalInstance("' + this._objectID + '")._onTopicFailed');
		ajaxEngine.doGet(this.service);
	},
/**
 * -----------------------------------------------------------------------------
 * Callback Ajax appelée lorsque le topic a été obtenu.
 */ 
	'_onTopicLoaded' : function(context)
	{
		var root = context.lastDocument;
		if (root)
		{
			if( this.type != 'result_infos' )
			{
				var rangeNodes = $('range',root);
				if (rangeNodes.length == 1)
				{
					this.startRange = parseInt( rangeNodes.attr('from'), 10);
					this.endRange = parseInt( rangeNodes.attr('to'), 10);
				}
				this.title = $(root).find('title').text();
				this.shortTitle = $(root).find('short_title').text();
				this.content = $(root).find('content').text();
				this.url = $(root).find('node_url').text();
			}else
			{
				this.title = 'Infos';
				this.content = $(root).text();
				this.url = null;
			}
		}
		this.display();
	},
/**
 * -----------------------------------------------------------------------------
 * Callback Ajax appelée lorsque le topic a été en erreur.
 */ 
	'_onTopicFailed' : function(context) {
		this.display();
	},
/**
 * -----------------------------------------------------------------------------
 * Affiche la zone d'aide si elle est valide, la cache sinon.
 */ 
	'display' : function()
	{
		if (this.title != null) 
		{
		   if ( !this.isAlone )
		   {
   			function tabCollapse(){
   				window.location = "#" + that.type;
   				if (!$('.topic.' + that.type).hasClass('expanded')) {
   					$('.topic.' + that.type).addClass('expanded')
   						.children('.body').slideDown('fast');
   				}				
   				return false;
   			}

   			$('.result > .infos > .topic_tab.' + this.type).css('display', 'block');
   			// Mise à jour du titre de l'onglet
   			if ( this.type != 'bulletin' && this.type != 'analysis' && this.type != 'result_infos' )
   			{
   				$('.result > .infos > .topic_tab.' + this.type + '> .title > a').empty();
   				var tabTitle = this.shortTitle ? this.shortTitle : this.title;
   				if ( tabTitle.length > 30 )
   					tabTitle = tabTitle.substr( 0, 27 ) + '...';
   				$('.result > .infos > .topic_tab.' + this.type + '> .title > a').html( tabTitle );
   				$('.result > .infos > .topic_tab.' + this.type + '> .title > a').attr( 'title', this.title );
   			}
   			$('.result > .infos > .topic_tab.' + this.type + '> .title > a').unbind('click');
   			$('.result > .infos > .topic_tab.' + this.type + '> .title > a').click(tabCollapse);
		   }
			var topic = $('.topic.' + this.type)
			if ( topic.children().length > 0 )
			{
				// Mettre à jour
				if ( ( this.type != ' bulletin' && this.type != 'analysis' && this.type != 'result_infos' ) ||
		           ( this.title && this.isAlone ) )
				{
					topic.find('h2 > a').html( this.title )
				}else
				{
					topic.find('h2 > a').html( $('.result > .infos > .topic_tab.' + this.type + '> .title > a').attr( 'title' ) );
				}
/*
				topic.find('h2 > a').unbind('click');
				topic.find('h2 > a').click( function(){
					var topic = $(this).parents('.topic');
					if (topic.hasClass('expanded')) {
						topic.removeClass('expanded')
							.children('.body').slideUp('fast');
						
					}
					else {
						topic.addClass('expanded')
							.children('.body').slideDown('fast');
					}
					return false;
				} );
*/
				topic.find('.body').html( this.content );
				
				if ( !this.isAlone )
				{
   				// Mise à jour du bouton d'impression
   				topic.find( '.button_group > .popup > a' ).unbind( 'click' );
   				topic.find( '.button_group > .popup > a' ).click( function(){
   					if ( that.url && !$(this).hasClass('disabled'))
   					{
   						$(window.browser).get(0).getCBManager().onPopup( '/layout/set/popup' + that.url );
   					}
   					return false;
   				});
				
   				// Mise à jour du bouton popup
   				topic.find( '.button_group > .print > a' ).unbind( 'click' );
   				topic.find( '.button_group > .print > a' ).click( function(){
   					if ( that.url && !$(this).hasClass('disabled'))
   					{
   						$(window.browser).get(0).getCBManager().onPopup( '/layout/set/print' + that.url );
   					}
   					return false;
   				});
				}
				
			}else
			{
				// créer
				topic = this._create();
			}
			topic.css('display', 'block');
			
			// Gestion des boutons
			if ( !this.isAlone )
			{
   			var topicTab = $('.result > .infos > .topic_tab.' + this.type);
   			var that = this;
   			// Bouton collapse
   			topicTab.find('.button_group > .collapse > a').unbind('click');
   			topicTab.find('.button_group > .collapse > a').click(tabCollapse);
   			// Bouton popup
   			topicTab.find('.button_group > .popup > a').unbind('click');
   			topicTab.find('.button_group > .popup > a').click(function(){
   				if ( that.url )
   				{
   					$(window.browser).get(0).getCBManager().onPopup( '/layout/set/popup' + that.url );
   				}
   				return false;
   			});
   			if( !this.url )
   				topicTab.find('.button_group > .popup > a').addClass('disabled');
			}
		}
		else
		{
			$('.result > .infos > .topic_tab.' + this.type).css('display', 'none');
			$('.topic.' + this.type).css('display','none');
			var types = [ 'bulletin', 'analyse', 'visualisation_type', 'variable', 'emprise', 'infos' ];
			for (var i = 0; i < types.length; ++i)
			{
				if ($('.result > .infos > .topic_tab.' + types[i]).css('display') == 'block')
				{
					return;
				}
			}
		}
	},
/**
 * Crée un structure d'affichage d'un topic
 */
	'_create' : function()
	{
		var topic = $('.topic.' + this.type);
		if( !topic.hasClass( 'expanded' ) )
		{
			topic.addClass( 'expanded' );
		}
		if ( this.isAlone )
		   var titleContainer = $('<div class="title"/>');
		else
		var titleContainer = $('<div class="title buttons_holder"/>');
		topic.append( titleContainer );
//		titleContainer.appendTo( topic);
		if ( !this.isAlone )
		{
   		function createButton( type, label, link, callback, stateClass, title)
   		{
   			var button = $('<div class="button ' + type + '"/>');
   			var aElm = $('<a href="' + ( link ? link : '#' ) + '"/>');
   			if ( title )
   				aElm.attr('title', title );
   			if ( callback )
   			{
   				aElm.click( callback );
   			}
   			if ( stateClass )
   			{
   				aElm.addClass( stateClass );
   			}
   			aElm.appendTo( button );
   			var text = $('<span/>');
   			text.html( label );
   			text.appendTo( aElm );
   			return button;
   		}
   		function collapse() {
   			var topic = $(this).parents('.topic');
   			if (topic.hasClass('expanded')) {
   				topic.removeClass('expanded')
   					.children('.body').slideUp('fast');
   				
   			}
   			else {
   				topic.addClass('expanded')
   					.children('.body').slideDown('fast');
   			}
   			return false;
   		}
   		var buttonGroup = $('<div class="button_group left"/>');
   		buttonGroup.appendTo(titleContainer);
   		// Bouton retour
   		buttonGroup.append(
   				createButton(
   						'back',
   						'Back', 
   						'#appTop',
   						null,
   						null,
   						this.lang == 'en' ? 'Back' : 'Retour' ) );
   		var that = this;
   		// Bouton Popup
   		buttonGroup.append(
   				createButton(
   						'popup',
   						'Popup',
   						'#',
   						function(){
   							if ( that.url && !$(this).hasClass('disabled'))
   							{
   								$(window.browser).get(0).getCBManager().onPopup( '/layout/set/popup' + that.url );
   							}
   							return false;
   						},
   						this.url ? '' : 'disabled',
   						this.lang == 'en' ? 'Open in popup' : 'Ouvrir en popup' ) );
   		// Bouton collapse
   		buttonGroup.append(
   				createButton(
   						'collapse',
   						'Collapse',
   						'#',
   						collapse,
   						null,
   						this.lang == 'en' ? 'Open / Close' : 'Ouvrir / Fermer ' ));
		}
		if ( this.isAlone )
		{
		   var title = $('<h2>' + this.title + '</h2>' );
		}else
		{
		   var title = $('<h2/>');
		   var link = $('<a name="' + this.type + '"/>');
   		if ( this.type != 'bulletin' && this.type != 'analysis' && this.type != 'result_infos' )
   		{
   			link.attr('title', this.title);
   			link.html( this.title );
   		}else
   		{
   			link.attr('title', $('.result > .infos > .topic_tab.' + this.type + '> .title > a').attr( 'title' ) );
   			link.html( $('.result > .infos > .topic_tab.' + this.type + '> .title > a').attr( 'title' ) );
   		}
		
   		link.appendTo( title );
   		link.click(collapse);
		}
		titleContainer.append( title );
//		title.appendTo(titleContainer);
		if ( !this.isAlone )
		{
		   buttonGroup = $('<div class="button_group right"/>');
		   titleContainer.append( buttonGroup );
   		// Bouton Print
   		buttonGroup.append(
   				createButton(
   						'print',
   						'Print',
   						'#',
   						function(){
   							if ( that.url && !$(this).hasClass('disabled'))
   							{
   								$(window.browser).get(0).getCBManager().onPopup( '/layout/set/print' + that.url );
   							}
   							return false;
   						},
   						this.url ? '' : 'disabled',
   						this.lang == 'en' ? 'Print topic' : 'Imprimer la rubrique' ) );
		}
		var body = $('<div class="body"/>');
		body.html( this.content );
		body.appendTo(topic);
		return topic;
	}
}
