var App; if (!App) App = {};
var Init; if (!Init) Init = {};
var Interact; if (!Interact) Interact = {};
var Options; if (!Options) Options = {};
var Handlers; if (!Handlers) Handlers = {};
var Manipulate; if (!Manipulate) Manipulate = {};

Interact = {
	
	"share" : function(service,infos){
		var services = {
			"facebook": "http://www.facebook.com/sharer.php?u={url}",
			"delicious": "http://delicious.com/save?url={url}&title={title}",
			"google": "http://www.google.com/bookmarks/mark?op=add&bkmk={url}&title={title}",
			"blogger": "http://www.blogger.com/blog_this.pyra?t={url}",
			"digg": "http://digg.com/submit?url={url}&title={title}",
			"myspace": "http://www.myspace.com/Modules/PostTo/Pages/?u={url}&t={title}",
			"twitter": "http://twitter.com/home?status={url}",
			"linkedin": "http://www.linkedin.com/shareArticle?mini=true&ro=false&url={url}&title={title}",
			"netvibes": "http://www.netvibes.com/share?url={url}&title={title}",
			"newsvine": "http://www.newsvine.com/_tools/seed&save?u={url}&h={title}&s=&loginError=insufficient-params",
			"stumbleupon": "http://www.stumbleupon.com/submit?url={url}&title={title}",
			"tumblr": "http://www.tumblr.com/login?s=&v=3&u={url}&t={title}",
			"yahoobuzz": "http://buzz.yahoo.com/buzz?targetUrl={url}"
		};
		if(services[service]) {
			var url = Templates.render(services[service],infos);
			App.Stats.event('Share', service, infos.url);
			var wdw = window.open(url,"share");
		}
	},
	
	"comment" : function(related,params,callback,error) {
		if(!callback) { callback = function(comment){}; }
		if(!error) { error = function(){}; }
		$.post("/interact/comments.html","related="+related+"&"+params,function(data) {
			if(!data.error) {
				//var comment = $.evalJSON(data);
				var comment = data;
				callback(comment);
			} else {
				error(data);
			}
		},"json");
	
	},
	
	"abuse" : function(related,params,callback,error) {
		if(!callback) { callback = function(){}; }
		if(!error) { error = function(){}; }
		$.post("/interact/abuse.html",params+"&related="+related,function(data) {
			if(data == "DONE") { callback(); }
			else { error(); }
		},"text");
	
	},
	
	"rank" : function(related,rank,el) {
		var params = "related="+related+"&rank="+rank;
		//if(!$.cookie("ranking_"+related) || ($.cookie("ranking_"+related)+0) < 0) {
		if(!Cookies.exist("ranking_"+related)) {
			el.qtip("api").updateContent("Vote en cours...").show();
			$.post("/interact/rankings.html",params,function(data) {
				if(data != "ERROR") {
					Cookies.set("ranking_"+related,rank);
					//$.cookie("ranking_"+related, rank, { expires: 365, path: '/' });
					if(el && el.length) {
						el.qtip("api").updateContent("<b>Merci!</b>").show();
						
						var title = window.location.href;
						if($(el).parents("span.article").find("a.title").length) {
							title = $(el).parents("span.article").find("a.title").text();
						}
						if(rank == 0) { App.Stats.event("Rank","Down",title); }
						else { App.Stats.event("Rank","Up",title); }
					}
				}
				else if(el && el.length) {
					el.qtip("api").updateContent("Erreur").show();
				}
			});
		} else if(el && el.length) {
			el.qtip("api").updateContent("<b>Déjà voté</b>").show();
		}
	
	},
	
	"rate" : function(related,rating,form) {
		//if(!$.cookie("rating_"+related) || ($.cookie("rating_"+related)+0) <= 0) {
		if(!Cookies.exist("rating_"+related)) {
			$.post("/interact/ratings.html",form.serialize(),function(data) {
				if(data != "ERROR") {
					//$.cookie("rating_"+related, rating, { expires: 365, path: '/' });
					Cookies.set("rating_"+related,rating);
					if(form && form.length) {
						form.children("input[name=currentRating]").val(rating)
						form.children(".count").html("<strong>Merci !</strong>");
						window.setTimeout(function() {
							form.children(".count").html(data+" vote(s)");
						},2000);
						
						var title = window.location.href;
						if($(form).parents("span.article").find("a.title").length) {
							title = $(form).parents("span.article").find("a.title").text();
						}
						App.Stats.event("Rate",rating,title);
					}
				}
				else {
					if(form && form.length) {
						var html = form.children(".count").html();
						form.children(".count").html("<strong>Erreur</strong>");
						window.setTimeout(function() {
							form.children(".count").html(html);
							form.stars("select", $("#ratingForm input[name=currentRating]").val());
						},2000);
					}
				}
			});
		} else if(form && form.length) {
			var html = form.children(".count").html();
			form.children(".count").html("<strong>Déjà voté</strong>");
			window.setTimeout(function() {
				form.children(".count").html(html);
				form.stars("select", form.children("input[name=currentRating]").val());
			},2000);
		}
	
	},
	
	"addComment" : function(container,comment) {
		var html = $(Templates.render(Templates.comment,comment));
		if(container.find("span.comment").length) { container.find("span.comment:last").after(html.hide()); }
		else { container.find("h4.top").after(html.hide()); }
		if(container.find("p.nocomment").length) { container.find("p.nocomment").remove(); }
		html.show("fast");
		Interact.updateCommentCount(comment.related);
		Init.Rank(html.find("a.rank"));
		Init.Reply(html.find("a.reply"));
		Init.Abuse(html.find("a.abuse"));
		
	},
	
	"addReply" : function(target,comment) {
		var html = $(Templates.render(Templates.reply,comment));
		target.parents("span.comment").after(html.addClass("reply").hide());
		html.show("fast");
		Interact.updateCommentCount(comment.related);
		Init.Rank(html.find("a.rank"));
		Init.Reply(html.find("a.reply"));
		Init.Abuse(html.find("a.abuse"));
	},
	
	"updateCommentCount" : function(related) {
		if($(".view-comments a[rel="+related+"]").length) {
			var count = parseInt($(".view-comments a[rel="+related+"]").text()) + 1;
			$(".view-comments a[rel="+related+"]").text(count);
		}
	}

};


