
function RoomObject(id, name, title){
    this.id = id;
    this.name = name;
    this.lower_name = name.toLowerCase();
    this.title = title;
    this.topic = "";
    
    this.chatters = {};
    this.is_privmsg = strpos(name, '__pv')?true:false;


    this.nb_unread = 0;
    this.span_unread = $('a[href$=tabs-' + id + '] span.unread', $tabs);

    this.isHL = false;

    this.__highlight = function(){
        if( !this.isHL ){
            var elt = $('a[href$=tabs-'+this.id+']').parent();
            var elt_id = this.id;
            var self = this;
            this.isHL = true;
            var lmbd = function(){
                var index = Room.findIndexById(elt_id);
                var selected = $tabs.tabs('option', 'selected');
                if(index != selected ){
                    elt.effect('highlight', {}, 1000, lmbd );
                }
                else{
                    self.isHL = false;
                }
            }
            lmbd();
        }
    }

    this.__incUnread = function(){
        if( $firstLoad == 1 ){
            return;
        }


        this.nb_unread++;
        this.__getSpanUnread().html('[' + this.nb_unread + ']');
        
        //elt.effect('highlight', {}, 'slow', );
        this.__highlight();
    }

    this.__getSpanUnread = function(){
        if( this.span_unread == null || this.span_unread.length == 0){
            this.span_unread = $('a[href$=tabs-'+this.id+'] span.unread', $tabs);
        }

        return this.span_unread;
    }

    this.__resetUnread = function(){
        this.nb_unread = 0;
        this.__getSpanUnread().html('');
    }

    this.addMessage = function(message_id, message, incUnread, debug_id){
        var index = Room.findIndexById(this.id);
        var selected = $tabs.tabs('option', 'selected');

        var isText = $('.text', message).length > 0;
        var nickname = $(message).find('span.nickname span').text();
        var me = $(Global.NickInput).val();

        if( index != selected && isText && (incUnread == undefined || incUnread == true) ){
            if( me != nickname ){
                this.__incUnread();
            }
        }

        if( isText && me != nickname){
            $WM.incUnread(1);
        }
        
        var htmlMessage = message;
        var li = $('<li>' + htmlMessage + '</li>');
        $(li).attr('id', message_id);

        if( debug_id ){
            $(li).attr('debug_id', debug_id);
        }
        li = this.__parseMessage(li);

        if( nickname ){
            $('span.nickname span', li).css('color', $WM.colorize(nickname));
        }

        var messages = $('#messages-' + this.id);
        var canScroll = false;
        //debug(this.id + "[" + index + "," + selected + "] can scroll ?" + messages.canScroll());
        if( index == selected){
            //debug(this.name + " can scroll ?" + messages.canScroll());
            canScroll = messages.canScroll();
        }

        $('#tabs-' + this.id + ' .messages').append(li);
        this.clearHistory();

        if( canScroll ){
            messages.scrollBottom();
        }
    }

    this.__parseMessage = function(li){
        var me = $(Global.NickInput).val();
        var author = $('span.nickname span', li).html();
        if( author == me ){
            return li;
        }
        var exp = new RegExp("\\b" + me + "\\b", "gi")

        if( $('span.text', li).length == 1){

            var text = $('span.text', li).html().replace(exp, '<b>' + me + '</b>');
            $('span.text', li).html( text );


        }
        //debug('li = ' + xmlentities(li.html()) );
        return li;
    }

    this.addChatter = function(chatter_id, chatter_nickname){
        var ul_id = '#tabs-' + this.id + ' .users';
        chatter_id = 'chatter_' + this.id + '_' + chatter_id;
        var elt_id = '#' + chatter_id;

        //debug("html=" + $(elt_id).html() +', chatter=[' + chatter_nickname + ',' + chatter_id + ']');

        if( !$(elt_id).html() ){
            var li = $('<li id="' + chatter_id + '">' + chatter_nickname + '</li>');
            li.css('color', $WM.colorize($(li).html()));
            $(ul_id).append(li);
        }
        else{
            if( $(elt_id).html() != chatter_nickname ){
                $(elt_id).css('color', $WM.colorize($(elt_id).html()));
                $(elt_id).html(chatter_nickname);
            }
        }

        this.__addChatter(chatter_id, $(elt_id).html());

    }


    this.__addChatter = function(chatter_id, chatter_nickname){
        if( this.chatters[chatter_id] == undefined ){
            debug('Adding chatter : < ' + chatter_id + ', ' + chatter_nickname + '>');

            this.chatters[chatter_id] = {
                'nickname' : chatter_nickname
            };
            Autocompletor.set(this.getNicknames());
        }
        else if( this.chatters[chatter_id].nickname != chatter_nickname ){
            debug('Adding chatter : < ' + chatter_id + ', ' + chatter_nickname + '>');
            this.chatters[chatter_id].nickname = chatter_nickname;
            Autocompletor.set(this.getNicknames());
        }

    }

    this.removeChatter = function (chatter_id){
        debug('Removing chatter : < ' + chatter_id + '>');
        this.__removeChatter(chatter_id);
        
        chatter_id = 'chatter_' + this.id + '_' + chatter_id;
        var elt_id = '#' + chatter_id;

        if( $(elt_id).length != 0 ){
            $(elt_id).remove();

            Autocompletor.set(this.getNicknames());
        }
    }

    this.__removeChatter = function(chatter_id){
        if( this.chatters[chatter_id] != undefined ){
            this.chatters[chatter_id] = undefined;
        }
    }

    this.getNicknames = function(){
        var res = [];
        for( var i in this.chatters ){
            var elt = this.chatters[i];
            if( elt != undefined && elt.nickname != undefined){
                res.push(elt.nickname);
            }
        }
        return res;
    }

    this.clearHistory = function(){
        var messages = $('#tabs-' + this.id + ' .messages').find('li');

        if( messages.length > Room.maxHistory ){
            var toDelete = messages.length - Room.maxHistory;
            var i = 0;
            messages.each(function(){
                if( i < toDelete ){
                    $(this).remove();
                }
                i++;
            });
        }
    }

    this.setActive = function(){
        this.__resetUnread();
        Autocompletor.set(this.getNicknames());
    }

    this.setTopic = function(topic){
        if( topic != this.topic ){
            if( topic != ""){
                this.topic = topic;
                $('#topic-' + this.id).html(topic);
                $('#topic-' + this.id).show();
            }
            else{
                this.topic = topic;
                $('#topic-' + this.id).hide();
            }
            $WM.resizeChat();
        }
    }
}

