var nick;
var pass;
var status;
var myIp;

// -------------------------------------
// Boot loader
// -------------------------------------

$(function(){
	if (readCookie('banned') == 'yes')
	{
		alert('Vous etes banni');
		//for(;;);
		return;
	}
	
    $messages = $('.messages ul');
    $users = $('.users ul');
    $message = $('#message');
    $login = $('#login');
    $overlay = $('#overlay');
    $window = $(window);
    $infobar = $('.infobar');
    $bubble = $('.bubble');
    $sheepSay = $('#sheepSay');
    $sun = $('#sun');

    $('.formMessage').submit(listenerSendMessage);
    $('form', $login).submit(listenerLogin);

    promptLogin();

    //cloud1();
    //cloud2();
    //bubble('coucou');
    //sheepSay('Bienvenue ! Cliquez sur l\'herbe pour bouger !', 10000);
});

// -------------------------------------
// Colline
// -------------------------------------

function cloud1()
{
    var time = 10000;
    with($('#cloud1'))
    {
        animate({opacity:Math.random()}, time);
        animate({right:'+='+((50*Math.random())-25)}, time, cloud1);
    }
}
function cloud2()
{
    var time = 10000;
    with($('#cloud2'))
    {
        animate({opacity:Math.random()}, time);
        animate({left:'+='+((50*Math.random())-25)}, time, cloud2);
    }
}

// -------------------------------------
// Interface
// -------------------------------------

var $messages;
var $users;
var $message;
var $login;
var $overlay;
var $window;
var $infobar;
var $bubble;
var $sheepSay;
var $sun;

// http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines
var tabColors = ['#c4a000', '#ce5c00', '#8f5902', '#4e9a06', '#204a87', '#5c3566', '#555753'];
var modoColor = '#B61F1F';
var usersColor = {};

function promptLogin()
{
	if (readCookie('login') != 'null') $login.find('input[name=username]').val(readCookie('login'));
    $overlay.show();
    $login.show();

    var top = $window.height()/3-$login.height()/2;
    var left = $window.width()/2-$login.width()/2;
    $login.css('top', top);
    $login.css('left', left);
}
function setInfobar(info)
{
    $infobar.text(info);
}
function addUser(nickName, moderator, ip)
{
    nickText = moderator ? '★'+nickName : nickName;

    if (status >= 2)
    {
		//var kickL = $('<a/>').click(function(){kick(ip).text('K');});
		//var banL = $('<a/>').click(function(){banByIP(ip).text('B');});
		//var $line = $('<li/>').append(kickL).append('<span> </span>').append(banL).append('<span> </span>').append('<span>'+nickText+'</span>');
		var $line = $('<li><a href="#" onclick="kick(\''+ip+'\',\''+nickName+'\');return false;">K</a><a href="#" onclick="banByIP(\''+ip+'\');return false;">B</a> '+nickText+'</li>')
			.css('color', moderator ? modoColor : 'black');
    }
	else
	{
		var $line = $('<li/>')
			.text(nickText)
			.css('color', moderator ? modoColor : 'black');
	}

    $users.append($line);
}
function removeUsers()
{
    $users.empty();
}

