$(document).ready(function () {
	/* 2011 - conditions générales d'utilisation */
	$("#cgu").colorbox({inline:true,width:"500px",height:"500px",opacity:"0.5",close:"Fermer",href:"#modalCharte"});

    /* Validation de formulaires */
    jQuery.validator.setDefaults({
        errorLabelContainer: ".error",
        wrapper: "span"
    });;

    /* Validation Inscription des anciens membres non inscrits sur le forum */
    $("#formInscForum").validate({
        rules: {
            login: "required",
            pwd: "required",
            cg: "required"
        },
        messages: {
            email: {
                required: "L'email est obligatoire.",
                email: "L'email saisi n'est pas valide."
            },
            login: "Le pseudo est obligatoire.",
            pwd: "Le mot de passe est obligatoire.",
            cg: "Veuillez cocher la case pour accepter les conditions générales d'utilisation."
        }
    });

    /* Validation Login anciens membres du site */
    $("#formLoginForum").validate({
        errorLabelContainer: ".loginError",
        rules: {
            login: "required",
            pwd: "required"
        },
        messages: {
            login: "Le pseudo est obligatoire.",
            pwd: "Le mot de passe est obligatoire."
        }
    });


	
    /* Validation Login */
    $("#formLogin").validate({
        rules: {
            pseudo: "required",
            pwd: "required"
        },
        messages: {
            pseudo: "Le pseudo est obligatoire.",
            pwd: "Le mot de passe est obligatoire."
        }
    });

	/* Validation Réponse au sondage */
/*  var v = jQuery(".radioSondage").click(function (e) {
        var form = $("#sondage");
            doLogin(form);
            return false;
    });
*/

    /* Validation formulaire
    $("#formComment").submit(function(){
        if (!validateComment("#formComment","#txtComment")) {
            return false;
        }
    }); */

    /* Ajout d'un commentaire : si non loggué, on affiche la popup de login
    $(".postComment").click(function (e) {
        var form = $("#formComment");
        if (!validateComment(form.selector,"#txtComment")) {
            return false;
        }
        else {
            $(".error").html(msgError).fadeOut(200);
            //$(".postComment").colorbox({width:"400px",opacity:"0.5",href:"/blog/login.php",close:"Fermer",scrolling:false},function(){
            doLogin(form);
            return false;
        }
    });  */

    /* Edition in place d'un commentaire */
    $(".cancelEditComment").bind("click", function(event){
        var form = $(this).parents("form");
       /* $("#"+form.attr("id")).fadeOut(50);*/
	   /* MB */
	   $("#"+form.attr("id")).hide();
	   /* /MB */
        var id = $("#"+form.attr("id")+" .editPostId").val();
        /*$("#comment_"+id+" .commentMsg").show("normal");*/
		$("#comment_"+id+" .commentMsg").show();
    });
    $(".editComment").bind("click", function(event){
        var form = $(this).parents("form");
        if (!validateComment("#"+form.attr("id"),".txtEditComment")) {
            return false;
        }
        else {
            $.ajax({
                url: '/focus/process.php',
                data: $("#"+form.attr("id")).serialize(),
                type: 'post',
                cache: false,
                dataType: 'html',
                success: function (data) {
                    if(data == "error") {
                        var msgError = "Le commentaire n'a pas pu être modifié ; merci d'essayer à nouveau.";
                        $("#"+form.attr("id")+" .error").html(msgError).fadeIn(200);
                    }
                    else {
                       /* $("#"+form.attr("id")).fadeOut(50);*/
					    /* MB */
					  $("#"+form.attr("id")).hide();
					   /* /MB */
                        var id = $("#"+form.attr("id")+" .editPostId").val();
                        /*$("#comment_"+id+" .commentMsg").html(data).show("normal");*/
						$("#comment_"+id+" .commentMsg").html(data).show();
                    }
                }
            });
            return false;
        }
    });
});

var msgError = "";

/* Validation réponse au sondage */
function click_sondage(formId) {    
    var form = $("#" + formId);
        doLogin(form, "", "");
}

/* Validation formulaire Ajout de commentaire */
function validateComment(form, selector) {
    var comment = $(form+" "+selector);
    if (!comment.val()) {
        msgError = "Le commentaire est vide. Merci de saisir votre commentaire.";
        $(form+" .error").html(msgError).fadeIn(200);
        return false;
    }
    else {
        return true;
    }
}

