/* ------------------------ CONSTANTES ------------------------ */
// Nombre total de commentaire
var totalNbrComments = 0;

// Nombre de commentaire affichés par défaut
var defaultNbrCommentsShown = 3;

// Nombre de commentaire à retirer/ajouter
var nbrCommentToAddAndRemove = 5;

// Vitesse de l'effet cacher/montrer
var speedEffect = 500;

// Vitesse à laquelle on scroll aux commentaires
var scrollSpeed = 500;

// Effet avec lequel on scroll aux commentaires
var scrollEffect = "swing";

// Nombre de commentaire en train d'être affiché
var nbrCommentShowing = 0;

// Nombre de commentaire en train d'être caché
var nbrCommentHiding = 0;

// Commentaire auquel scroller
var commentObjectToScrollTo = "";

// Vitesse à laquelle le message apparaît
var speedshowMsgForCommentForm = 1000;

// Effet avec lequel le message apparaît
var effectshowMsgForCommentForm = "easeOutBounce";

// Temps avant de faire disparaitre le message
var timeBeforeHideMsgForCommentForm = 2000;

// Vitesse à laquelle faire disparaitre le message
var speedHideMsgForCommentForm = 250;

// Effet avec lequel faire disparaitre le message
var effectHideMsgForCommentForm = "easeInExpo";


/* ------------------------ INIT ------------------------ */
$(document).ready(function(){
	// On affiche que le nombre de commentaire par défaut
	setCommentsShownToDefaut();
	
	// On défini le click sur le nombre de commentaire
	setClickOnCommentNbrTotal();
	
	// On défini les événements de formulaire
	setEventsOnForm();
});

/* ------------------------ EVENEMENTS ------------------------ */
// Début d'affichage d'un commentaire
$(document).bind("startShowComment", function(e){
	nbrCommentShowing++;

	if(nbrCommentShowing == 1)
		commentObjectToScrollTo = e.target;
});

// Fin d'affichage d'un commentaire
$(document).bind("endShowComment", function(){
	nbrCommentShowing = nbrCommentShowing-1;

	if (nbrCommentShowing == 0) {
		// On scroll jusqu'au premier nouveau commentaire si on a affiché plus de commentaire que par défaut
		if($(".commentlist > LI:visible").length > defaultNbrCommentsShown)
			scrollToComment(commentObjectToScrollTo);
		
		// On annonce qu'on a terminé de mettre à jour les commentaire
		$(document).trigger("endUpdateComment");
	}
});

// Début de cachage d'un commentaire
$(document).bind("startHideComment", function(e){
	nbrCommentHiding++;
});

// Fin de cachage d'un commentaire
$(document).bind("endHideComment", function(){
	nbrCommentHiding = nbrCommentHiding-1;

	if (nbrCommentHiding == 0) {
		// On annonce qu'on a terminé de mettre à jour les commentaire
		$(document).trigger("endUpdateComment");
	}
});

// Fin de mise à jour des commentaires
$(document).bind("endUpdateComment", function(){
	// On affiche les liens
	refreshMoreAndLessLinks();
});

// Soumission du formulaire d'envoi de commentaire
$(document).bind("submitNewComment", function(){
	submitNewComment();
});

// Début de l'envoi de nouveau commentaire
$(document).bind("startNewCommentSubmission", function(){
	// On cache le btn envoyer
	$(".btnSubmitComment").hide();	

	// On met le gif indiquant le chargement à la place du bouton envoyer
	$(".submitCommentInProgress").show();
});

// Fin de l'envoi de nouveau commentaire
$(document).bind("endNewCommentSubmission", function(){
	// On va récupérer les commentaires
	getHTMLComments();
		
	// On MAJ le nombre de commentaires total
	getNbrComments();
});


$(document).bind("endCommentsUpdate", function(){
	// On affiche que le nombre de commentaire par défaut
	setCommentsShownToDefaut();
	
	// On vide le formulaire
	$("#formulaire_comment > TEXTAREA").val("");
	
	// On cache le gif
	$(".submitCommentInProgress").hide();	

	// On montre le bouton envoyer
	$(".btnSubmitComment").show();
})

/* ------------------------ FONCTIONS ------------------------ */

