/**
 * @package benchmark
 * @subpackage commentaire
 * @filesource
 */

/**
 * Action d'un formulaire de commentaires
 *
 * @author Benoit Landhauser <landhauser@benchmark.fr>
 * @package benchmark
 * @subpackage commentaire
 * @version 1.00
 * @since 27/05/2009 Anthony Terrien <terrien@benchmark.fr> Conversion classe
 */

if(typeof(benchmark) == "undefined") { var benchmark = new Object(); }
if(typeof(benchmark.application) == "undefined") { benchmark.application = new Object(); }
if(typeof(benchmark.application.commentaire) == "undefined") { benchmark.application.commentaire = new Object(); }

/**
 * constructeur :
 * @return void
 */
benchmark.application.commentaire.ObjGestionFormulaireCommentaire = function(){

	/**
	* @since 23/06/09 Anthony Terrien <terrien@benchmark.fr>
	* redéclaré ici car cet objet hérite de l'eventDispatcher et sans celà la liste reste mutualisée entre les instances
	* cf eventDispatcher.js pour de plus amples explications
	*/
	this._listeEvenenement = {};

	/* Configuration du popup lors de la dépose de commentaire par popup */
	this.configurationPopup = {
		fermetureMasqueSurClic	: false,
		fermetureAfficheBouton	: true,
		ouvertureAvecAnimation	: false,
		fermetureSurClic		: false,
		masquerFlash			: false,
		hauteur 				: 350,
		largeur					: 550
	};

    this.MODE_DEFAUT = 'MODE_DEFAUT';
    this.MODE_MARQUEUR = 'MODE_MARQUEUR';
    this.MODE_OBJPOPUP = 'MODE_OBJPOPUP';

    this.EVT_ERREUR = 'EVT_ERREUR';
    this.EVT_SUCCES = 'EVT_SUCCES';

	/**
	* Permet de conserver le mode de traitement
	*/
    this.mode = this.MODE_DEFAUT ;

	/**
	* initialisation
	* @return void
	*/
	this.initialise = function(){
		this.bindActions();
	};

	/**
	* Applique les binds sur les éléments nécéssaires
	* @return void
	*/
	this.bindActions = function(){

    	$("#commentaire_submit").unbind().bind(
    	    'click',
    	    {self:this},
    	    function(e){
    		    e.data.self.validerFormulaire( $(this), e);
    		    return false;
    	    }
    	);

    	$(".ofcc_versmarqueurhtml").unbind().bind(
    	    'click',
    	    {self:this},
    	    function(e){
    	        e.data.self.mode = e.data.self.MODE_MARQUEUR;
    		    e.data.self.validerFormulaire( $(this), e);
    		    return false;
    	    }
    	);

    	$(".ofcc_versobjpopup").unbind().bind(
            'click',
            {self:this},
            function(e){
                e.data.self.mode = e.data.self.MODE_OBJPOPUP;
                e.data.self.validerFormulaire( $(this), e);
                return false;
            }
    	);

		$("a.supprimer_commentaire").unbind().bind(
			'click',
			{self:this},
			function(e){
				e.data.self.supprimerCommentaire($(this), e);
				return false;
			}
		);

		$("a.restaurer_commentaire").unbind().bind(
			'click',
			{self:this},
			function(e){
				e.data.self.restaurerCommentaire($(this), e);
				return false;
			}
		);

		/* On rebind les actions "lire la suite" */
		if(typeof(benchmark.framework.ihm.util) != 'undefined'){
			if(typeof(benchmark.framework.ihm.util.ObjLireLaSuite) != 'undefined'){
				var objLireLaSuite = new benchmark.framework.ihm.util.ObjLireLaSuite();
				objLireLaSuite.initialise();
			}
		}
	};

	/**
	* Centralise l'appel au gestionnaire de formulaires
	* @return void
	*/
    this.validerFormulaire = function( elementsource, pEvent){

        // On ne fait rien si le marqueur est absent en mode_marqueur
        if( pEvent.data.self.mode == pEvent.data.self.MODE_MARQUEUR ){
            if( $("#commentaire_formulaire").length == 0 ){
                throw 'Le marqueur #commentaire_formulaire n\'est pas présent sur la page.';
                return false;
            }
        }

        // On attrape l'url AJAX de l'element
    	monurl = elementsource.attr('f_ajax');

        // On détermine la fonction à appeler en fonction du mode
        if( pEvent.data.self.mode == pEvent.data.self.MODE_OBJPOPUP ){
            func = this.traiteRetourActionFormulaireCommentaireObjPopup ;
        }else{
            func = this.traiteRetourActionFormulaireCommentaire ;
        }

    	benchmark.framework.net.ObjControleurAjax3.appelScriptAction(
    		elementsource,
    		monurl,
    		{
    			SUCCES: benchmark.framework.util.delegate( this, func ),
    			COMPLET: ['DEFAUT'],
    			AVANT_ENVOI: benchmark.framework.util.delegate( this, this.handlerEvtAvant_envoi),
    			ERREUR: 'DEFAUT'
    		},
    		benchmark.framework.util.form.getFormulaireDonneeJson('#formulairecommentaire',true)
    	);
    };

    this.traiteRetourActionFormulaireCommentaireObjPopup = function( pEvent ) {

        if(typeof(benchmark.execution) == "undefined") { benchmark.execution = new Object(); }
		benchmark.execution.objPopup = new benchmark.framework.ihm.ObjPopup();
		benchmark.execution.objPopup.ouvreHtml(
			"<div class='commentaire_formulaire' id='commentaire_formulaire'>" + pEvent.json.message_retour + "</div>",
			this.configurationPopup
		);
        this.traiteRetourActionFormulaireCommentaire( pEvent );
    }

    this.traiteRetourActionFormulaireCommentaire = function( pEvent ) {

        // On rétablit le curseur
    	$(pEvent.currentTarget).css('cursor','pointer');
    	$('body').css('cursor','auto');

    	// On teste le retour de l'action
    	if(pEvent.json.code_retour == "0"){
    		// L'action a échoué
			var evenement = new benchmark.framework.util.Event(benchmark.application.commentaire.ObjGestionFormulaireCommentaire.EVT_ERREUR);
			evenement.donnees = pEvent.json;
    		this.dispatchEvent(evenement);
    	}else if(pEvent.json.evt == "1"){
    		// Succès
			var evenement = new benchmark.framework.util.Event(benchmark.application.commentaire.ObjGestionFormulaireCommentaire.EVT_SUCCES);
			evenement.donnees = pEvent.json;
    		this.dispatchEvent(evenement);
	    }

    	$("#commentaire_formulaire").empty();
    	$("#commentaire_formulaire").append(pEvent.json.message_retour);

		if( this.mode == this.MODE_OBJPOPUP ){
			// On recentre ObjPopUp à chaque fois
			benchmark.execution.objPopup.centre();
		}

    	// on recharge l'écouteur sur le bouton "valider"
    	this.initialise();

		if( this.mode == this.MODE_OBJPOPUP ){
			$(".ofcc_modifier").unbind().bind(
				'click',
				{self:this},
				function(e){
					e.data.self.mode = e.data.self.MODE_OBJPOPUP;
					e.data.self.validerFormulaire( $(this), e );
					return false;
				}
			);

			$(".popup_fermer").unbind().bind(
				'click',
				{self:this},
				function(e){
					e.data.self.mode = e.data.self.MODE_OBJPOPUP;
					benchmark.execution.objPopup.ferme();
					return false;
				}
			);
		}

    	// on recharge l'initialisation des etoiles de notation
    	benchmark.execution.objScore.initialise("#commentaire_formulaire");
    }


    /**
     * Surcharge la fonction du même nom de l'ObjControleurAjax3
     * Handler par défaut pour l'événement AVANT_ENVOI
     * @param benchmark.framework.util.Event pEvent Instance de l'événement de la requête Ajax courante
     */
    this.handlerEvtAvant_envoi = function(pEvent){
    	// Affichage du sablier à côté de la souris
        $(pEvent.currentTarget).css('cursor','progress');
        $('body').css('cursor','progress');
    };

    /**
     * Fonction d'affichage d'une icone d'attente sur un lien
     * @param object element L'objet jquery définissant le lien
     */
    this.debutAttente = function(element){
		/* On affiche un sablier en lieu et place de l'élément que l'on rend invisible */
		if(typeof(element.findPos) == 'function'){
			var coords = element.findPos();
			$('body').append('<img class="ajax_icone_chargement" style="float: left; z-index: 1000; position: absolute; top :'+(coords.y)+'px; left :'+(coords.x)+'px;" src="/framework/lib/js/image/chargement.gif"/>');
			element.css('visibility', 'hidden');
		}
    };

    /**
     * Fonction de suppression de l'icone d'attente sur un lien
     * @param object element L'objet jquery définissant le lien
     */
    this.finAttente = function(element){
		$('img.ajax_icone_chargement').remove();
		element.css('visibility', 'visible');
    };

	/**
	 * Fonction appelée lors d'un clic sur un lien de suppression de commentaire
	 * @return void
	 */
    this.supprimerCommentaire = function(elementsource, pEvent){
    	var self = this;

    	/* On récupère l'url ajax a appeler */
    	var f_url_ajax = elementsource.attr('f_url_ajax');

    	if(typeof(f_url_ajax) != 'undefined' && f_url_ajax != ''){
			benchmark.framework.net.ObjControleurAjax3.appelScriptAction(
				elementsource,
				f_url_ajax,
				{
					'SUCCES': function(pEvent){
					self.finAttente(elementsource);
						if(pEvent.json.code_retour == 1){
							var div_commentaire = $('#commentaire_'+pEvent.json.id_commentaire);
							var div_commentaire_supprime = $('#commentaire_supprime_'+pEvent.json.id_commentaire);

							var taille = div_commentaire.height();

							div_commentaire.hide();
							div_commentaire_supprime.show();
							div_commentaire_supprime.height(taille - 2);
						}else{
							benchmark.framework.ihm.popup.ObjPopupFabrique.creerPopUpInformation(
								'Impossible de supprimer ce commentaire.'
							);
						}
					},
					'ERREUR': function(){
						self.finAttente(elementsource);
						benchmark.framework.ihm.popup.ObjPopupFabrique.creerPopUpInformation(
							'Impossible de supprimer ce commentaire.'
						);
					},
	    			'AVANT_ENVOI': function(pEvent){
						self.debutAttente(elementsource);
					}
				}
			);
    	}
    };

	/**
	 * Fonction appelée lors de la restauration d'un commentaire supprimé
	 * @return void
	 */
    this.restaurerCommentaire = function(elementsource, pEvent){
    	var self = this;

    	/* On récupère l'url ajax a appeler */
    	var f_url_ajax = elementsource.attr('f_url_ajax');
    	if(typeof(f_url_ajax) != 'undefined' && f_url_ajax != ''){
			benchmark.framework.net.ObjControleurAjax3.appelScriptAction(
				elementsource,
				f_url_ajax,
				{
					'SUCCES': function(pEvent){
						self.finAttente(elementsource);
						if(pEvent.json.code_retour == 1){
							$('#commentaire_'+pEvent.json.id_commentaire).show();
							$('#commentaire_supprime_'+pEvent.json.id_commentaire).hide();
						}else{
							benchmark.framework.ihm.popup.ObjPopupFabrique.creerPopUpInformation(
								'Impossible de restaurer ce commentaire.'
							);
						}
					},
					'ERREUR': function(){
						self.finAttente(elementsource);
						benchmark.framework.ihm.popup.ObjPopupFabrique.creerPopUpInformation(
							'Impossible de restaurer ce commentaire.'
						);
					},
	    			'AVANT_ENVOI': function(pEvent){
						self.debutAttente(elementsource);
					}
				}
			);
    	}
    };
}

benchmark.application.commentaire.ObjGestionFormulaireCommentaire.prototype = new benchmark.framework.util.EventDispatcher;

<!--
/**
* pour l'instant l'instanciation est automatique :
*/
$(document).ready(
	function(){
		if(typeof(benchmark.execution) == "undefined") { benchmark.execution = new Object(); }
		benchmark.execution.objGestionFormulaireCommentaire = new benchmark.application.commentaire.ObjGestionFormulaireCommentaire();
		benchmark.execution.objGestionFormulaireCommentaire.initialise();

		// Exemple de listener
    	/*benchmark.execution.objGestionFormulaireCommentaire.addEventListener(
    	        benchmark.application.commentaire.ObjGestionFormulaireCommentaire.EVT_SUCCES,
    	        function(){ alert('Succes'); }
    	        );*/
	}
);
//-->