///////////////////////////////////////////////////////////
/////////////////Rank/////////////////////////////////////
///////////////////////////////////////////////////////////
Init.Rank = function(selector) {

	$(selector).qtip(Options.qtip_rank);
	
	$(selector).click(function(e) {
		e.preventDefault();
		var relativeY = e.pageY - $(this).offset().top;
		var related = $(this).attr("rel");
		if(relativeY >= 0 && relativeY <= 16) { var rank = 5; }
		else { var rank = 0; }
		Interact.rank(related,rank,$(this));
		
	}).mouseover(function(e) {
		var content = $(this).qtip("api").elements.content.html();
		
		if(content == "Vote" || content == "Intéressant" ||  content == "Sans intérêt") {
			var relativeY = e.pageY - $(this).offset().top;
			if(relativeY >= 0 && relativeY <= 16) { $(this).qtip("api").updateContent("Intéressant"); }
			else { $(this).qtip("api").updateContent("Sans intérêt"); }
		}
		
	}).mousemove(function(e) {
		if($(this).qtip("api").elements.content) {
			var content = $(this).qtip("api").elements.content.html();
			
			if(content == "Vote" || content == "Intéressant" ||  content == "Sans intérêt") {
				var relativeY = e.pageY - $(this).offset().top;
				if(relativeY >= 0 && relativeY <= 16) { $(this).qtip("api").updateContent("Intéressant"); }
				else { $(this).qtip("api").updateContent("Sans intérêt"); }
			}
		}
	});
};
//////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////
/////////////////Share/////////////////////////////////////
///////////////////////////////////////////////////////////
Init.Share = function(selector) {
	var share_opts = Options.qtip_share;
	share_opts.api = {
		onContentUpdate:function() {
			if(this.elements.content) { Init.ShareTooltip(this); }
		}
	};
	$(selector).click(function(e){ e.preventDefault(); }).qtip(share_opts);
};