function setCommentsShownToDefaut(){
	// On ajout la class "shownComment" à tous les commentaire
	$(".commentlist > LI:visible").addClass("shownComment");
	
	// On affiche le nombre de commentaire par défaut
	setNumberCommentsShown(defaultNbrCommentsShown, true);
}

/**
 * Cette fonction affiche ou cache suffisament de commentaire pour correspondre au nombre demandé
 * 
 * @param {Object} iNbrToShow Nombre de commentaire à afficher
 * @param {Object} bNoEffect Si vrai, les commentaires ne s'afficheront pas avec effet
 */
function setNumberCommentsShown(iNbrToShow, bNoEffect){
	totalNbrComments = 0;
	iShown = 0;

	// On boucle sur les commentaires
	$(".commentlist > LI").each(function(){
		totalNbrComments++;

		// Si on a moins de commentaire que demandé, on l'affiche
		if(iShown < iNbrToShow){
			showComment(this, bNoEffect);
			
			iShown++;
		}
		// S'il y en a plus que demandé, on le cache
		else {
			hideComment(this, bNoEffect);
		}
	});
}

/**
 * Cette fonction affiche un commentaire
 * 
 * @param {Object} commentObject Objet que l'on doit afficher
 * @param {Boolean} bNoEffect Si vrai, aucun effet ne sera appliqué
 */
function showComment(commentObject, bNoEffect){
	
	// Si le commentaire est déjà affiché, on ne fait rien
	if (!$(commentObject).hasClass("shownComment")) {
		// On met la bonne classe
		$(commentObject).addClass("shownComment");
		$(commentObject).removeClass("hiddenComment");

		// On annonce qu'on démarre l'affichage du commentaire
		$(commentObject).trigger("startShowComment");		
		
		if (bNoEffect) {
			$(commentObject).css({
				"display": "block"
			});
			// On annonce qu'on a terminé l'affichage du commentaire
			$(commentObject).trigger("endShowComment");
		}
		else {			
			$(commentObject).slideDown(speedEffect, function(){
				// On annonce qu'on a terminé l'affichage du commentaire
				$(commentObject).trigger("endShowComment");
			});
		}
	}
}

/**
 * Cette fonction cache un commentaire
 * 
 * @param {Object} commentObject Objet que l'on doit cacher
 * @param {Boolean} bNoEffect Si vrai, aucun effet ne sera appliqué
 */
function hideComment(commentObject, bNoEffect){
	// Si le commentaire a déjà été affiché, on lui retire la classe correspondante
	if ($(commentObject).hasClass("shownComment")) {
		$(commentObject).removeClass("shownComment");
	}	

	// On lui ajoute la classe de commentaire caché
	$(commentObject).addClass("hiddenComment");

	// On annonce qu'on démarre le cachage du commentaire
	$(commentObject).trigger("startHideComment");

	// On le cache
	if(bNoEffect){
		$(commentObject).css({
			"display": "none"
		});

		// On annonce qu'on a terminé le cachage du commentaire
		$(commentObject).trigger("endHideComment");
	}
	else{
		$(commentObject).slideUp(speedEffect, function(){
			// On annonce qu'on a terminé le cachage du commentaire
			$(commentObject).trigger("endHideComment");
		});
	}
}

/**
 * Cette fonction met à jour les liens d'affichage de commentaires
 */
