/* Setup Ajax */
$.ajaxSetup( { 
  url: "xml.php", 
  type: "POST"
} );

/* SHOUTBOX */
var shoutbox = {

	init: function() {
		$("div.toggle-avatar").hover(function () {
			$(this).children("img").show();
		}, function () {
			$(this).children("img").hide();
		});
		
		if(userID == 0) {
			$('a[href=#add_shout]').requires_login();
		}
	},
	
	post: function() {
		var sbBtn = $("#shoutbox-form input:button");
		var sbText = $('#shoutbox-form textarea');
		
		if(sbText.val() == "") { 	
			$('#shoutbox-status').html('Message vide !');
			return false;
		} else {
			$.ajax({
				data: {
					action: 'shout_add',
					comment: sbText.val()
				},
				beforeSend: function() {
					sbBtn.btnLoading("Ajout en cours...");
					sbText.attr("disabled", "disabled");
				},
				success: function(response) {
					sbBtn.btnRestore();
					sbText.removeAttr("disabled").val("");
					$('#shoutbox-form').hide();
					$('#shoutbox-status').empty();
					$('#shoutbox-list').prepend(response);
					shoutbox.init();
				}
			});
		}
	},
	
	del: function(id) {
		var shout = $('#shout-' + id);
		shout.css("opacity", 0.5);
		var deleteConfirm = confirm("Voulez-vous vraiment supprimer ce message de la shoutbox ?");
		if(deleteConfirm == true) {
			shout.remove();
			$.ajax({
				data: {
					action: 'shout_delete',
					id: id
				}
			});
		} else
			shout.fadeTo("fast", 1);
	},
	
	check: function() {
	
		// Récupère la date de dernière mise à jour de la shoutbox
		var time = $('#shoutbox').attr("class").split("-");

		$.ajax({
			data: {
				action: 'shoutbox_check',
				time: time[1]
			},
			success: function(response) {
				if(response > 0) {
					$('#shoutbox-refresh').html(response + ' nouveau' + (response > 1 ? 'x' : '') + ' shout' + (response > 1 ? 's' : '') + '. <a href="#sb_refresh" onclick="shoutbox.refresh();return false;">Rafraîchir</a><div class="space"></div>');
					document.title = '(' + response + ') ' + _documentTitle;
				}
			}
		});

	},
	
	refresh: function() {
		$.ajax({
			data: {
				action: 'shoutbox_get'
			},
			success: function(response) {
				$('#shoutbox').replaceWith(response);
				shoutbox.init();
				document.title = _documentTitle;
			}
		});

	}
};
	
