var App; if (!App) App = {};
var Init; if (!Init) Init = {};
var Options; if (!Options) Options = {};


App = {
	
	'ie' : false,
	'ieVersion' : 0,
	'ie6' : false,
	'ie7' : false,
	'ie8' : false,
	
	'Stats' : null,

	'init' : function() {
		
		App.detectIE();
		
		$(".png").pngFix();
		
		$("input.hint, textarea.hint").hint();
		
		Init.Carousel("#banner");
		
		Init.LogoReel("#logoReel");
		
		Init.Team(".equipe");
		
		Init.Tabs(".twitterTabs");
		
		Init.Comments("#comments");
		
		Init.Share(".shareTool");
		
		Init.Contact("#contactForm");
		
		Init.Contact("#contactFormSkinny");
		
		Init.Haiti("#haitiForm");
		
	},
	
	'detectIE' : function() {
		if ($.browser.msie) {
			App.ie = true;
			App.ieVersion = parseInt($.browser.version.substr(0,1));
			if(App.ieVersion == 6) { App.ie6 = true; }
			if(App.ieVersion == 7) { App.ie7 = true; }
			if(App.ieVersion == 8) { App.ie8 = true; }
		}
	}
	
};


/*********************************************
*
* Common options
*
**********************************************/

Options = {

	"block_comments" : {
		message : "<img src='/statics/img/loading_block.gif' />",
		centerY : true,
		overlayCSS: {
			backgroundColor:'#666'
		}
	},
	"block_comments_error" : {
		message : "Veuillez remplir les champs requis",
		centerY : true,
		css: {
			backgroundColor:'#FBE3E4',
			color: "#8a1f11",
			border: "solid 2px #FBC2C4",
			width:'250px',
			cursor: 'pointer'
		},
		overlayCSS: {
			backgroundColor:'#666',
			cursor: 'pointer'
		}
	},
	"block_comments_success" : {
		message : "Votre commentaire a été ajouté avec succès",
		centerY : true,
		css: {
			backgroundColor:'#E6EFC2',
			color: "#264409",
			border: "solid 2px #C6D880",
			width:'250px',
			cursor: 'pointer'
		},
		overlayCSS: {
			backgroundColor:'#666',
			cursor: 'pointer'
		}
	},
	"block_contact" : {
		message : "<img src='/statics/img/loading_block.gif' />",
		centerY : true,
		overlayCSS: {
			backgroundColor:'#666'
		}
	}

};

/*********************************************
*
* Templates
*
**********************************************/

Templates = {

	"sendByMail" : 'Bonjour,\nVoici une adresse intéressante :\n\n{title}\n{url}',

	"comment" : "<div class='comment'><div class='top'><br/><b>{author}</b> au {dateFormat}</div><div class='body'>{text}</div></div>",

	"render" : function(text,values) {
		var re_cache = {};
		var tmpl = text.replace(/%7B/ig,'{').replace(/%7D/ig,'}');
		$.each(values, function(k,v) {
			tmpl = tmpl.replace( new RegExp('{'+k+'}', 'gm'), v );	
		});
		
		return tmpl;

	}
};

/*********************************************
*
* Quick Init
*
**********************************************/

Init.Team = function(selector) {

	var $el = $(selector);
	if(!$el.length || !$el.find("a").length) { return; }
	
	$el.find("a").click(function(e) {
		e.preventDefault();
		
		var src = $el.find("a.active img").attr("src")+"";
		$el.find("a.active").removeClass("active").find("img").attr("src",src.replace(/\-on\./i,'-off.'));
		
		var src = $(this).find("img").attr("src")+"";
		$(this).addClass("active").find("img").attr("src",src.replace(/\-off\./i,'-on.'));
	});
	var src = $el.find("a:first img").attr("src")+"";
	$el.find("a:first").addClass("active").find("img").attr("src",src.replace(/\-off\./i,'-on.'));
	
}

