SoundBox =
{
	soundId : 0,
	makeSoundBox : function(soundId)
	{
		if (soundId > 0 && soundId <= 3)
		{
			this.soundId = soundId;
			
			var obj = new Swiff('flash/soundBox.swf', {
				id: 'soundBoxItem',
				width: 0,
				height: 0,
				params: {
					wmode: 'transparent'
				}
			});
			$(document.body).adopt(obj);
		}
		else
		{
			this.soundId = 0;
		}
	},
	playSound : function()
	{
		if (this.soundId != 0)
		{
			window.document.soundBoxItem.GotoFrame(this.soundId);
			window.document.soundBoxItem.GotoFrame(0);
		}
	}
}

function makeSmileyPanel()
{
	var smileyPanel = new Element('div', {id: 'smileys'});
	$(document.body).adopt(smileyPanel);
	smileysArray.each(function(item, index){
		if (index%5 == 0 && index != 0)
		{

			var br = new Element('br');
			smileyPanel.adopt(br);
		}
		
		var smiley  = new Element('img', {src:smileysPath+item[1],title:item[0],alt:item[0]});
		smileyPanel.adopt(smiley);
	});
}

RequestFactory =
{
	isReady : true,
	
	setBusy : function()
	{
		this.isReady = false;
		$('refresh').addClass('load');
	},
	setReady : function()
	{
		$('refresh').removeClass('load');
		this.isReady = true;
	},
	
	doRequest : function(argsObj, handler)
	{
		if (!this.isReady) return;
		else RequestFactory.setBusy();
		
		var jsonRequest = new Request.JSON({url: "update.php", onComplete: handler}).POST(argsObj);
		jsonRequest.chain(function(){RequestFactory.setReady()});
	}
}

var Field = new Class({
	field : null,
	isBlinking : false,
	
	initialize : function(idName){
        this.field = $(idName);
    },
	blink : function()
	{
		if(this.isBlinking) return;
		else this.isBlinking = true;
		
		var color = this.field.getStyle('border-left-color');
		var myFx = new Fx.Tween(this.field, {duration:100});
		var thisField = this;
		myFx.start('border-color', '#f00').chain(
			function(){this.start('border-color', color);},
			function(){this.start('border-color', '#f00');},
			function(){this.start('border-color', color);},
			function(){thisField.isBlinking = false;}
		);	
	},
	getField : function()
	{
		return this.field;
	},
	getValue : function()
	{
		return this.field.value;
	},
	setValue : function(value)
	{
		this.field.value = value;
	},
	isEmpty : function()
	{
		return (this.field.value=='');
	},
	focus : function()
	{
		this.field.focus();
	},
	clear : function()
	{
		this.field.value = '';
	}
});

var usernameField = new Field('username');
var messageField = new Field('message');


function refreshShoutbox(e)
{
	e.stop();
	
	var updateInfos = {
		idShoutbox:idShoutbox,
		lastMessage:lastMessage
	}
	
	RequestFactory.doRequest(updateInfos, updateShoutbox);
}

function postMessage(e)
{
	e.stop();
	
	if(usernameField.isEmpty())
	{
		usernameField.blink();
		return;
	}
	if(messageField.isEmpty())
	{
		messageField.blink();
		return;
	}
	
	var longWord = checkLongString(messageField.getValue());
	if (longWord != null)
	{
		alert('\''+longWord+'\' est un mot trop long !');
		messageField.blink();
		return;
	}
	
	var postInfos = {
		idShoutbox : idShoutbox,
		lastMessage : lastMessage,
		username : usernameField.getValue().clean(),
		message : messageField.getValue().clean()
	}
	
	if (RequestFactory.isReady)
	{
		messageField.clear();
		RequestFactory.doRequest(postInfos, updateShoutbox);
	}
}

function updateShoutbox(shoutbox)
{
	if (shoutbox.error != undefined)
	{
		handleUpdateError(shoutbox.error);
		return;
	}
	
	var newLiveCount = shoutbox.livecount;
	var objLiveCount = $('livecount');
	if (newLiveCount > 1) objLiveCount.innerHTML = newLiveCount + ' connectés';
	else objLiveCount.innerHTML = newLiveCount + ' connecté';
	
	updateMessages(shoutbox.messages);
}

function handleUpdateError(error)
{
	alert('Erreur : ' + error);
}

function updateMessages(messages)
{
	var msgList = $('messages');
	for (var i=0; i<messages.length; i++)
	{
		var curMsg = messages[i];
		
		if (lastMessage >= curMsg.idMessage) continue;
		else lastMessage = curMsg.idMessage;
		
		curMsg.user = HTMLEncode(curMsg.user)+': ';
		curMsg.msg = messageFormatter(HTMLEncode(curMsg.msg));
		
		var li 		= new Element('li', {id: 'p'+curMsg.idMessage});
		var cite 	= new Element('cite', {title: curMsg.ip, html: curMsg.user});
		var q 		= new Element('q', {html: curMsg.msg});
		var span 	= new Element('span', {html: curMsg.date});
		
		li.adopt(cite);
		li.adopt(q);
		li.adopt(span);
		
		msgList.adopt(li);
		highlightLastPost();
		SoundBox.playSound();
		ScrollBottom.fxScroll();
	}
}