function refreshMoreAndLessLinks(){
	// On vide la div
	$("#more_and_less_links").html("");

	// S'il y a plus de commentaires au total que ceux affiché, on met un lien pour en afficher en plus
	if($(".commentlist > LI:visible").length < totalNbrComments){
		// Nombre de commentaire à ajouter
		nbrCommentAAjouter = Math.min(nbrCommentToAddAndRemove, totalNbrComments-$(".commentlist > LI:visible").length);

		$("#more_and_less_links").append("<div id='more_comments_link'>Afficher plus</div>");
	}

	// S'il y a plus de commentaires affichés que par défaut, on met un lien pour en afficher moins
	if($(".commentlist > LI:visible").length > defaultNbrCommentsShown){
		// Nombre de commentaire à retirer
		nbrCommentARetirer = Math.min(nbrCommentToAddAndRemove, $(".commentlist > LI:visible").length-defaultNbrCommentsShown);
		
		$("#more_and_less_links").append("<div id='less_comments_link'>Afficher moins</div>");
	}

	// On associe les evenements
	if ($("#more_comments_link").length > 0) {
		// Click
		$("#more_comments_link").click(function(){
			setNumberCommentsShown($(".commentlist > LI:visible").length + nbrCommentAAjouter, false);
		});
		
		// Over
		$("#more_comments_link").mouseover(function(){
			$("#more_comments_link").addClass("over");
		});
		
		// Out
		$("#more_comments_link").mouseout(function(){
			$("#more_comments_link").removeClass("over");
		});	
	}
			
	if ($("#less_comments_link").length > 0) {
		// Click
		$("#less_comments_link").click(function(){
			setNumberCommentsShown($(".commentlist > LI:visible").length - nbrCommentARetirer, false);
		});
		
		
		// Over
		$("#less_comments_link").mouseover(function(){
			$("#less_comments_link").addClass("over");
		});
		
		// Out
		$("#less_comments_link").mouseout(function(){
			$("#less_comments_link").removeClass("over");
		});	
	}
}

/**
 * Cette fonction recardre la fenetre sur les commentaires
 * 
 * @param {Object} commentObject Objet DOM du commentaire sur lequel scroller
 */
function scrollToComment(commentObject){

	// On determine la position du commentaire précédent
	commentPositionTop = $(commentObject).prev().offset().top;

	$('html,body').animate({
		scrollTop: commentPositionTop
		}, scrollSpeed, scrollEffect, "");
}

/**
 * Cette fonction défini le click sur le nombre de commentaire total
 */
function setClickOnCommentNbrTotal(){
	$(".countComment").click(function(){
		nbrTotalComment = $(".countComment").html();
		
		if($(".commentlist > LI:visible").length < nbrTotalComment)
			setNumberCommentsShown(nbrTotalComment, false);
		else if($(".commentlist > LI:visible").length == nbrTotalComment)
			setNumberCommentsShown(defaultNbrCommentsShown, false);
	});
}

/**
 * Cette fonction défini les différents événements à emettre selon les actions sur le formulaire
 */
function setEventsOnForm(){
	$("#formulaire_comment").submit(function(){
		return false;
	});

	$("#formulaire_comment").submit(function(){
		$(this).trigger("submitNewComment");
	});	
}

function submitNewComment(){

	dataToSend ={
		'author':$("#inputCommentAuthor").val(),
		'email':$("#inputCommentEmail").val(),
		'url':$("#inputCommentURL").val(),
		'comment':($("#inputCommentMsg").val() != 'undefined' ? $("#inputCommentMsg").val() : ""),
		'submit':$("INPUT[name='submit']").val(),
		'comment_post_ID':$("INPUT[name='comment_post_ID']").val(),
		'comment_parent':$("INPUT[name='comment_parent']").val(),
		'_wp_unfiltered_html_comment':$("INPUT[name='_wp_unfiltered_html_comment']").val()
	};

	// URL à laquelle envoyer les données
	curURLToPost = $("#formulaire_comment").attr("action");

	// On annonce qu'on envoi le commentaire
	$(document).trigger("startNewCommentSubmission");
	
	// On envoi la requête
	$.ajax({
		url:curURLToPost,
		data:dataToSend,
		dataType:'html',
		type:'POST',
		success:function(data){
			$(document).trigger("endNewCommentSubmission");
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			showErrorOnCommentSubmit(XMLHttpRequest.responseText);
		}
	});
}

function showErrorOnCommentSubmit(sError){

	// On recup le message d'erreur de wordpress
	indexOpeningP = sError.indexOf("<p>",0);
	indexClosingP = sError.indexOf("</p>",0);
	sError = sError.substring(indexOpeningP+3, indexClosingP);
	indexDP = sError.indexOf(":",0);
	sError = sError.substr(indexDP+2, sError.length);
		
	showMsgForCommentForm(sError.substr(0,1).toUpperCase()+sError.substr(1,sError.length));
}