Init.Carousel = function(selector) {

	var el = $(selector);
	if(!el.length || !el.find("a.next").length) { return; }

	var screenshots = [];
	var stats = [];
	var currentIndex = 0;
	var currentStatsIndex = 0;
	el.data("animating",false);
	
	el.find("a.next").click(function(e) {
		e.preventDefault();
		
		if(!el.data("animating")) {
			App.Stats.event("Naviguation", "Carousel", "next");
			el.data("animating",true);
			var nextIndex = (currentIndex == (screenshots.length-1)) ? 0:currentIndex+1;
			var nextStatsIndex = (currentStatsIndex == (stats.length-1)) ? 0:currentStatsIndex+1;
			
			
			///Change les screenshots
			el.find("a.screenshot").after(screenshots[nextIndex].clone());
			el.find("a.screenshot").eq(0).animate({'left':"-890px"},"slow",function() {
				$(this).remove();
				el.data("animating",false);
			});
			el.find("a.screenshot").eq(1).css("left","890px").animate({'left':"0px"},"slow");
			
			el.find("a.screenshot").unbind("click").click(function(e) { 
				App.Stats.event("Naviguation", "Carousel", $(this).attr("href"));							 
			});
			
			///Change les ronds de statistiques
			var currentStat = el.prev(".stats").find("a.rond").eq(0);
			var nextStat = stats[nextStatsIndex].clone();
			el.prev(".stats").append(nextStat);
			if(App.ie6) { nextStat.pngFix(); }
			currentStat.css({"zIndex":111,"top":"0px","left":"0px","position":"relative"});
			nextStat.css({"zIndex":110,"opacity":0,"top":"0px","left":"-248px","position":"relative"});
			currentStat.fadeTo("slow",0,function() {
				$(this).remove();
			});
			currentStat.find("img").fadeTo("slow",0);
			nextStat.fadeTo("slow",1,function() {
				$(this).css({"filter":"","left":"0px"});
			});
			
			
			
			currentIndex = nextIndex;
			currentStatsIndex = nextStatsIndex;
		}
	});
	
	///Charge les screenshots dans une array javascript
	el.find("a.screenshot").each(function() {
		screenshots.push($(this).clone());
		$(this).remove();
	});
	
	///Charge les ronds de statistiques dans une array javascript
	el.find("a.rond").each(function() {
		stats.push($(this).clone());
		$(this).remove();
	});
	
	el.before("<div class='stats'></div>");
	el.prev(".stats").css({'position':'absolute','top':(el.offset().top+20)+'px','left':(el.offset().left-50)+'px','zIndex':101, 'overflow':"hidden"});
	el.css({'zIndex':100, 'position':"relative", 'overflow':"hidden"});
	el.find("a.next").css({"top":"240px","left":"727px"});
	el.prepend(screenshots[currentIndex].clone());
	el.prev(".stats").append(stats[currentStatsIndex].clone());
	
	$(window).resize(function() {
		el.prev(".stats").css({'top':(el.offset().top+20)+'px','left':(el.offset().left-50)+'px'});
	}).load(function() {
		el.prev(".stats").css({'top':(el.offset().top+20)+'px','left':(el.offset().left-50)+'px'});
	});
	
	if(App.ie6) {
		el.prev(".stats").pngFix();
		el.find("a.next").pngFix();
	}

};

Init.LogoReel = function(selector) {

	var el = $(selector);
	if(!el.length || !el.find("a.prev").length) { return; }

	var logos = [];
	var currentIndex = 0;
	var reelWidth = el.find(".logos").width();
	
	el.data("animating",false);
	
	el.find("a.next").click(function(e) {
		e.preventDefault();
		
		if(!el.data("animating")) {
			App.Stats.event("Naviguation", "LogoReel", "next");
			el.data("animating",true);
			var nextIndex = (currentIndex == (logos.length-1)) ? 0:currentIndex+1;
			
			///Change les logos
			var width = el.find(".logos a.logo:first").addClass("remove").width();
			el.find(".logos a.logo:last").after(logos[nextIndex].clone());
			var currentWidth = 0 - width;
			el.find(".logos a.logo").each(function() { currentWidth += $(this).width(); });
			while(reelWidth > currentWidth) {
				nextIndex = (nextIndex == (logos.length-1)) ? 0:nextIndex+1;
				el.find(".logos a.logo:last").after(logos[nextIndex].clone());
				currentWidth += el.find(".logos a.logo:last").width();
			}
			
			el.find(".logos a.logo").unbind("click").click(function(e) { 
				App.Stats.event("Naviguation", "LogoReel", $(this).attr("href"));							 
			});
			
			el.find(".logos a.logo").css("position","relative").animate({'left':"-"+width+"px"},"slow",function() {
				el.find(".logos a.remove").remove();
				el.find(".logos a.logo").css({"position":"static","left":"0px"});
				el.data("animating",false);
			});
			
			currentIndex = parseInt(el.find(".logos a.logo:last").attr("rel"));
		}
	});
	
	el.find("a.prev").click(function(e) {
		e.preventDefault();
		
		if(!el.data("animating")) {
			App.Stats.event("Naviguation", "LogoReel", "previous");
			el.data("animating",true);
			var firstIndex = el.find(".logos a.logo:first").attr("rel");
			var prevIndex = (firstIndex == 0) ? (logos.length-1):firstIndex-1;
			
			///Change les logos
			el.find(".logos a.logo:first").before(logos[prevIndex].clone());
			var width = el.find(".logos a.logo:first").width();
			
			var currentWidth = 0 - el.find(".logos a.logo:last").width();
			el.find(".logos a.logo").each(function() { currentWidth += $(this).width(); });
			if(currentWidth > reelWidth){ el.find(".logos a.logo:last").addClass("remove"); }
			
			el.find(".logos a.logo").css({"position":"relative","left":"-"+width+"px"});
			el.find(".logos a.logo").animate({'left':"0px"},"slow",function() {
				el.find(".logos a.remove").remove();
				el.find(".logos a.logo").css({"position":"static","left":"0px"});
				currentIndex = parseInt(el.find(".logos a.logo:last").attr("rel"));
				el.data("animating",false);
			});
			
			
		}
	});
	
	var currentWidth = 0;
	
	///Charge les logos dans une array javascript
	el.find(".logos a.logo").each(function(index) {
		$(this).attr("rel",index);
		logos.push($(this).clone());
		currentWidth += $(this).width();
		if(currentIndex > 0) { $(this).remove(); }
		if(currentWidth > reelWidth) { currentIndex = index; }
		
	});
	
	
	
	el.find(".logos").css("position","relative");
	
	currentIndex = parseInt(el.find(".logos a.logo:last").attr("rel"));
	
	var autoInterval = window.setInterval(function() {
		el.find("a.next").trigger("click");
	},2000);
	
	el.mouseover(function() {
		if(autoInterval) { window.clearInterval(autoInterval); }
	});
	el.mouseout(function() {
		if(autoInterval) { window.clearInterval(autoInterval); }
		autoInterval = window.setInterval(function() {
			el.find("a.next").trigger("click");
		},2000);
	});

};