function noHTML(html)
{
    html = html.replace('<', '&lt;');
    html = html.replace('<', '&lt;');
    return html;
}
var smileysPath = '/tchat/smileys/';
var smileysArray = [
    [ "attention.gif", ":!:" ],
    [ "banned.gif", ":ban:" ],
    [ "smile.gif", ":-)" ],
    [ "sad.gif", ":-(" ],
    [ "wink.gif", ";-)" ],
    [ "grin.gif", ":-D" ],
    [ "tongue.gif", ":-p" ],
    [ "cool.gif", "B-)" ],
    [ "blush.gif", ":-$" ],
    [ "cry.gif", ":'(" ],
    [ "rolleyes.gif", "8-)" ],
    [ "surprised.gif", ":oO:" ],
    [ "suspicious.gif", ":hein:" ],
    [ "eek.gif", ":oh:" ],
    [ "twisted.gif", ":666:" ],
    [ "thumbsup.gif", ":bien:" ],
    [ "argh.gif", ":arg:" ],
    [ "banghead.gif", ":mur:" ],
    [ "drool.gif", ":bave:" ],
    [ "wise.gif", ":ah:" ],
    [ "shrug.gif", ":tantpis:" ],
    [ "love.gif", ":love:" ],
    [ "buttrock.gif", ":buttrock:" ],
    [ "notworthy.gif", "^O^" ]
];
function useSmileys(msg)
{

    for (var i=0, smiley; smiley=smileysArray[i]; i++) {
        var regex = smiley[1].replace(/(\(|\)|\$|\?|\*|\+|\^|\[|\.|\|)/gi, "\\$1");
        re = new RegExp(regex, 'gi');
        msg = msg.replace(re, '<img src="'+smileysPath+''+smiley[0]+ '" alt="" />');
    }

    return msg;
}
function colorFor(nick, moderator)
{
    if (nick in usersColor)
    {
        return usersColor[nick];
    }
    else if (moderator)
    {
        return usersColor[nick] = modoColor;
    }
    else
    {
        var r = Math.round(Math.random()*(tabColors.length-1));
        return usersColor[nick] = tabColors[r];
    }
}

function addMessage(time, nick, msg, moderator)
{
    if (moderator && msg.match(/\/sheep .+/))
    {
        sheepSay(msg.substr(6, msg.length-6));
        return;
    }

    msg = noHTML(msg);
    msg = useSmileys(msg);
    
    var color, nickShow;
    if (msg.match(/\/me .+/))
    {
        color = 'black';
        msg = msg.substr(3, msg.length-3);
        nickShow = nick;
    }
    else
    {
        color = colorFor(nick, moderator);
        nickShow = moderator ? '★'+nick : nick;
        nickShow += ': ';
    }

    var $time = $('<span/>')
        .attr('title', time)
        .addClass('time')
        .css('color', color)
        .text('('+time+') ');

    var $nick = $('<span/>')
        .addClass('nick')
        .css('color', color)
        .text(nickShow)
        .click(function(){
            $message.val(nick+' > '+$message.val());
            $message.focus();
        });

    var $msg = $('<span/>')
        .addClass('message')
        .html(msg);

    var $line = $('<li/>')
        .append($time)
        .append($nick)
        .append($msg);

    $messages.append($line);
}
function scrollBottom()
{
    $messages.parent().scrollTop(99999);
}
function removeMessages()
{
    $messages.empty();
}

function listenerSendMessage()
{
    var message = $message.val();
    if (!message)
    {
        focusMessage();
        return false;
    }

    sendMessage(message);
    removeMessage();
    focusMessage();

    return false;
}
function listenerLogin()
{
    var username = $login.find('input[name=username]').val();
    var password = $login.find('input[name=password]').val();
    
    username = username.replace(/ /g, '');

    if (!username)
    {
        alert('Hum c\'est vide comme pseudo...');
        return false;
    }
	
	if (!/^[a-z0-9-_]{2,15}$/i.test(username))
	{
        alert('Le pseudo peut faire de 2 à 15 caractères, des lettres, des chiffres, - et _');
        return false;
	}

    login(username, password);

    return false;
}
function removeMessage()
{
    $message.val('');
}
function focusMessage()
{
    $message.focus();
}
function restart()
{
    window.location.reload();
}
function hideLogin()
{
    $overlay.hide();
    $login.hide();
}
function bubble(html)
{
    $bubble
        .show()
        .find('.content')
        .html(html);

    $bubble
        .css('top', 10)
        .css('left', 10)
        .animate({opacity:1}, 1000);

    //$bubble.animate({opacity:0}, 1000);
}
function sheepSay(text, d)
{
	if (!d) d = 3000;
    $sheepSay
        .css('opacity', 1)
        .show()
        .find('.content')
        .text(text);

    setTimeout(function(){
        $sheepSay.animate({opacity:0}, 1000);
    }, d);
}

// -------------------------------------
// AJAX logic
// -------------------------------------

var urlLogin = 'http://www.i-tchat.com/api/login.php?idShoutbox=657&callback=?';
var urlMessages = 'http://www.i-tchat.com/api/messages.php?idShoutbox=657&callback=?';
var urlUsers = 'http://www.i-tchat.com/api/users.php?idShoutbox=657&callback=?';
var urlPost = 'http://www.i-tchat.com/api/post.php?idShoutbox=657&callback=?';
var urlBan = 'http://www.i-tchat.com/api/ban.php?idShoutbox=657&callback=?';
var urlKick = 'http://www.i-tchat.com/api/kick.php?idShoutbox=657&callback=?';

var timerMessages;
var timerUsers;
var minIdMessage = 0;

var refreshMessages = 10000;
var refreshUsers = 3000;

function logout()
{
    clearInterval(timerMessages);
    clearInterval(timerUsers);
    nick = null;
    pass = null;
    status = null;
}
function login(username, password)
{
    var url = urlLogin
        + '&username=' + encodeURIComponent(username)
        + '&password=' + encodeURIComponent(password);

    $.getJSON(url, function(data){
        if ('username' in data && data.status > -1)
        {
            nick = data.username;
            pass = password;
            status = data.status;
			myIp = data.ip;

            loadMessages();
            loadUsers();
            hideLogin();
            Comet.init('mouton', cometHandler);
			addCookie('login', nick, 60*60*24*7);
            game_init();
			//enter_in_the_world(nick);
			getMovie().setNick(nick);

            //timerMessages = setInterval(loadMessages, refreshMessages);
            //timerUsers = setInterval(loadUsers, refreshUsers);
        }
        else if (data.error)
        {
			log('erreur ' + data.error);
            errorHandler(data.error);
        }
    });
}

function loadUsers()
{
    clearInterval(timerUsers);
    timerUsers = setInterval(loadUsers, refreshUsers);

    var url = urlUsers
        + '&username=' + encodeURIComponent(nick)
        + '&password=' + encodeURIComponent(pass);

    $.getJSON(url, function(data){
        if (data.ok)
        {
            var users = data.users;
            removeUsers();
            setInfobar(users.length + ' connectés');
            $.each(users, function(i, obj){
                addUser(obj.pseudo, obj.status==2, obj.ip);
            });
        }
        else if (data.error)
        {
            errorHandler(data.error);
        }
    });
}

function loadMessages()
{
    clearInterval(timerMessages);
    timerMessages = setInterval(loadMessages, refreshMessages);

    var url = urlMessages
        + '&username=' + encodeURIComponent(nick)
        + '&password=' + encodeURIComponent(pass)
        + '&minIdMessage=' + minIdMessage;

    $.getJSON(url, function(data){
        if (data.ok)
        {
            var messages = data.messages;
            if (minIdMessage == 0)
                removeMessages();
            messages.reverse();
            $.each(messages, function(i, obj){
                if (minIdMessage < obj.idMessage)
                {
                    minIdMessage = obj.idMessage;
                    addMessage(obj.time, obj.username, obj.message, obj.status==2);
                }
            });
            scrollBottom();
        }
        else if (data.error)
        {
            errorHandler(data.error);
        }
    });
}

function sendMessage(message)
{
    var url = urlPost
        + '&message=' + encodeURIComponent(message)
        + '&username=' + encodeURIComponent(nick)
        + '&password=' + encodeURIComponent(pass);
    $.getJSON(url, function(data){
        if (data.ok)
        {
            loadMessages();
            Comet.send({type:'msg_notif'});
			try{socket.send({message: message});}catch(e){}
        }
        else if (data.error)
        {
            errorHandler(data.error);
        }
    });
}

function banByIP(ip)
{
    if (!confirm('Bannir '+ip+' pour 5h ? (abus = plus modo)'))
    {
        return;
    }

    var url = urlBan
        + '&ip=' + ip
        + '&username=' + encodeURIComponent(nick)
        + '&password=' + encodeURIComponent(pass);
    $.getJSON(url, function(data){
        if (data.ok)
        {
            alert('Fait.');
        }
        else if (data.error)
        {
            errorHandler(data.error);
        }
    });
}

function kick(ip, name)
{
    if (!confirm('Kicker '+ip+' ? (actualiser sa page avec un message)'))
    {
        return;
    }
	var why2 = prompt('Raison du kick :');
	if(!why2) why2 = 'pas de raison';
	Comet.send({type:'kick', ip:ip, by:nick, why:why2, name:name});
	
	var url = urlKick
        + '&ip=' + ip
        + '&username=' + encodeURIComponent(nick)
        + '&password=' + encodeURIComponent(pass);
    $.getJSON(url, function(data){
        if (data.ok)
        {
            alert('Fait.');
        }
        else if (data.error)
        {
            errorHandler(data.error);
        }
    });
}

function errorHandler(error)
{
    switch(parseInt(error))
    {
        case 1: alert('Mauvais mot de passe'); break;
        case 2: alert('Attention au flood'); break;
        case 3: alert('Vous etes banni'); addCookie('banned', 'yes', 60*60*5); restart(); break;
        case 4: alert('Pseudo déjà utilisé'); break;
        case 5: alert('Pseudo non conforme [a-z0-9-_]{2,15}'); break;
    }
}

// Cookie
function addCookie(name, value)
{
    var argv=addCookie.arguments;
    var argc=addCookie.arguments.length;
    var expires=(argc > 2) ? argv[2] : null;
	if (expires)
	{
		date = new Date();
		date.setTime(date.getTime() + expires * 1000);
		expires = date;
	}
    var path=(argc > 3) ? argv[3] : null;
    var domain=(argc > 4) ? argv[4] : null;
    var secure=(argc > 5) ? argv[5] : false;
    document.cookie=name+"="+escape(value)+
    ((expires==null) ? "" : ("; expires="+expires.toGMTString()))+
    ((path==null) ? "" : ("; path="+path))+
    ((domain==null) ? "" : ("; domain="+domain))+
    ((secure==true) ? "; secure" : "");
}

function getCookieVal(offset)
{
    var endstr=document.cookie.indexOf (";", offset);
    if (endstr==-1) endstr=document.cookie.length;
    return unescape(document.cookie.substring(offset, endstr));
}

function readCookie(name)
{
    var arg=name+"=";
    var alen=arg.length;
    var clen=document.cookie.length;
    var i=0;
    while (i<clen)
    {
        var j=i+alen;
        if (document.cookie.substring(i, j)==arg) return getCookieVal(j);
        i=document.cookie.indexOf(" ",i)+1;
        if (i==0) break;
    }
    return null;
}

// flash
function getMovie()
{
	// from chatroulette.com
	var M$ =  navigator.appName.indexOf("Microsoft")!=-1
	return (M$ ? window : document)["movieFlash"];
}

// -------------------------------------
// Comet
// -------------------------------------

function cometHandler(data, time)
{
    if (!data || !data.type) return;

    if (data == 'refresh' || data.type == 'msg_notif')
    {
        loadMessages();
    }
    else if (data.type == 'move')
    {
        game_move(data.to);
    }
    else if (data.type == 'kick')
    {
	    var $line = $('<li/>').text(data.by+' a kické '+data.name+' ('+data.why+')');
		$messages.append($line);
        if(data.ip == myIp)
		{
			alert(data.by+' vous a kicke, raison : '+data.why);
			restart();
		}
    }
	else if (data.type == 'maj')
    {
		if (data.msg == undefined) data.msg = 'mise a jour :)';
		//alert(data.msg);
		//restart(); JB faut trouver mieux que ça
    }
    else
    {
        //loadMessages();
    }
}

// -------------------------------------
// UI/jeu
// -------------------------------------

var xMax;

function game_init()
{
    // 37 - left
    // 38 - up
    // 39 - right
    // 40 - down
    //$(document).keydown(function(e){
    //    if (e.keyCode == 37) {
    //        comet.send({type: 'move', to: 'left'});
    //        return false;
    //    } else if (e.keyCode == 39) {
    //        comet.send({type: 'move', to: 'right'});
    //        return false;
    //    }
    //});
    xMax = $(document).width();
    $(document).click(function(e){
        var xMouse = e.pageX;

        // Pourcentage à envoyer : 0-100
        var pc = parseInt(xMouse/xMax*100, 10);
        //Comet.send({type: 'move', to: pc}); => chiant
    });
}

function game_move(to)
{
    // Partie trigo
    // x: -PI/2  0  +PI/2
    // y:     0  1  0
    var x = (to - 50) / 50 * Math.PI / 2;
    var y = Math.cos(x);

    // Partie interface
    var left = to/100 * xMax;
    var top = 200 - y * 200 - 20;
    $sun.animate({left: left, top: top}, 1000);
}

// personnage

function Skin()
{
	var img = 'http://www.ape-project.org/demos/mmo/img/0'+(Math.round(Math.random()*6+1))+'.png';
	var dirs = {'bottom':0, 'left':1, 'right':2, 'top':3};
	var dir = 'bottom';
	var frame = 0;
	var $skin = $('<div/>').
		appendTo('#video').
		css('position', 'absolute').
		css('float', 'left').
		css('bottom', 0);
	var $text = $('<div/>').appendTo($skin).text('coucou').css('opacity', 0.5);
	var $skinn = $('<div/>').
		width('32px').
		height('48px').
		appendTo($skin);
	
	this.update = function(state)
	{
		if (state.yv)
		{
			if (state.yv > 0) dir = 'right';
			else if (state.yv < 0) dir = 'left';
		}
		else
		{
			frame = 0;
		}
		
		$text.text(state.nick);
		var top = dirs[dir]*48;
		var left = (parseInt(frame/5, 10)%4)*32;
		$skinn.css('background', 'url('+img+') -'+left+'px -'+top+'px');
		$skin.css('left', state.y+'px');
		
		frame++;
	};
	this.remove = function()
	{
		$skin.remove();	
	};
}

function Perso(nick)
{
	this.skin = new Skin();
	var self = this;
	this.state = {
		y: parseInt(Math.random()*940),
		yv: 0,
		nick: nick
	};
	
	this.update = function()
	{
		if (this.state.yv)
		{
			if (this.state.yv > 0 && this.state.y < 940 || this.state.yv < 0 && this.state.y > 0 ) this.state.y += this.state.yv;
		}
		this.skin.update(this.state);
	};
	this.change = function(state){};
	this.play = function(yv)
	{
		this.state.yv = yv*2;
		this.change(this.state);
	};
	this.stop = function()
	{
		this.state.yv = 0;
		this.change(this.state);
	};
	this.setState = function(state)
	{
		this.state = state;
	};
}

function time()
{
	return (new Date()).getTime();	
}

var myBody;
var socket;
var persos = {};
function enter_in_the_world2(nick)
{
	/*
	socket = new WebSocket('ws://r15082.ovh.net:8080/');
	socket.onmessage = function(data){
		log('message : '+data.data);
		var buffer = $.json.decode(data.data);
		for (var id in buffer)
		{
			var state = $.json.decode(buffer[id]);
			if (nick != state.nick)
			{
				if (!(id in persos))
				{
					persos[id] = new Perso(state.nick);
					persos[id].setState(state);
				}
				else
				{
					persos[id].setState(state);
				}
			}
		}
		for (var id in persos)
		{
			if (!(id in buffer))	
			{
				persos[id].skin.remove();
				delete persos[id];
			}
		}
	};
	socket.onopen = function(){
		myBody = new Perso(nick);
		myBody.change = function(state)
		{
			socket.send($.json.encode(state));
		};
		socket.send($.json.encode(myBody.state));
		setInterval(function(){
			for (id in persos)
			{
				persos[id].update();
			}
			myBody.update();
		}, 33);
	};

	var down37 = false;
	var down39 = false;
	$(document).keydown(function(event){
		switch (event.keyCode) {
			case 37:
				if (!down37)
				{
					myBody.play(-1);//moveLeft();
					down37 = true;
				}
				break
			case 38:
				//moveUp();
				break;
			case 39:
				if (!down39)
				{
					myBody.play(1);//moveRight();
					down39 = true;
				}
				break;
			case 40:
				//moveDown();
				break;
		}
	});
	$(document).keyup(function(event){
		switch (event.keyCode) {
			case 37:
				myBody.stop();//moveLeft();
				down37 = false;
				break
			case 38:
				//moveUp();
				break;
			case 39:
				myBody.stop();//moveRight();
				down39 = false;
				break;
			case 40:
				//moveDown();
				break;
		}
	});*/
};
//enter_in_the_world('gege'+time());
