
var yg_chat = {
    refresh: 0,
    lastActivity: 0,
    currentTime: 0,
    activeUserRefresh: 2000,
    inactiveUserRefresh: 10000,
    away: 10,
    waitingForResponse: false,

    init: function(currentTS)
    {
        this.refresh = this.inactiveUserRefresh;
        this.currentTime = currentTS;
        this.lastActivity = this.currentTime;
        this.getData();
        intervalID = setInterval('yg_chat.getData()', this.refresh);
    },

    activeUser: function()
    {
        if(this.refresh != this.activeUserRefresh && typeof(intervalID) !== 'undefined')
        {
            this.refresh = this.activeUserRefresh;
            clearInterval(intervalID);
            intervalID = setInterval('yg_chat.getData()', this.refresh);
        }
        this.lastActivity = this.currentTime;
    },

    getData: function()
    {
        if(this.refresh < this.inactiveUserRefresh && this.currentTime-this.lastActivity > this.away)
        {
            this.refresh = this.inactiveUserRefresh;
            clearInterval(intervalID);
            intervalID = setInterval('yg_chat.getData()', this.refresh);
        }
        this.getUsersAndMessages();
        this.currentTime = this.currentTime + Math.round(this.refresh/1000);
    },

    getUsersAndMessages: function()
    {
        if(this.waitingForResponse == true)
            return;

        this.waitingForResponse = true;
        var usersAndMessagesBlock = new yRemote();
        usersAndMessagesBlock.onLoad = function(status, data)
        {
            if(status == 200 && data !== null)
            {
                if(data.success)
                {
                    yg_chat.displayUsers(data.users);
                    yg_chat.displayMessages(data.messages);
                }
                yg_chat.waitingForResponse = false;
            }
        }
        usersAndMessagesBlock.post('/services/chat/getUsersAndMessages.php', '');
        return true;
    },

    displayUsers: function(users)
    {
        if(typeof(users) == 'object' && users !== null)
        {
            var connectedUsers = new Array();
            var displayedUsers = $$('div.game_chatRoom_userList_user');

            // Check if hash is empty by verifying if the type of first value is "function"
            if(typeof($H(users).values().first()) != 'function')
            {
                $H(users).each(function(pair) {
                    if(!$('game_chatRoom_userList_user_'+pair.key))
                        yg_chat.insertUser(pair.key, pair.value);
                    else
                        yg_chat.updateUser(pair.key, pair.value);
                    connectedUsers.push(pair.key);
                });
            }

            // Remove timed out users
            for(var i=0; i < displayedUsers.length; i++)
            {
                if(connectedUsers.indexOf(displayedUsers[i].readAttribute('value')) == -1)
                    displayedUsers[i].remove();
            }

            if(connectedUsers.length == 0)
                $('game_chatRoom_users').innerHTML = 'no user connected';
            else
            {
                if(connectedUsers.length == 1)
                    $('game_chatRoom_users').innerHTML = '1 user connected';
                else
                    $('game_chatRoom_users').innerHTML = connectedUsers.length+' users connected';
            }
            $('game_chatRoom_users').show();
        }
    },

    displayMessages: function(messages)
    {
        if(typeof(messages) == 'object' && messages !== null)
        {
            for(var i=0; i < messages.length; i++)
            {
                var id = messages[i].id;
                var author = messages[i].author;
                var message = messages[i].message;
                var idElt = messages[i].idElt;

                if(!$('game_chatRoom_messageList_message_'+idElt))
                    yg_chat.insertMessage(id, author, message);
            }
        }
    },

    sendMessage: function(login, message)
    {
        if(message == '')
            return false;

        var id = Math.round(Math.random()*100000);

        var messageDiv = new Element('div', { id: 'game_chatRoom_messageList_message_'+id }).addClassName('game_chatRoom_messageList_message');

        var link = new Element('a', {
            href: '/people/'+login+'/',
            title: 'user\'s profile',
            target:'_blank'
        }).update(login);
        messageDiv.appendChild(link);
        messageDiv.innerHTML += ':&nbsp;'+message.escapeHTML();

        $('game_chatRoom_messageList').appendChild(messageDiv);
        $('game_chatRoom_messageList').scrollTop = $('game_chatRoom_messageList').scrollHeight;
        $('game_chatRoom_messageComposer_box').clear();

        var messageBlock = new yRemote();
        messageBlock.onLoad = function(status, data)
        {
            if ( status == 200 && data !== null )
            {
                if(data.success == false)
                    $('game_chatRoom_errorNotice').update('An error occured while sending your message');

                $('game_chatRoom_messageComposer_box').focus();
            }
        }

        var args = {
            message: message,
            id: id
        }

        messageBlock.post('/services/chat/sendMessage.php', args);
        return true;
    },

    insertUser: function(login, infos)
    {
        if(!$('game_chatRoom_userList_user_'+login))
        {
            var userDiv = new Element('div', { id:'game_chatRoom_userList_user_'+login, value:login }).addClassName('game_chatRoom_userList_user');
            var space = document.createTextNode(' ');

            if(infos.picture)
            {
                var img = new Element('img', { src: 'http:\/\/data.pictogame.com\/'+infos.picture, height: 18, width: 18 });
                img.setStyle({ 'verticalAlign': 'bottom' });
                userDiv.appendChild(img);
                userDiv.appendChild(space);
            }

            var userLink = new Element('a', {
                href: '/people/'+login+'/',
                title: 'user\'s profile',
                target: '_blank'
            }).update(login);
            userLink.addClassName('game_chatRoom_userList_userLink');
            userDiv.appendChild(userLink);

            if(infos.gameName && infos.gameUrl)
            {
                var span = new Element('span', {});
                span.setStyle({'fontSize' : '0.8em'});

                var url = '/play/game/'+infos.gameUrl;

                var gameLink = new Element('a', {
                    id: 'game_chatRoom_userList_user_'+login+'_playing',
                    href: url,
                    title: infos.gameName,
                    target: 'blank'
                }).update(infos.gameName);

                var gameSpan = new Element('span', {}).update('playing&nbsp;');
                gameSpan.addClassName('grey');

                span.appendChild(document.createTextNode(' ('));
                span.appendChild(gameSpan);
                span.appendChild(gameLink);
                span.appendChild(document.createTextNode(') '));
                userDiv.appendChild(span);
            }

            $('game_chatRoom_userList').appendChild(userDiv);
        }
    },

    updateUser: function(login, infos)
    {
        if($('game_chatRoom_userList_user_'+login+'_playing'))
        {
            if(infos.gameName && infos.gameUrl)
            {
                $('game_chatRoom_userList_user_'+login+'_playing').setAttribute('href', infos.gameUrl);
                $('game_chatRoom_userList_user_'+login+'_playing').setAttribute('title', infos.gameName);
                $('game_chatRoom_userList_user_'+login+'_playing').update(infos.gameName);
            }
        }
    },

    insertMessage: function(id, author, message)
    {
        if(!$('game_chatRoom_messageList_message_'+id))
        {
            var messageDiv = new Element('div', { id: 'game_chatRoom_messageList_message_'+id }).addClassName('game_chatRoom_messageList_message');

            var link = new Element('a', {
                href: '/people/'+author+'/',
                title: 'user\'s profile',
                target: '_blank'
            }).update(author);
            messageDiv.appendChild(link);
            messageDiv.innerHTML += ':&nbsp;'+message;

            $('game_chatRoom_messageList').appendChild(messageDiv);
            $('game_chatRoom_messageList').scrollTop = $('game_chatRoom_messageList').scrollHeight;
        }
    },

    selectRoom: function(room)
    {
        if(room)
        {
            var roomBlock = new yRemote();
            roomBlock.onLoad = function(status, data)
            {
                if ( status == 200 && data !== null )
                {
                    if(data.success)
                    {
                        $('game_chatRoom_messageList').update();
                        yg_chat.getUsersAndMessages();
                    }

                    if(element = $('game_chatRoom_roomSelection'))
                        new Effect.toggle('game_chatRoom_roomSelection', 'blind')
                }
            }

            var args = {
                room: room
            }

            roomBlock.post('/services/chat/selectRoom.php', args);
            return true;
        }
    }
};


