/**
 *  ****************************************************************************
 *  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 filter filtre d'utilisation du topic
 * @param name le nom du topic
 * @param topicID l'identifiant ezPublish de l'aide associée
 */  
	'addTopic' : function(type, filter, name, topicID)
	{
		if (this['htype_' + type] == undefined)
		{
			this['htype_' + type] = new Array();
			this._helpTypes.push(type);
		}
		this['htype_' + type].push({
		   'filter' : filter,
		   'id' : 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')
      {
         // Recherche des aides disponibles pour la configuration en cours
         var laHelpIDs = [];
         if ( this['htype_' + type] != undefined )
         {
            // Au moins une aide est défini pour ce type
            // Pour chaque aide définit, contrôle des filtre d'utilisation
            for ( var i = 0; i < this['htype_' + type].length ; i++ )
            {
               var filter = this['htype_' + type][i].filter;
               // filtre sur la variable
               if ( filter.variable != '*' && filter.variable !=  state.variable.id )
               {
                  continue;
               }
               // filtre sur le type de résultat
               if ( filter.visualisation_type != '*' && filter.visualisation_type !=  state.resultType.id )
               {
                  continue;
               }
               // filtre sur l'emprise
               if ( filter.emprise != '*' && filter.emprise !=  state.area._id )
               {
                  continue;
               }
               // filtre sur le point géographique
               if ( filter.geoitem != '*' )
               {
                  if ( typeof state.geoItem == 'undefined' ) {
                     continue;
                  }
                  if ( filter.geoitem != state.geoItem._id ) { 
                     continue;
                  }
               }
               // filtre sur une profondeur
               if ( filter.depth != '*' && filter.depth != state.depth )
               {
                  continue;
               }
               laHelpIDs.push( this['htype_' + type][i].id );
            }
         }
         if ( laHelpIDs.length == 0 )
         { // 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;
         }
         // Création des requêtes d'aide
         for ( var i = 0; i < laHelpIDs.length ; i++ )
         {
            var request = new HelpRequest(type, laHelpIDs[i], state, this._config, lang, i);
            var requestHash = request.getHashcode();
            if ( this._cache[requestHash] )
            {
               // 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;
            }
         }
         // Masquage des onglets en trop
         $('.result > .infos > .topic_tab.' + type).each(function(){
            var hidde = true
            for ( var i =0 ; i < laHelpIDs.length ; i++ )
            {
               if( $(this).hasClass ( String(i) ) )
               {
                  hidde = false;
               }
            }
            if ( hidde )
            {
               $(this).css( 'display', 'none' );
            }
         });
         // Masquage de paneaux en trop
         $('.topic.' + type).each(function(){
            var hidde = true
            for ( var i =0 ; i < laHelpIDs.length ; i++ )
            {
               if( $(this).hasClass ( String(i) ) )
               {
                  hidde = false;
               }
            }
            if ( hidde )
            {
               $(this).css( 'display', 'none' );
            }
         });
      }else
      {
         // Création de la requête
         var request = new HelpRequest(type, null, state, this._config, lang, 0 );
         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, idx )
{
	// 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;
	this.index = idx;
	
	// 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 + ( state.area !== null ? '_' + state.area._id : '' );
			this.nodeID = config.appNodeID;
			break;
		case 'analyse' :
			// Chargement bulletin d'analyse
			this.service = PrevimerToolkit.getService(
				'getBulletin',
				state.getRequestParams(CurrentState.TYPE_ANALYSIS, config));
			this.server = config;
			this.hash = type + '_' + state.area._id;
			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();
				if ( this.type == 'bulletin' )
				{
				   this.url = "/content/view/bulletin/" + this.nodeID;
				}else
				{
				   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()
   {
      // recherche de l'onglet à utiliser
      var loTab = $( '.result > .infos > .topic_tab.' + this.type + '.' + this.index );
      if( !loTab || ( loTab && loTab.length == 0 ) )
      {
         loTab = $( '.result > .infos > .topic_tab.' + this.type + '.0').clone(true).insertAfter( '.result > .infos > .topic_tab.' + this.type + '.0' );
         loTab.removeClass( '0' );
         loTab.addClass( String( this.index ) );
      }
      // recherche du paneau à utiliser
      var loPan = $('.topic.' + this.type + '.' + this.index );
      if ( !loPan || (loPan && loPan.length == 0 ) )
      {
         loPan = $('.topic.' + this.type + '.0').clone(true).insertAfter( '.topic.' + this.type + '.0' );
         loPan.removeClass( '0' );
         loPan.addClass( String( this.index ) );
      }
      if ( !loPan.hasClass( this.type + this.index ) ) 
      {
         loPan.addClass( this.type + this.index );
      }
      if ( this.title != null ) 
      {
         if ( !this.isAlone )
         {
            function tabCollapse(){
               window.location = "#" + that.type + that.index;
               if ( !$('.topic.' + that.type + '.' + that.index ).hasClass( 'expanded' ) ) {
                  $('.topic.' + that.type + '.' + that.index ).addClass('expanded')
                  .children('.body').slideDown('fast');
               }
               return false;
            }

            loTab.css('display', 'block');
            // Mise à jour du titre de l'onglet
            if ( this.type != 'bulletin' && this.type != 'analysis' && this.type != 'result_infos' )
            {
               loTab.find( '.title > a' ).empty();
               var tabTitle = this.shortTitle ? this.shortTitle : this.title;
               if ( tabTitle.length > 30 )
                  tabTitle = tabTitle.substr( 0, 27 ) + '...';
               loTab.find( '.title > a' ).html( tabTitle );
               loTab.find( '.title > a' ).attr( 'title', this.title );
            }
            loTab.find( '.title > a' ).unbind('click');
            loTab.find( '.title > a' ).click(tabCollapse);
         }

         if ( loPan.children().length > 0 )
         {
            // Mettre à jour
            if ( ( this.type != ' bulletin' && this.type != 'analysis' && this.type != 'result_infos' ) ||
                  ( this.title && this.isAlone ) )
            {
               loPan.find('h2 > a').html( this.title )
            }else
            {
               loPan.find('h2 > a').html( loTab.find('.title > a').attr( 'title' ) );
            }
            loPan.find('h2 > a').attr( 'name', this.type + this.index );
            loPan.find('.body').html( this.content );

            if ( !this.isAlone )
            {
               // Mise à jour du bouton d'impression
               loPan.find( '.button_group > .popup > a' ).unbind( 'click' );
               loPan.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
               loPan.find( '.button_group > .print > a' ).unbind( 'click' );
               loPan.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;
               });
               // Mise à jour du bouton collapse
//               loPan.find( '.button_group > .collapse > a' ).unbind( 'click' );
//               loPan.find( '.button_group > .collapse > 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
            loPan = this._create();
         }
         loPan.css('display', 'block');

         // Gestion des boutons
         if ( !this.isAlone )
         {
            var that = this;
            // Bouton collapse
            loTab.find('.button_group > .collapse > a').unbind('click');
            loTab.find('.button_group > .collapse > a').click(tabCollapse);
            // Bouton popup
            loTab.find('.button_group > .popup > a').unbind('click');
            loTab.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 )
               loTab.find('.button_group > .popup > a').addClass('disabled');
         }
      }
      else
      {
         if ( ! this.isAlone )
         {
            loTab.css('display', 'none');
            loPan.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;
               }
            }
         }else
         {
            loPan.css('display','block');
         }
      }
   },
/**
 * Crée un structure d'affichage d'un topic
 */
   '_create' : function()
   {
      var topic = $('.topic.' + this.type + '.' + this.index );
      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 );
      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 + this.index + '"/>');
         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 + '.' + this.index + '> .title > a').attr( 'title' ) );
            link.html( $('.result > .infos > .topic_tab.' + this.type + '.' + this.index + '> .title > a').attr( 'title' ) );
         }

         title.append( link );
         link.click(collapse);
      }
      titleContainer.append( title );
      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 );
      topic.append( body );
      return topic;
   }
}