Init.Tabs = function(selector) {
			
	var el = $(selector);
	if(!el.length) { return; }
	
	el.find("ul.tabs li a").click(function(ev) {
		ev.preventDefault();
		App.Stats.event("Naviguation", "Tabs", "click");
		var index = el.find("ul.tabs li").index($(this).parent());
		
		el.find("ul.tabs li").addClass("inactive");
		el.find("ul.tabs li").eq(index).removeClass("inactive");
		if(App.ie6) {
			var offset = el.find(".contents").offset();
			el.find(".contents .content").eq(index).css({"position":"absolute","top":(offset.top)+"px","left":(offset.left)+"px"});
		}
		el.find(".contents .content:visible").fadeOut("fast");
		el.find(".contents .content").eq(index).fadeIn("fast",function() {
			if(App.ie6) {
				$(this).css({"position":"static"});
			}
		});
		
	});
	
	
	var maxHeight = 0;
	el.find(".contents").css({"zIndex":9});
	
	el.find(".contents .content").each(function(index) {
		
		if($(this).height() > maxHeight) { maxHeight = $(this).height(); }
		
		$(this).css({"position":"absolute","zIndex":(10+index)});
		
		if(App.ie6) {
			$(this).css({"position":"static"});
		}
		
	});
	
	el.find(".contents").css("height",maxHeight+"px");
	
};

Init.Comments = function(selector) {
	
	var el = $(selector);
	var form = el.find(".write form");
	var list = el.find(".list");
	if(!el.length) { return; }
	
	form.submit(function(e) {
		e.preventDefault();
		
		el.find(".write form").block(Options.block_comments);
		
		if(form.find("textarea").val() == form.find("textarea").attr("title")) {
			form.find("textarea").val("");
		}
		
		$.post("/blog/comments.html",form.serialize(),function(data) {
			var comment = $.evalJSON(data);
			if(!comment.error) {
				App.Stats.event("Comments", "Write", comment.title);
				list.append(Templates.render(Templates.comment,comment));
				if(list.find(".noresult").length) { list.find(".noresult").remove(); }
				form.find("input, textarea").val("");
				el.find(".write form").unblock();
				el.find(".write form").block(Options.block_comments_success);
				el.find(".write").unbind("click");
				el.find(".write form").click(function() { $(this).unbind("click").unblock(); });
				window.setTimeout(function(){
					el.find(".write").unblock();
				},2500);
			} else {
				el.find(".write form").unblock();
				App.Stats.event("Comments", "Error", comment.error);
				var opts = Options.block_comments_error;
				opts.message = comment.error;
				el.find(".write form").block(opts);
				el.find(".write").unbind("click");
				el.find(".write form").click(function() { $(this).unbind("click").unblock(); });
				window.setTimeout(function(){
					el.find(".write").unblock();
				},2500);
			}
			
			if(form.find("textarea").val() == "") {
				form.find("textarea").val(form.find("textarea").attr("title"));
			}
			
		
		});
	
	});

};