Init.ShareTooltip = function(qtip) {
	var content = qtip.elements.content;
	var domain = "http://"+location.hostname;
	var url = (qtip.elements.target.attr("href").length > 1) ? qtip.elements.target.attr("href"):location.href;
	var id = parseInt(qtip.elements.target.parents(".article").attr("id").substr(1));
	var title = qtip.elements.target.parents("span.article").find(".title").text()+" - I.nfor.me";
	content.find(".url").click(function(){ this.select(); });
	content.find(".long").val(domain + url);
	content.find(".tiny").val(domain + "/" +encode_base36(id));
	url = domain + "/" +encode_base36(id);
	var infos = { 'url': url, 'title': title };
	
	content.find(".sendEmail .hint").hint();
	content.find(".sendEmail textarea").val(Templates.render(Templates.sendByMail,infos));
	content.find(".sendEmail form").submit(function(e) {
		e.preventDefault();
		var form = $(this);
		form.find("div.success").remove();
		form.find("div.error").remove();
		if(form.validate()) {
			form.block({centerY:true});
			$.post("/ajax/contact.txt",form.serialize(),function(data) {
				form.unblock();
				if(data == "DONE") {
					App.Stats.event("Share","Email",infos.title);
					content.find(".sendEmail").before("<div class='success' style='cursor:pointer;'>Votre message a été envoyé</div>");
					content.find(".success").click(function() { content.find(".success").remove(); });
					form.find("input[type=text]").each(function() {
						$(this).val($(this).attr("title")).addClass("hasHint");
					});
					content.find(".sendEmail").hide("fast");
				} else {
					form.prepend("<div class='error'>"+data+"</div>");
				}
			});
		}
	});
	content.find(".services a").click(function(e) {
		e.preventDefault();
		if($(this).attr("rel") == "email") {
			
			content.find(".sendEmail").toggle("fast");
			
			
		} else { Interact.share($(this).attr("rel"),infos); }
	});
};
//////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////
/////////////////Rating/////////////////////////////////////
///////////////////////////////////////////////////////////
Init.Stars = function(selector) {
	$(selector).stars({
		oneVoteOnly: true,
		callback: function(ui, type, rating) {
			var form = $(ui.element);
			var related = form.children("input[name=related]").val();
			Interact.rate(related,rating,form);
		}
	});
};
//////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////
/////////////////Comments//////////////////////////////////
///////////////////////////////////////////////////////////
Init.Comments = function(selector) {

	var container = $(selector);
	
	container.find(".comments-close").click(function(e) {
		e.preventDefault();
		container.slideUp("fast");
	});
	
	Init.Reply(container.find("a.reply"));
	Init.Abuse(container.find("a.abuse"));
	
	
	/////Envoie le formulaire de commentaire
	container.find(".make-comment form").submit(function(e) {
		e.preventDefault();
		var related = $(this).find("input[name=related]").val();
		var title = window.location.href;
		if(!$(this).find("#recaptcha_div_"+related).length) {
			container.find(".make-comment").block();
		}
		if($(this).parents("div.article-container").find(".title").length) {
			title = $(this).parents("div.article-container").find(".title").text();
		}
		Interact.comment(related,$(this).serialize(),function(comment) {
			App.Stats.event("Comments","Write",title);
			if(!container.find("#recaptcha_div_"+related).length) { container.find(".make-comment").unblock(); }
			else { container.find(".make-comment form").unblock(); }
			container.find(".make-comment input[type=text], .make-comment textarea").val("");
			Interact.addComment(container,comment);
		},function(data) {
			container.find(".make-comment").unblock();
			var opts = Options.block_comments;
			if(!data.bot) {
				opts.message = data.error;
				container.find(".make-comment").block(opts);
				container.find(".make-comment").click(function() { $(this).unblock(); });
				window.setTimeout(function(){
					container.find(".make-comment").unblock();
				},2500);
			} else {
				opts.message = "<div id='recaptcha_div_"+related+"' align='center'></div>";
				opts.message += "<a href='#' class='recaptcha_submit'><img src='/statics/img/btn/ok.gif'/></a>";
				opts.centerY = false;
				opts.css.width = "500px";
				opts.css.textAlign = "center";
				opts.css.top = "10px";
				opts.css.backgroundColor = '#eee';
				opts.css.border = 'solid 1px #ccc';
				container.find(".make-comment form").block(opts);
				Recaptcha.create("6LcGDgoAAAAAAJqjgSdNWPsWj3_bKceMprWxvLws ","recaptcha_div_"+related, {
				   theme: "clean",
				   callback: Recaptcha.focus_response_field
				});
				container.find(".make-comment form .recaptcha_submit").click(function(e) {
					e.preventDefault();
					$(this).after("<span class='loading'> Chargement...</span>");
					container.find(".make-comment form").trigger("submit");
				});
				
			}
			
		});
	});
	///////////////////////////////////////////
};