/* Edition d'un commentaire */
function editComment(id) {
    var commentMsg  = $("#comment_"+id+" .commentMsg");
	var formEdit    = $("#formEditComment_"+id);    	
	commentMsg.fadeOut(50, function() {
        /*formEdit.show("normal");*/
		formEdit.show();
    });	
    return false;
}

/* Citation d'un commentaire */
function citerComment(id, position, id_auteur, idUser) {

	// var commentMsg  = $("#comment_"+id+" .commentMsg");
	var commentMsg  = $("#formEditComment_"+id+" .txtEditComment");
	var contenu = commentMsg.html();
	
/*	if (idUser == 0) 
	{doLogin("", function doCitation(id) {
		var url = window.location.href;
        window.location.href = url;
			
		document.formComment.txtComment.value += "[quote]";
		document.formComment.txtComment.value += contenu;
		document.formComment.txtComment.value += "[/quote]";		
		});
	}
	else
	{
*/
		document.formComment.txtComment.value += "[quotemsg="+id+","+position+","+id_auteur+"]";
		document.formComment.txtComment.value += contenu;
		document.formComment.txtComment.value += "[/quotemsg]";
//	}
    return false;
}

/* Supprimer une réponse - MB */
function supprimerComment(DeleteComment, idTopic, idResponse, catid) {
        $.ajax({
            url: '/focus/process.php',
            data: ({ DeleteComment: DeleteComment, topic_id: idTopic, responseid: idResponse, catid : catid }),
            type: 'post',
            cache: false,
            dataType: 'html',
            success: function (data) {
                if(data == "error") {
                    var msgError = "Le vote n'a pas pu être pris en compte ; merci d'essayer à nouveau.";
                    $("#comment_"+idResponse+" span.error").html(msgError).fadeIn(200);
                }
				else {
					location.reload(true);
                }               
            }
        });
    return false;
}

/* Vote positif sur une réponse */
function addVotePositif(votePositif, idTopic, idResponse, idUser, catid) {
    if (idUser == 0) {
         doLogin("",function doVote(id) {
            //$.get("/blog/lire.php", { vote: vote, blogid: idTopic, responseid: idResponse, userid: id })
            $.ajax({
                url: '/focus/process.php',
                data: ({ votePositif: votePositif, blogid: idTopic, responseid: idResponse, userid: id, catid : catid }),
                type: 'post',
                cache: false,
                dataType: 'html',
                success: function (data) {
                    if(data == "error") {
                        /*var url = window.location.href;
                        $(document).load(url, function(){
                            var msgError = "Le vote n'a pas pu être pris en compte ; merci d'essayer à nouveau.";
                            $("#comment_"+idResponse+" span.error").html(msgError).fadeIn(200);
                            }
                        );*/
                        /*var msgError = "Le vote n'a pas pu être pris en compte ; merci d'essayer à nouveau.";
                        $("#comment_"+idResponse+" span.error").html(msgError).fadeIn(200, function() {
                            window.setTimeout("location.reload(true)", 1000);
                        });*/
                        var url = window.location.href+"/"+idResponse;
                        window.location.href = url;
                    }
                    else {
                        $("#actions_"+idResponse+" .commentRatingPositif").fadeOut(10, function() {
							$("#actions_"+idResponse+" .commentRatingPositif").html(data).fadeIn(10, function() {
                                    location.reload(true);
									document.getElementById("voteUp_"+idResponse).onclick = '';
									document.getElementById("voteDown_"+idResponse).onclick = '';

                                });
                            });
                       // });
                    }
                }
            });
            return false;
         },"");
    }
    else {
        $.ajax({
            url: '/focus/process.php',
            data: ({ votePositif: votePositif, blogid: idTopic, responseid: idResponse, userid: idUser, catid : catid  }),
            type: 'post',
            cache: false,
            dataType: 'html',
            success: function (data) {
                if(data == "error") {
                    var msgError = "Le vote n'a pas pu être pris en compte ; merci d'essayer à nouveau.";
                    $("#comment_"+idResponse+" span.error").html(msgError).fadeIn(200);
                }
                else {
                    //$("#comment_rating_"+idResponse).html(data).show("normal");
                    $("#actions_"+idResponse+" .commentRatingPositif").fadeOut(10, function() {
                            $("#actions_"+idResponse+" .commentRatingPositif").html(data).fadeIn(10);
							document.getElementById("voteUp_"+idResponse).onclick = '';
							document.getElementById("voteDown_"+idResponse).onclick = '';
                       // });
                    });
                }
            }
        });
        return false;
    }
    return false;
}


