/*	Project: 	Zloche landing page	Date: 		07/09/10	Author: 	Alexandre Leclair <alexandre.leclair@zloche.net>		Last Modification: 09/09/10*///======================================================================================//Defining global variablesvar messageQueueInterval = 4000; //Each message will be visible for 3 secondsvar lastID = 0; //Will hosld the lates ID we got from Message Servicevar msgCount = 5; //The amount of messages we want to fetch from the servervar gatewayURL = 'messageService.php';var konamiSound = 'media/splash.mp3';var konamiImage = {url: 'images/konami.png', w:321, h: 275};//Do not touch anuthing below thisvar messages = new Array(); //This array will hold objects representing the messages that will scroll.var animateTimeout;var session = '';var loadingMessages=false;var eraseTextboxOnClick = true;//Konami Codevar konami = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];var keyHistory = new Array(konami.length);//IE is acting up.var fblikeHovering = true;$(function() {  begin();});//======================================================================================/////	This function will initialize everything that needs to be initialized (Heh!)///function begin(){	//alert('Lucy a eu un ticket à cause de Poules. $128 de bonheur.');	/*******************	 *	Event handlers	 ******************/		//Color Easter Egg	$("#logo").click(function(e){	var offset = $("#logo").offset();	var x = e.pageX - offset.left;	var y = e.pageY - offset.top;	setColor(x,y)	$("#input").focus();   });			//form submit	$("form").submit(function() {		if(!($("#input").attr("disabled")))			addMessage($("#input").val(), hexToColor($("#input").css('color')));		return false;	});			//Input focus	$("#input").focus(function(){	if(eraseTextboxOnClick)	{		$("#input").val("");		$("#input").css("color", "#FFFFFF");	}	eraseTextboxOnClick = false;	});		//Konami code	$(document).keyup(function(e) {		var key = e.which;		var doKonami = true;		for(var i=0; i<konami.length-1; ++i)		{			if(konami[i] != keyHistory[i+1])  //Not the same keys, therefore the code is not good!				doKonami = false;			keyHistory[i] = keyHistory[i+1]; //'eating' the next key		}		keyHistory[keyHistory.length-1] = key;		doKonami = doKonami && keyHistory[keyHistory.length-1] == konami[konami.length-1];				if(doKonami)			showKonami();			});		/*******************	 *	Visual Effects	 ******************/	if($('#message-holder').length > 0)	{		//Hide everything		$(".textbox").hide();		$("#splash").hide();		$("#logo").hide();		$("#message-holder").hide();				//Show the splash		$("#splash").slideDown(1500);				//Wait 1.6s and show everything else		setTimeout("showContent()", 1600);		fetchMessages();		animate();		}		/*******************	 *	Facebook like	 ******************/	$("#facebooklike").html($('#message-holder').length == 0 ? '' : '<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.zloche.net%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=dark&amp;height=80" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:80px;" allowTransparency="true"></iframe>');}/////	Shows the contents. This is called a few seconds after the page has finished loading///function showContent(){	$('#logo').fadeIn(500);	$(".textbox").fadeIn(500);	$("#message-holder").fadeIn(500);}function showKonami(){	callService("action=konami", function(){})	var nb = Math.random() * 3 + 1;	for(var i=0; i<nb; ++i)	{		var timeout = Math.random() * 6000;		setTimeout('splashPaint();', timeout);	}}function splashPaint(){  var name = "paint_"+uniqid();  $("#paint").append("<div id='" + name + "'><img class='paint' src='" + konamiImage.url + "' alt='' />");  setTimeout('$("#sound").html(\'<embed src="'+konamiSound+'" hidden="true" autostart="true" loop="false" />\');', 500);  var obj = $("#"+name);  var img = $("#"+name+" img");  img.css('width', '0px');  img.css('height', '0px');  img.css('position', 'absolute');  img.css('top', (Math.random()*95) + 5 + "%");  img.css('left', (Math.random()*95) + 5 + "%");  img.css('margin-left', -konamiImage.w + 'px');  img.css('margin-top', -konamiImage.h + 'px');  img.animate({		"height": konamiImage.h + "px",		"width": konamiImage.w + "px",		"left": "-=" +  (konamiImage.w/2),		"top": "-=" +  (konamiImage.h/2)	  }, 500, function() {				img.animate({			"height": "1000%",			"top": "100%"		  }, 30000, function() {			obj.remove();		});			});}/////	This function is used to fetch new (or old, if there are no new) messaged from the server.///function fetchMessages(){	callService('action=getMessages&from='+lastID+'&count='+msgCount, function(data) {		//Process messages		  for(var i=1; i<data.length; ++i)		  	{				if(!data[i] == undefined)					continue;				lastID = data[i].id;				//Parsing colors, making sure they are visible enough.				data[i].color = processColor(data[i].color);				messages.push(data[i]); //adding the message to the queue			}						//Calculating when to fetch new messages.			var interval = (messages.length - 1) * messageQueueInterval;			interval = interval >= 2000 ? interval : 2000;			//Setting the timeout			setTimeout('fetchMessages()', interval);			animate();					});}/////	Sends a message to the server///function addMessage(text, color){		callService('action=addMessage&msg='+escape(text)+'&color='+escape(color), function(data) {			var status = '';			var statusColor = 0;			switch(data)			{				case -3: 							status="C'est un peu poche un message vide!";							statusColor = 0xff6600;							break;											case -2:							status='C\'est un peu r\u00E9p\u00E9titif ton affaire!';							statusColor = 0xff6600;							break;				case -1: 							status="Wow! P\u00E8se un peu moins vite sur les pitons!";							statusColor = 0xff6600;							break;				default:							status="Ton message est le #"+data+"!";							statusColor = 0x99ff00;			}						setStatus(status, statusColor)					});}/////	Animates and sets the current status message along with its color///function setStatus(text, color){	var oldColor = $("#input").css("color");	$("#input").attr("disabled", true);	$("#input").val(text);	$("#input").css("color","#"+colorToHex(color));	$("#input").css("letter-spacing","20px");	$("#input").animate({		"letterSpacing": '1px'	  }, 2500, function() {		setTimeout('unsetStatus("' + oldColor + '")', 3000);	});}/////	Animates the current status message, making it go away. It then enables #input and set focus() on it///function unsetStatus(color){	$("#input").blur()	$("#input").animate({		"textIndent": '100%'	  }, 500, function() {		$("#input").attr("disabled", false);		$("#input").val("");		$("#input").css("color",color);		$("#input").css("text-indent","-100%");		$("#input").focus();		$("#input").animate({"textIndent": '0%'}, 500);	});}/////	Asks the server which color the user has clicked on, processes it and sets it.///function setColor(x, y){	callService('action=getColorAt&x='+x+'&y='+y, function(data) {			$("#input").css('color', '#'+colorToHex(processColor(data)));		});}/////	This functions, when called, appends and prepends stuff required by teh service.///function processColor(color){	var color = parseInt(color); //Making sure it is treated as an integer	var rgb = {r: (color & 0xFF0000) >> 16, g: (color & 0x00FF00) >> 8, b: color & 0x0000FF};	var hsv = rgb2hsv(rgb.r, rgb.g, rgb.b);	hsv.v = hsv.v >= 25 ? hsv.v : 25;	rgb = hsv2rgb(hsv.h, hsv.s, hsv.v);	//Finally saving the color.	return (rgb.r << 16) + (rgb.g << 8) + rgb.b;}/////	This functions, when called, appends and prepends stuff required by teh service.///function callService(queryString, callback){	queryString = queryString=='' ? '?' : '?'+queryString+'&'; 	$.getJSON(gatewayURL+queryString+"rnd="+Math.random()+"&"+session, function(data) {		  session = data.session != '' ? data.session : session;		  if(data.type == 'error')		  	alert("Error:\n"+data.data);		  else		  	callback(data.data)		});}/////	Animates the text///function animate(){	if(animateTimeout != null)		clearTimeout(animateTimeout)	if(messages.length == 0)//avoiding animations that are not needed		return;	$("#message").fadeOut(500);	setTimeout("showNext()",500);	animateTimeout = setTimeout('animate()', messageQueueInterval);}/////	Changes the current message for the next one in the queue and makes it fade in///function showNext(){	if(messages.length == 0 && loadingMessages)//avoiding animations that are not needed		return;	loadingMessages = true;	var message="";	if(messages.length == 0 && lastID == 0)		message = "chargement des messages...";	else if(messages.length > 0)	{		loadingMessages = false;		message = '<span class="msgid">[#'+messages[0].id+']</span><span style="color: #'+colorToHex(messages[0].color)+';">'+$("<div />").text(messages[0].message).html()+'</span>';		messages.splice(0,1);	}	else		return;	$("#message").html(message);	$("#message").fadeIn(1000);}/////	Transforms a color # that is in decimal format to its hexadecimal value///function colorToHex(color){	color = color+"";	if(color.substr(0, 1) === 'r') //Assuming rgb(red, gre, blu)	{		var m = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(color);		return m ? (1 << 24 | m[1] << 16 | m[2] << 8 | m[3]).toString(16).substr(1) : color;	}	else		return zeroPad(parseInt(color).toString(16), 6)}/////	Transforms a color # that is in hexadecimal format to its decimal value///function hexToColor(hex){	hex = hex+""; //Treating it as a string		if(hex.substr(0, 1) === 'r') //Assuming rgb(red, gre, blu) (Temporary fix. I feel lazy right now.	{		var m = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(hex);		return m ? (m[1] << 16 | m[2] << 8 | m[3]).toString(10) : hex;	}	if(hex.length == 0)		return 0;	hex = hex.charAt(0) == '#' ? hex.substr(1) : hex;	return parseInt(hex, 16);}/////	Adds zeros to the given str/num if its length is smaller than <count>///function zeroPad(num,count){var numZeropad = num + '';while(numZeropad.length < count) {numZeropad = "0" + numZeropad;}return numZeropad;}function uniqid(){	var d= new Date();	return d.getTime();}