var Room = {
    activeRoom: null,
    maxHistory: 1000,

    __toScroll: {},
    __scrollPos: {},
    __scrollMax: {},
    
    __rooms: {},
    
    buildId: function(room_id, dieze){ // plus de flexibilie future
        var prefix = '#';
        if( dieze == false || dieze == undefined){
            prefix = '';
        }
        return prefix + 'tabs-' + room_id;
    },

    __extractId: function(id){
        return id.replace('#tabs-', '');
    },

    __getIdFromName: function(room_name){
        for( var it in Room.__rooms){
            var elt = Room.__rooms[it];
            if( elt.name == room_name ){
                return it;
            }
        }
        return undefined;
    },

    __getNameFromId: function(room_id){
        var room = Room.getRoomFromId(room_id);
        if( room != undefined ){
            return room.name;
        }
        return undefined;
    },

    getRoomFromId: function(room_id){
        if( Room.__rooms[room_id] != undefined ){
            return Room.__rooms[room_id];
        }
        return undefined;
    },

    getRoomFromName: function(room_name){
        for( var it in Room.__rooms){
            var elt = Room.__rooms[it];
            if( elt.name == room_name ){
                return elt;
            }
        }
        return undefined;
    },

    findIndexById: function(room_id){
        if( Room.__rooms[room_id] != undefined){
            if( $( Room.buildId(room_id, true) + ' .messages').length > 0){
                var li = $('a[href$=' + Room.buildId(room_id, false) + ']', $tabs).parent('li');
                return $('#tabs > ul > li').index(li);
            }
        }
        return -1;
    },

    findIndexByName: function(room_name){

        var room_id = Room.__getIdFromName(room_name);
        if( room_id == undefined ){
            return -1;
        }

        return Room.findIndexById(room_id);
    },

    add: function(room_id, room_name, room_title){
        if( Room.__rooms[room_id] == undefined){
            debug( "Room.add(" + room_id + ", " + room_name + ', ' + room_title + ')' );
            $tabs.tabs('add', Room.buildId(room_id, true) , room_title);
            Room.__rooms[room_id] = new RoomObject(room_id, room_name, room_title);;

            if( Cookie.get('display_users') == 'false'){
                if( Cookie.get('display_users') == 'false' ){
                    $('td.userslist').hide();
                }
            }
        }
        else {
            var elt = $('a[href$=tabs-'+room_id+'] span.title');
            if( elt.html() != room_title && room_title != ''){
                elt.html(room_title);
                Room.__rooms[room_id].title = room_title;
            }
        }
        return Room.__rooms[room_id];
    },
    remove: function(room_id, room_name){
        var index = Room.findIndexById(room_id);
        if( index >= 0){
            $tabs.tabs('remove', index);
            Room.__rooms[room_id] = undefined;
        }
    },

    set: function(room_id, room_name){

        var room  = Room.getRoomFromId(room_id);

        if( room_name == undefined ){
            room_name = room.name;
        }
        $(Global.RoomInput).attr('value', room_name);

        room.setActive();
        Room.activeRoom = room;
        Cookie.set('activeRoom', room_id);
        $WM.resizeChat(true);
    },

    setActive: function(room_id){
        //var index = Room.findIndex(room_name);
        debug('trying to set active:' + room_id);
        var index = Room.findIndexById(room_id);
        var room_name = Room.__getNameFromId(room_id);

        debug("setActive " + room_name + " => index=" + index);
        
        if( index >= 0 && room_name != undefined ){
            $tabs.tabs('select', index);
            Room.set(room_id, room_name);
        }
    },

    addMessageToCurrentRoom: function(message){
        var room = Room.activeRoom;
        var li = $('<li>' + message + '</li>');
        $('#tabs-' + room.id + ' .messages').append(li);
        $('#messages-' + room.id).scrollBottom();
    },


    dummy: null
};