/* Vote négatif sur une réponse */
function addVoteNegatif(voteNegatif, idTopic, idResponse, idUser, catid) {
    if (idUser == 0) {
         doLogin("",function doVote(id) {
            //$.get("/blog/lire.php", { vote: vote, blogid: idTopic, responseid: idResponse, userid: id })
            $.ajax({
                url: '/focus/process.php',
                data: ({ voteNegatif: voteNegatif, blogid: idTopic, responseid: idResponse, userid: id, catid : catid }),
                type: 'post',
                cache: false,
                dataType: 'html',
                success: function (data) {
                    if(data == "error") {
                        /*var url = window.location.href;
                        $(document).load(url, function(){
                            var msgError = "Le vote n'a pas pu être pris en compte ; merci d'essayer à nouveau.";
                            $("#comment_"+idResponse+" span.error").html(msgError).fadeIn(200);
                            }
                        );*/
                        /*var msgError = "Le vote n'a pas pu être pris en compte ; merci d'essayer à nouveau.";
                        $("#comment_"+idResponse+" span.error").html(msgError).fadeIn(200, function() {
                            window.setTimeout("location.reload(true)", 1000);
                        });*/
                        var url = window.location.href+"/"+idResponse;
                        window.location.href = url;
                    }
                    else {
                        $("#actions_"+idResponse+" .commentRatingNegatif").fadeOut(10, function() {
                      //      $("#actions_"+idResponse+" .loading").fadeIn(400);
                       //     $("#actions_"+idResponse+" .loading").fadeOut(10, function() {
                                $("#actions_"+idResponse+" .commentRatingNegatif").html(data).fadeIn(10, function() {
                                    location.reload(true);
									document.getElementById("voteUp_"+idResponse).onclick = '';
									document.getElementById("voteDown_"+idResponse).onclick = '';

                                });
                            });
                       // });
                    }
                }
            });
            return false;
         },"");
    }
    else {
        $.ajax({
            url: '/focus/process.php',
            data: ({ voteNegatif: voteNegatif, blogid: idTopic, responseid: idResponse, userid: idUser, catid : catid  }),
            type: 'post',
            cache: false,
            dataType: 'html',
            success: function (data) {
                if(data == "error") {
                    var msgError = "Le vote n'a pas pu être pris en compte ; merci d'essayer à nouveau.";
                    $("#comment_"+idResponse+" span.error").html(msgError).fadeIn(200);
                }
                else {
                    //$("#comment_rating_"+idResponse).html(data).show("normal");
                    $("#actions_"+idResponse+" .commentRatingNegatif").fadeOut(10, function() {
                    //    $("#actions_"+idResponse+" .loading").fadeIn(400);
                    //    $("#actions_"+idResponse+" .loading").fadeOut(10, function() {
                            $("#actions_"+idResponse+" .commentRatingNegatif").html(data).fadeIn(10);
							document.getElementById("voteUp_"+idResponse).onclick = '';
							document.getElementById("voteDown_"+idResponse).onclick = '';
                       // });
                    });
                }
            }
        });
        return false;
    }
    return false;
}