function showMsgForCommentForm(sMsg){

	// On défini le texte
	$("#showMsgForCommentForm P").html(sMsg);
	$("#showMsgForCommentForm").css({'display':'block'});

	// On centre le paragraphe
	milieuMsg = $("#showMsgForCommentForm").outerHeight()/2-$("#showMsgForCommentForm P").outerHeight()/2;
	$("#showMsgForCommentForm P").css({
		top:milieuMsg
	})

	// Position du textarea de comment
	textareaTop = $("#formulaire_comment > TEXTAREA").offset().top;
	textareaLeft = $("#formulaire_comment > TEXTAREA").offset().left;

	// Position de départ
	startPosTop = textareaTop;
	startPosLeft = -$("#showMsgForCommentForm").outerWidth();
	startPosTop = -$("#showMsgForCommentForm").outerHeight();
	startPosLeft = textareaLeft;

	$("#showMsgForCommentForm").css({
		top:startPosTop,
		left:startPosLeft
	});

	// On recupere les dimensions de l'element
	showMsgForCommentFormW = $("#showMsgForCommentForm").outerWidth();
	showMsgForCommentFormH = $("#showMsgForCommentForm").outerHeight();

	// Position visible
	visiblePosTop = textareaTop-50;
	visiblePosLeft = textareaLeft-2;

	$("#showMsgForCommentForm").animate({
		top:visiblePosTop,
		left:visiblePosLeft
	}, speedshowMsgForCommentForm, effectshowMsgForCommentForm, function(){
		setTimeout("hideMsgForCommentForm()", timeBeforeHideMsgForCommentForm)
	});
}

function hideMsgForCommentForm()
{
	// On recupere les dimensions de l'element
	showMsgForCommentFormW = $("#showMsgForCommentForm").outerWidth();
	showMsgForCommentFormH = $("#showMsgForCommentForm").outerHeight();

	// On check si on est en jackson ou en kent
	bJackson = $("#showMsgForCommentForm").parent().hasClass("jackson");

	// Position caché
	hiddenPosLeft = bJackson ? -showMsgForCommentFormW : $(document).scrollLeft() + $(window).width()+showMsgForCommentFormW;

	$("#showMsgForCommentForm").animate({
		left:hiddenPosLeft
	}, speedHideMsgForCommentForm, effectHideMsgForCommentForm, function(){
		$("#showMsgForCommentForm").removeClass("error");
		$("#showMsgForCommentForm").removeClass("success");		
		
		$(this).css({'display':'none'});
	
		// On indique que l'update des commentaire est terminé
		$(document).trigger("endCommentsUpdate");
	});
}

/**
 * Cette fonction envoie une requête AJAX pour recup les commentaires
 */
function getHTMLComments(){
	// On annonce qu'on démarre la mise à jour des commentaires
	$(document).trigger("startCommentsUpdate");
	
	// On recupere l'id du post
	curPostId = $("#comment_post_ID").val();
	
	// Url de recup des commentaires
	curURLToPost = $("#comments_ajax_url").val();
	
	// Donnée envoyé
	dataToSend = {'post_id':curPostId};

	// On envoi la requête
	jQuery.post(curURLToPost, dataToSend, function(data){
		setHTMLComments(data);
	},"html");
}

function setHTMLComments(sHTMLComments){
	$("#commentsContainer").html(sHTMLComments);
	
	// On annonce qu'on arrête la mise à jour des commentaires
	$(document).trigger("endCommentsUpdate");
}

/**
 * Cette fonction envoie une requête AJAX pour recup le nombre de commentaires
 */
function getNbrComments(){
	// On annonce qu'on démarre la mise à jour du nombre de commentaires
	$(document).trigger("startNbrCommentsUpdate");
	
	// On recupere l'id du post
	curPostId = $("#comment_post_ID").val();
	
	// Url de recup des commentaires
	curURLToPost = $("#comments_nbr_ajax_url").val();
	
	// Donnée envoyé
	dataToSend = {'post_id':curPostId};

	// On envoi la requête
	jQuery.post(curURLToPost, dataToSend, function(data){
		setNbrComments(data);
	});
}

function setNbrComments(iNbrComment){
	$(".countComment").html(iNbrComment);
	
	// On annonce qu'on arrête la mise à jour des commentaires
	$(document).trigger("NbrCommentsUpdate");
}