function HTMLEncode(text)
{
	text = text.replace(/&/gi, "&amp;");
	text = text.replace(/"/gi, "&quot;");
	text = text.replace(/</gi, "&lt;");
	text = text.replace(/>/gi, "&gt;");
	text = text.replace(/'/gi, "&#146;");
	return text;
};


function messageFormatter(res)
{
	var regex = /([^ ]{1,10}:\/\/[^ ]*)/gi;	
	res = res.replace(regex, "<a href=\"$1\" target=\"_blank\">&laquo;lien&raquo;</a>");

	for (var i = 0; i < smileysArray.length; i++)
	{
		var regex = smileysArray[i][0].replace(/(\(|\)|\$|\?|\*|\+|\^|\[|\.|\|)/gi, "\\$1");
		re = new RegExp(regex, 'gi');
		res = res.replace(re, '<img src="'+smileysPath+smileysArray[i][1]+'" alt="'+smileysArray[i][0]+'" />');
	}

	var regex = /([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+(\.[-a-z0-9]+)*\.[a-z]{2,6})/gi;
	res = res.replace(regex,"<a href=\"mailto:$1\">&laquo;email&raquo;</a>");
	
	return res;
}

function convertTxt2ImgNLink()
{
	var postList = $('messages').getElements('li').each(function(el){
		var msg = el.getElements('q')[0];
		var content = messageFormatter(msg.get('html'));
		msg.set('html', content);
	});
}

function checkLongString(string)
{
	/* Delete links and emails */	
	var regex = /((http|https|ftp|mms|sop|tvu):\/\/[^ ]*)/gi;	
	string = string.replace(regex, "");
	var regex = /([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+(\.[-a-z0-9]+)*\.[a-z]{2,6})/gi;
	string = string.replace(regex,"");
	
	/* Analyze every words */
	var strings = string.split(' ');
	var answer = false;
	for (var i=0; i < strings.length; i++)
	{
		if (strings[i].length > 18) return strings[i];
	}
	
	return null;
}

function highlightLastPost()
{
	var lastPost = $$('li:last-child');
	var lastPostId = new String(lastPost.getProperty('id'));
	
	new Fx.Morph(lastPostId).set('.highlightOn');
	new Fx.Morph(lastPostId, {duration: 1000}).start('.highlightOff');
	return;
	
	var lastPost = $$('li:last-child');
	lastPost.highlight();
	return;
	var color = lastPost.getStyle('background-color');
	var myFx = new Fx.Tween(new String(lastPost.getProperty('id')), {duration:400});
	
	myFx.start('background-color', '#FFFFBB').chain(
		function(){this.start('background-color', color);}
	);
}

var myFx = new Fx.Scroll('content', {duration: 250});
/*function scrollBottom()
{
	myFx.cancel();
	myFx.toBottom();
}*/
var ScrollBottom =
{
	content : $('content'),
	myFx : new Fx.Scroll('content', {duration: 250}),
	quickScroll : function()
	{
		var c = this.content; 
		setTimeout(function(){c.scrollTop=c.scrollHeight;}, 0);
		setTimeout(function(){c.scrollTop=c.scrollHeight;}, 50);
		setTimeout(function(){c.scrollTop=c.scrollHeight;}, 150);
	},
	fxScroll : function()
	{
		this.myFx.cancel();
		this.myFx.toBottom();
	}
}

var SmileyPanel =
{
	hidden : true,
	moving : false,
	toggle : function()
	{
		if (this.moving) return;
		else this.moving = true;
		
		var morph = new Fx.Morph('smileys', {duration: 'short', transition: Fx.Transitions.Quint.easeOut});
		
		if(this.hidden)
		{
			this.hidden = false;
			morph.start({
				right: '0'
			}).chain(function(){SmileyPanel.moving = false;});
		}
		else
		{
			this.hidden = true;
			morph.start({
				right: -$('smileys').getSize().x
			}).chain(function(){SmileyPanel.moving = false;});
		}	
	}
}

function toggleSmileys(e)
{
	e.stop();
	SmileyPanel.toggle();
}

function smileyToField(smile)
{
	if (messageField.isEmpty()) messageField.setValue(smile + ' ');
	else if (messageField.getValue().test("\\s$")) messageField.setValue( messageField.getValue() + smile + ' ' );
	else messageField.setValue( messageField.getValue() + ' ' + smile + ' ' );
	messageField.focus();
}

// Initialize shoutbox
var domreadynow = false;
window.addEvent('domready', function() {
	if (domreadynow) return;
	
	convertTxt2ImgNLink();
	makeSmileyPanel();
	SoundBox.makeSoundBox(soundId);
	
	//setTimeout(function(){var c=$('content'); c.scrollTop=c.scrollHeight;}, 0);/* IE hack */
	ScrollBottom.quickScroll();
	
	$('smileys').getElements('img').addEvents({
		'click': function(){
			smileyToField(this.getProperty('alt'));
			SmileyPanel.toggle();
		}
	});
	
	$('more').addEvent('click', toggleSmileys);
	$('send').addEvent('click', postMessage);
	$('refresh').addEvent('click', refreshShoutbox);
});