/* COMMENTAIRES */
var comments = {

	init: function(wrapper) {
		if(!wrapper) var wrapper = "";
		
		$(wrapper + '.comments-smileys a').css("opacity", ".2").hover(function(){
			$(this).css("opacity", "1");
		},function(){
			$(this).css("opacity", ".2");
		}).click(function() {
			comments.insert($(this).attr("rel"), $(this).attr("title"));
			return false;
		});
	},

	post: function(artId) {
		var wrapper = comments.wrapper(artId);
		
		var commentBtn = $(wrapper + ' input:button');
		var commentText = $(wrapper + ' textarea');
		var commentStatus = $(wrapper + ' .comments-status');
		
		if(commentText.val() == "") { 
			commentStatus.html('Commentaire vide !');
			return false;
		} else {
			$.ajax({
				data: {
					action: 'comment_add',
					id: artId,
					comment: commentText.val()
				},
				beforeSend: function() {
					commentText.attr("disabled", "disabled");
					commentBtn.btnLoading("Ajout en cours...");
				},
				success: function(response) {
					$(wrapper + ' .comments-none').hide();
					$(wrapper + ' .comments-list').append(response);
					commentText.removeAttr("disabled").val("");
					commentStatus.empty();
					commentBtn.btnRestore();
					comments.updateTotal(artId);
				}
			});
		}
	},

	edit: function(commId) {
	
		var comment = comments.comment(commId);
		
		$.ajax({
			data: {
				action: 'comment_get',
				id: commId
			},
			success: function(response) {
				$(comment + ' .comment-delete').hide();
				$(comment + ' .comment-text').hide()
				.after('<form action="#" id="edit-comment-' + commId + '"><textarea>' + response + '</textarea><br /><input type="button" onclick="comments.editPost(' + commId + ')" value="Ok" /> <input type="button" onclick="comments.editCancel(' + commId + ')" value="Annuler" /></form>');
			}
		});
	},
	
	editCancel: function(commId) {
	
		var comment = comments.comment(commId);
		
		$('#edit-comment-' + commId).remove();
		$(comment + ' .comment-text').fadeIn();
		$(comment + ' .comment-delete').css("display", null);
	},
	
	editPost: function(commId) {
	
		var comment = comments.comment(commId);
		var commentText = $('#edit-comment-' + commId + ' textarea');
		
		if(commentText.val() == "") {
			alert('Commentaire vide !');
			return false;
		} else {
			$.ajax({
				data: {
					action: 'comment_edit',
					comm_id: commId,
					comment: commentText.val()
				},
				success: function(response) {
					$(comment + ' .comment-text').html(response);
					comments.editCancel(commId); // clean le mess
				}
			});
		}
	},

	del: function(commId, artId) {
		var comment = $(comments.comment(commId));
		comment.css("opacity", 0.5);
		var deleteConfirm = confirm("Voulez-vous vraiment supprimer ce commentaire ?");
		if(deleteConfirm == true) {
			comment.remove();
			comments.updateTotal(artId);
			$.ajax({
				data: {
					action: 'comment_delete',
					id: commId
				}
			});
		} else
			comment.fadeTo("fast", 1);
	},
	
	insert: function(artId, text) {
		var textarea = $(comments.wrapper(artId) + ' textarea')[0]; // Bug stupide de jQuery qui retourne toujours un tableau
		var str = textarea.value;
		var msgStart = textarea.selectionStart, msgEnd = textarea.selectionEnd; // Récupération de la position du curseur
		var bbTag = text.split("]");
		if(bbTag[1])
			var bbTagStart = bbTag[0] + "]", bbTagEnd = bbTag[1] + "]";
		else
			var bbTagStart = bbTag[0], bbTagEnd = "";
		if(typeof msgStart == "undefined") { // Cas IE
			textarea.focus();
			var caretPos = document.selection.createRange().duplicate();
			caretPos.text = bbTagStart + caretPos.text + bbTagEnd;
		} else {
			textarea.value = str.substring(0, msgStart) + bbTagStart + str.substring(msgStart, msgEnd) + bbTagEnd + str.substring(msgEnd, str.length);
			var newCaretPos = msgStart + bbTagStart.length + str.substring(msgStart, msgEnd).length;
			textarea.setSelectionRange(newCaretPos, newCaretPos); // repositionne le curseur dans la textbox
     		}
		textarea.focus();
	},

	updateTotal: function(artId) {
		var wrapper = comments.wrapper(artId);
		var commTotal = $(wrapper + ' .comment-text').size();
		if(commTotal == 0) $(wrapper + ' .comments-none').show();
		$(wrapper + ' .comments-total').html((commTotal < 1 ? 'C' : commTotal + ' c') + "ommentaire" + (commTotal == 1 ? '' : 's'));
	},
	
	toggle: function(artId) {
		$('#article-' + artId + ' .article-comments').toggle();
		if($('#article-' + artId + ' .article-comments-list').html() == "") {
			$.ajax({
				data: {
					action: 'comments_get',
					art_id: artId
				},
				beforeSend: function() {
					$('#article-' + artId + ' .article-comments-list').html('Chargement...');
				},
				success: function(response) {
					$('#article-' + artId + ' .article-comments-list').html(response);
					comments.init('#article-' + artId + ' ');
					imagePreview();
				}
			});
		}
	},

	
	/* Retourne l'élément à partir de son ID */
	comment: function(commId) {
		return '#comment-' + commId;
	},
	
	wrapper: function(artId) {
		return '#comments-' + artId;
	}
		
};

/* Users */
var user = {
	
	signup: function() {
		user.formSubmit('signup');
	},
	
	login: function() {
		user.formSubmit('login');
	},
	
	formSubmit: function(action) {
	
		var form = '#' + action;
		var submitBtn = $(form + ' .submit');
		var status = $(form + ' .status');
		
		$.ajax({
			data: $(form).serialize() + "&action=user_" + action,
			beforeSend: function() {
				status.empty();
				submitBtn.btnLoading();
			},
			success: function(response) {
				if (response != "") {
					status.html(response);
					submitBtn.btnRestore();
					return false;
				} else {
					window.location.reload();
					return true;
				}
			}
		});
	},
	
	mailPassword: function() {
		var emailResend = $('#email_resend').val();
		$.ajax({
			data: {
				action: 'user_mail_password',
				email_resend: emailResend
			},
			success: function(response) {
				if (response != "")
					$('#login .status').html(response);
				else {
					$('#login .status').html("Vos identifiants ont été envoyés à l'adresse <strong>" + emailResend + "</strong>. Si vous ne les trouvez pas vérifiez dans vos spams.");
					$('#login_lost').toggle();
				}
			}
		});
	},
	
	update: function() {
		var postValues = $('#profile').serialize() + "&action=user_update";
		$.ajax({
			data: postValues,
			success: function(response) {
				$('#pref_status').html(response);
			}
		});
	}
};

i1 = new Image; i1.src = "img/progress.gif";

 
function isLoading(container) {
	$(container).html('<img src="img/progress.gif" alt="Chargement" />');
}