Init.ScrollComments = function(selector) {
	$(selector).each(function() {
		if($(this).is(".scroll")) {
			$(this).click(function(e) {
				e.preventDefault();
				var related = $(this).attr("rel");
				if($(this).parents("span.article").next("#"+related+"_comments").is(":visible")) {
					$(this).parents("span.article").next("#"+related+"_comments").slideUp("fast");
				} else {
					var container = $(this).parents("span.article").next("#"+related+"_comments");
					container.html("<span class='comments'><div align='center'><img src='/statics/img/loading_featured.gif' /></div></span>").slideDown(300);
					Templates.comments(related,function(data) {
					
						container.hide().html(data).slideDown(700,function() {
							Init.Rank($(this).find("a.rank"));
						});
						
						container.find(".comments-close").click(function(e) {
							e.preventDefault();
							container.slideUp("fast");
						});
						
						Init.Reply(container.find("a.reply"));
						Init.Abuse(container.find("a.abuse"));
						
						
						/////Envoie le formulaire de commentaire
						container.find(".make-comment form").submit(function(e) {
							e.preventDefault();
							
							var related = $(this).find("input[name=related]").val();
							var title = window.location.href;
							if(!$(this).find("#recaptcha_div_"+related).length) {
								container.find(".make-comment").block();
							}
							if($(this).parents("div.article-container").find(".title").length) {
								title = $(this).parents("div.article-container").find(".title").text();
							}
							
							Interact.comment(related,$(this).serialize(),function(comment) {
								App.Stats.event("Comments","Write",title);
								container.find(".make-comment input[type=text], .make-comment textarea").val("");
								if(!container.find("#recaptcha_div_"+related).length) { container.find(".make-comment").unblock(); }
								else { container.find(".make-comment form").unblock(); }
								Interact.addComment(container,comment);
							},function(data) {
								container.find(".make-comment").unblock();
								var opts = Options.block_comments;
								if(!data.bot) {
									opts.message = data.error;
									container.find(".make-comment").block(opts);
									container.find(".make-comment").click(function() { $(this).unblock(); });
									window.setTimeout(function(){
										container.find(".make-comment").unblock();
									},2500);
								} else {
									opts.message = "<div id='recaptcha_div_"+related+"' align='center'></div>";
									opts.message += "<a href='#' class='recaptcha_submit'><img src='/statics/img/btn/ok.gif'/></a>";
									opts.centerY = false;
									opts.css.width = "500px";
									opts.css.textAlign = "center";
									opts.css.top = "10px";
									opts.css.backgroundColor = '#eee';
									opts.css.border = 'solid 1px #ccc';
									container.find(".make-comment form").block(opts);
									Recaptcha.create("6LcGDgoAAAAAAJqjgSdNWPsWj3_bKceMprWxvLws ","recaptcha_div_"+related, {
									   theme: "clean",
									   callback: Recaptcha.focus_response_field
									});
									container.find(".make-comment form .recaptcha_submit").click(function(e) {
										e.preventDefault();
										$(this).after("<span class='loading'> Chargement...</span>");
										container.find(".make-comment form").trigger("submit");
									});
									
								}
							});
						});
						/////////////////////////////////
						
					},{page:1,nbr:3});
				}
				
			});
		}
	});
};