Init.Share = function(selector) {
	
	var el = $(selector);
	if(!el.length) { return; }
	
	el.find(".links a").click(function(e) {
		e.preventDefault();
		
		var el = $(this).parents(selector);
		var service = $(this).attr("rel");
		
		if(service == "email") {
			$(this).parents(selector).find(".sendEmail").toggle("fast")
			return;
		}
		
		var infos = {};
		infos.url = "http://sparko.ca"+el.parents("div.post").find("a.title").attr("href");
		infos.title = el.parents("div.post").find("a.title").text();
		
		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]) {
			App.Stats.event("Share", service, infos.title);
			var url = Templates.render(services[service],infos);
			var wdw = window.open(url,"share");
		}
	});
	
	el.each(function() {
		var infos = {};
		infos.url = "http://sparko.ca"+$(this).parents("div.post").find("a.title").attr("href");
		infos.title = $(this).parents("div.post").find("a.title").text();
		
		$(this).find(".sendEmail .hint").hint();
		$(this).find(".sendEmail textarea").val(Templates.render(Templates.sendByMail,infos));
	});
	el.find(".sendEmail form").submit(function(e) {
		e.preventDefault();
		var el = $(this).parents(selector);
		var form = $(this);
		form.find("div.success").remove();
		form.find("div.error").remove();
		
		if(form.validate()) {
			form.block(Options.block_comments);
			$.post("/"+App.lang+"/contact/sendtofriend.json",form.serialize(),function(data) {
				form.unblock();
				if(!data.error && data.success) {
					App.Stats.event("Share","Email",infos.title);
					el.find(".sendEmail").before("<div class='success' style='cursor:pointer;'>Votre message a été envoyé</div>");
					el.find(".success").click(function() { el.find(".success").remove(); });
					form.find("input[type=text]").each(function() {
						$(this).val($(this).attr("title")).addClass("hasHint");
					});
					el.find(".sendEmail").hide("fast");
				} else {
					form.prepend("<div class='error'>"+data.error+"</div>");
				}
			},"json");
		}
	});

};


Init.Contact = function(selector) {
	
	var el = $(selector);
	if(!el.length) { return; }
	
	el.find("form").submit(function(e) {
		e.preventDefault();
		var form = $(this);
		el.find("div.success").remove();
		el.find("div.error").remove();
		if(form.validate()) {
			form.block(Options.block_contact);
			$.post("/"+App.lang+"/contact.json",form.serialize(),function(data) {
				form.unblock();
				if(!data.error && data.success) {
					App.Stats.event("Contact", "Write", form.find("input[name=email]").val());
					el.find("form").before("<div class='success' style='cursor:pointer;'>"+data.msg+"</div>");
					el.find(".success").click(function() { el.find(".success").remove(); });
					form.find("textarea[name=message]").val("");
					form.find("input[type=text]").each(function() {
						$(this).val($(this).attr("title")).addClass("hasHint");
					});
				} else {
					el.find("form").before("<div class='error'>"+data.error+"</div>");
				}
			}, "json");
		}
	});

};

Init.Haiti = function(selector) {
	
	var el = $(selector);
	if(!el.length) { return; }
	
	el.find("form").submit(function(e) {
		e.preventDefault();
		var form = $(this);
		el.find("div.success").remove();
		el.find("div.error").remove();
		if(form.validate()) {
			form.block(Options.block_contact);
			$.post("/"+App.lang+"/haiti.json",form.serialize(),function(data) {
				form.unblock();
				if(!data.error && data.success) {
					App.Stats.event("Haiti", "Write", form.find("input[name=email]").val());
					el.find("form").before("<div class='success' style='cursor:pointer;'>"+data.msg+"</div>");
					el.find(".success").click(function() { el.find(".success").remove(); });
					form.find("textarea[name=message]").val("");
					form.find("input[type=text]").each(function() {
						$(this).val($(this).attr("title")).addClass("hasHint");
					});
				} else {
					el.find("form").before("<div class='error'>"+data.error+"</div>");
				}
			}, "json");
		}
	});

};

/*********************************************
*
* Google Analytics Object
*
**********************************************/

Analytics = function(account) {

	var self = this;
	
	try {
		self.tracker = _gat._getTracker(account);
		self.account = account;
	} catch(err) {}
	
};

Analytics.prototype.tracker = null;
Analytics.prototype.account = null;

Analytics.prototype.setVar = function(visitor) {
	if(!this.tracker) { return; }
	try {
	
		this.tracker._setVar(visitor);
		
	} catch(err) {}
};

Analytics.prototype.track = function(page) {
	if(!this.tracker) { return; }
	try {
	
		if(!page) { this.tracker._trackPageview(); }
		else{ this.tracker._trackPageview(page); }
		
	} catch(err) {}
};

Analytics.prototype.event = function(cat,action,label) {
	if(!this.tracker) { return; }
	try {
	
		this.tracker._trackEvent(cat, action, label);
		
	} catch(err) {}
};