/* Popup de login */
function doLogin(form, callback, redirection) {

	// chargement de la page popupLogin + la fonction... 
    $.get("/membres/popupLogin.php", function(data){
    
		// si l'utilisateur est loggué
        if (data == "logged") 
		{
            form.submit();
		}
		// sinon on affiche la pop-up
        else {
            $.fn.colorbox({open:true,width:"400px",opacity:"0.5",href:"/membres/popupLogin.php?formReferer="+form.name,close:"Fermer",scrolling:false},function(){
                $('.loginSend').click(function (e) {
					// chargement de la page popupLogin + retour : succès | échec
                    $.ajax({
                        url: '/membres/popupLogin.php',
                        data: $('#modalLogin form').serialize() + '&action=send',
                        type: 'post',
                        cache: false,
                        dataType: 'text',
                        success: function (data) {
                            if (data != "") {
                                $('#modalLogin form').fadeOut(50);
                                if($(".msg").hasClass("error")) $(".msg").removeClass("error");
                                $(".msg").html("Vous êtes connecté ...");
                                $('#cboxLoadingOverlay').fadeIn(1500, function() {
                                    $.fn.colorbox.close();
                                    if (form != "") {
                                        form.submit();
                                    }
                                    else if ($.isFunction(callback)) {
                                       callback(data);
                                    }
									else if (redirection != "") {
										document.location.href=redirection;
									} 
									/* on s'inscrit depuis le lien du bloc de droite */
									else {
										location.reload(true);
									}
                                });
                                /*if (form != "")
                                    form.submit();
                                else
                                    location.reload(true);*/
                            }
                            else {
                                if(!$(".msg").hasClass("error")) $(".msg").addClass("error");
                                $(".msg").html("Le nom d'utilisateur ou le mot de passe est incorrect.");
                            }
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            //inspect xhr.responseText, thrownError variables to find out what is the exact error.
                            //Once we know the exact error, it could be debugged further.
                        }
                    });
                    return false;
                });
            });
        }
    });
    //return false;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////
// pop-up inscription //
///////////////////////

/* MB : clic du lien allant vers la pop-up inscription */
function click_inscription(form) { 
	var form = document.getElementById(form);
	doInscription(form, "");
}

 /* MB : Validation Inscription  */
/*$("#formInscription").validate({
	rules: {
		pseudo: "required",
		pwd: "required",
		cg: "required"
	},
	messages: {
		email: {
			required: "L'email est obligatoire.",
			email: "L'email saisi n'est pas valide."
		},
		login: "Le pseudo est obligatoire.",
		pwd: "Le mot de passe est obligatoire.",
		cg: "Veuillez cocher la case pour accepter les conditions générales d'utilisation."
	}
});
*/
	
// Popup d'inscription 
// étape 1 : inscription
// étape 2 : login 
// étape 3 : submit du message
function doInscription(form,callback) {
	// chargement de la page popupInscription + la fonction... 
    $.fn.colorbox({open:true,width:"500px",opacity:"0.5",href:"/membres/popupInscription.php",close:"Fermer",scrolling:false},function(){
		$('.InscriptionSend').click(function (e) {
			// chargement de la page popupInscription + retour : succès | échec
			$.ajax({
				url: '/membres/popupInscription.php',
				data: $('#formInscription').serialize() + '&action=send',
				type: 'post',
				cache: false,
				dataType: 'text',
				success: function (data) {
					// succès <=> on a le message 'ok' renvoyé depuis la pop-up inscription
					if (data == "ok") {
						$('#modalInscription form').fadeOut(50);
						if($(".msg").hasClass("error")) $(".msg").removeClass("error");
						$(".msg").html("Vous êtes inscrit et connecté ...");
						$('#cboxLoadingOverlay').fadeIn(2000, function() {
							$.fn.colorbox.close();
							
							if (form != "") {
								form.submit();
							}
							else if ($.isFunction(callback)) {
								callback(data);
							}
							/* on s'inscrit depuis le lien du bloc de droite */
							else {
								location.reload(true);
							}
						});
						
					}
					// échec <=> la pop-up inscription a renvoyé des messages d'erreurs
					else if (data == "vide"){
						if(!$(".msg").hasClass("error")) $(".msg").addClass("error");
						$(".msg").html("Tous les champs obligatoires ne sont pas renseignés.");
					}
					else if (data == "pseudo"){
						if(!$(".msg").hasClass("error")) $(".msg").addClass("error");
						$(".msg").html("Un compte existe déjà avec ce pseudo. Merci d'en choisir un autre.");
					}
					else if (data == "email"){
						if(!$(".msg").hasClass("error")) $(".msg").addClass("error");
						$(".msg").html("Un compte existe déjà avec cet email. Merci d'en choisir un autre.");
					}
					else if (data == "erreur"){
						if(!$(".msg").hasClass("error")) $(".msg").addClass("error");
						$(".msg").html("Erreur.");
					}
				},
				error: function (xhr, ajaxOptions, thrownError) {
					//inspect xhr.responseText, thrownError variables to find out what is the exact error.
					//Once we know the exact error, it could be debugged further.
				}
			});
			return false;
		});
	});
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