Init.Reply = function(selector) {
	var reply_opts = Options.qtip_reply;
	reply_opts.api = {
		onContentUpdate:function() {
			var qtip = this;
			var content = this.elements.content;
			var target = this.elements.target;
			if(content.length) {
				content.find(".hint").hint();
				
				
				/////Envoie le formulaire de commentaire
				content.find(".make-comment form").submit(function(e) {
					e.preventDefault();
					
					var related = target.parents("span.comments").attr("rel");
					
					if(!$(this).find("#recaptcha_div_"+related).length) {
						content.find(".make-comment").block();
					}
					
					var currentcomment = target.parents("span.comment");
					while(currentcomment.is(".reply")) {
						currentcomment = currentcomment.prev("span.comment");
					}
					var xid = parseInt(currentcomment.attr("id").substr(1));
					
					$(this).find("input[name=hierarchy]").val(xid);
					Interact.comment(related,$(this).serialize(),function(comment) {
						qtip.hide();
						content.find(".make-comment input[type=text], .make-comment textarea").val("");
						if(!content.find("#recaptcha_div_"+related).length) { content.find(".make-comment").unblock(); }
						else { content.find(".make-comment form").unblock(); }
						Interact.addReply(target,comment);
					},function(data) {
						content.find(".make-comment").unblock();
						var opts = Options.block_comments;
						if(!data.bot) {
							opts.message = data.error;
							content.find(".make-comment").block(opts);
							content.find(".make-comment").click(function() { $(this).unblock(); });
							window.setTimeout(function(){
								content.find(".make-comment").unblock();
							},2500);
						} else {
							opts.message = "<div id='recaptcha_div_"+related+"' align='center'></div>";
							opts.message += "<a href='#' class='recaptcha_submit'><img src='/statics/img/btn/ok.gif'/></a>";
							opts.centerY = false;
							opts.css.width = "500px";
							opts.css.textAlign = "center";
							opts.css.top = "10px";
							opts.css.backgroundColor = '#eee';
							opts.css.border = 'solid 1px #ccc';
							content.find(".make-comment form").block(opts);
							Recaptcha.create("6LcGDgoAAAAAAJqjgSdNWPsWj3_bKceMprWxvLws ","recaptcha_div_"+related, {
							   theme: "clean",
							   callback: Recaptcha.focus_response_field
							});
							content.find(".make-comment form .recaptcha_submit").click(function(e) {
								e.preventDefault();
								$(this).after("<span class='loading'> Chargement...</span>");
								content.find(".make-comment form").trigger("submit");
							});
							
						}
						
					});
				});
				///////////////////////////////////////////
			}
		}
	};
	$(selector).click(function(e){ e.preventDefault(); }).qtip(reply_opts);
};

Init.Abuse = function(selector) {
	var abuse_opts = Options.qtip_abuse;
	abuse_opts.api = {
		onContentUpdate:function() {
			var qtip = this;
			var content = this.elements.content;
			var target = this.elements.target;
			if(content.length) {
				content.find(".hint").hint();
				
				/////Envoie le formulaire d'abus
				content.find("form").submit(function(e) {
					e.preventDefault();
					var related = target.parents("span.comment").attr("id");
					Interact.abuse(related,$(this).serialize(),function() {
						content.html("<div class='success'>L'abus a été signalé aux administrateurs du site. Merci!</div>");
					},function() {
						content.html("<div class='error'>Il s'est produit une erreur</div>");
					});
				});
				///////////////////////////////////////////
			}
		}
	};
	$(selector).click(function(e){ e.preventDefault(); }).qtip(abuse_opts);
};
//////////////////////////////////////////////////////////