var archives = {

	init: function() {
		$('.archives-months:not(:first)').hide();
		$('.archives-months div span:first').addClass("active");
		
		$('.archives-months span').click(function() {
			var month = $(this).attr("id").split("_");
			archives.getMonthly(month[1]);		
		});
		
	},

	toggleAll: function() {
		$('.archives-months:not(:first)').toggle();
	},
	
	getMonthly: function(fullDate) {
		element = $('#month_' + fullDate);
		
		element.toggleClass("active");
		list = $("#list" + fullDate);
		
		if(list.length == 0) {
			$.ajax({
				data: {
					action: 'articles_get_monthly',
					date: fullDate
				},
				beforeSend: function() {
					element.parent().after('<div id="loading' + fullDate + '" class="grey">Chargement...</div>');
				},
				success: function(response) {
					$("#loading" + fullDate).remove();
					element.parent().after(response);
				}
			});
		} else {
			list.toggle();
		}
	}
};

var articles = {

	check: function() {

		// Récupère la date de génération de la page
		var time = $('#main').attr("class").split("-");
	
		$.ajax({
			data: {
				action: 'articles_check',
				time: time[1]
			},
			success: function(resp) {
				var resp = $.parseJSON(resp);
				var newItems = resp.articles + resp.comments;
				if(newItems > 0) {
					
					$("#blog-refresh .info").html((resp.articles > 0 ? resp.articles + " article" + (resp.articles > 1 ? "s" : "") : "") + (resp.articles > 0 && resp.comments > 0 ? " et " : "") + (resp.comments > 0 ? resp.comments + " commentaire" + (resp.comments > 1 ? "s" : "") : "") + (newItems == 1 ? " a été posté" : " ont été postés"));
					$("#blog-refresh").fadeIn();
				}
			}
		});
	}

};

var menu = {

	init: function() {
		$("h2 label").attr("title", "Masquer");
		
		var menuElements = ["shoutbox", "hors_contexte", "lastfm", "archives", "tags", "links"];
		for(element in menuElements) {
			if($.cookie("menu_" + menuElements[element]) == "hide") {
				// Cacher l'élément et le décocher
				$("#menu_" + menuElements[element])
					.hide()
					.prevAll("h2")
					.children("label").attr("title", "Afficher")
					.prev(":checkbox").each(function() {
						this.checked = false;
					});
			}
		}
	},
	
	toggleElement: function(element) {
		var element = $(element);
		var checked = element.attr('checked') ? 1 : 0;
		if(checked) {
			element.parent().nextAll("div").show();
			element.next("label").attr("title", "Masquer");
			var cookieName = element.parent().nextAll("div").attr("id");
			$.cookie(cookieName, null, { path: '/' });
		} else {
			element.parent().nextAll("div").hide();
			element.next("label").attr("title", "Afficher");
			var cookieName = element.parent().nextAll("div").attr("id");
			$.cookie(cookieName, "hide", { expires: 666, path: '/' });
		}
	}
};

this.imagePreview = function(){	
	/* CONFIG */
		
		xOffset = 10;
		yOffset = 30;
		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
		
	/* END CONFIG */
	$("img.preview").hover(function(e){
		this.t = this.title;
		this.title = "";	
		var c = (this.t != "") ? "<br/>" + this.t : "";
		$("body").append("<p id='preview'><img src='"+ this.alt +"' alt='Image preview' />"+ c +"</p>");								 
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");						
    },
	function(){
		this.title = this.t;	
		$("#preview").remove();
    });	
	$("img.preview").mousemove(function(e){
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};

/* Extend */
jQuery.fn.extend({
	requires_login: function() {
		return this.each(function() {
			$(this).click(function() {
				lightbox.show('#loginbox');
				return false;
	    		});
		});
	},
	
	btnLoading: function(text) {
		if(!text) var text = "Chargement...";
		this.attr("title", this.attr("value"))
		.attr("value", text)
		.attr("disabled", "disabled");
	},
	
	btnRestore: function() {
		this.attr("value", this.attr("title"))
		.removeAttr("disabled")
		.removeAttr("title");
	}
});


/* On document ready */
$(document).ready(function() {

	tags.init();
	shoutbox.init();
	archives.init();
	menu.init();
	comments.init();
	
	imagePreview();
	
	_documentTitle = document.title;
	
	// Check la shoutbox à intervalle régulier (ms)
	setInterval("shoutbox.check()", 20000);
	setInterval("articles.check()", 300000);

	// Définit les liens toggle
	$('[rel]').click(function() {
		$('#' + $(this).attr("rel")).toggle();
		return false;
	});
	
	// Ferme les lightboxes
	$('a.close,#overlay').click(function() {
		lightbox.hide();
		return false;
	});
	
	// Login
	$('#login').submit(function() {
		user.login();
		return false;
	});
	
	// Signup
	$('#signup').submit(function() {
		user.signup();
		return false;
	});
});
