///////////////////////////////////
//         ajax im 3.41          //
//    AJAX Instant Messenger     //
//   Copyright (c) 2006-2008     //
//    http://www.ajaxim.com/     //
//   Do not remove this notice   //
///////////////////////////////////


/**
 * ChatHistory Class
 **/

var ChatHistory = {
    
   windows: {},    

   /**
    *
    * create a  ChatHistoryWindow instance
    *
    * @argument recipient (string) - the recipient of the Chat History
    * 
    * @argument chatroom (boolean) - whether is a chatroom or IM history window
    *
    * @author Augusto Mathias Adams <superflankerCTBA@gmail.com>
    * 
    **/
   
   create: function(recipient,chatroom) {
      
        var imLeft = Math.round(Math.random()*(Browser.width()-360))+'px';
        
        var imTop  = Math.round(Math.random()*(Browser.height()-400))+'px';
        
        var winId = randomString(32) + '_chathistory';
        
        var imTitle = '';
        
        if(typeof(chatroom)=='undefined'){
            
            //that means an im chat history
            
            chatroom = false;
            
        }
        
        if(chatroom==true){
          
            imTitle = Languages.get('chatHistory').replace('%',recipient);
          
        }else{
            
            imTitle = Languages.get('imHistory').replace('%%',recipient).replace('%',user);
            
        }
        
        this.windows[recipient] = new ChatHistoryWindow({id: winId, className: "dialog", width: 475, height: 340, top: imTop, left: imLeft,minimizable:false,maximizable:false, resizable: false, title: imTitle, draggable: true, detachable: false, minWidth: 475, minHeight: 150, showEffectOptions: {duration: 0}, hideEffectOptions: {duration: 0}});
        
        this.windows[recipient].setConstraint(true, {left: 0, right: 0, top: 0, bottom: 0});
        
        this.windows[recipient].getContent().innerHTML = '<div class="rcvdMessages" id="' + winId + '_rcvd"></div>' + "\n" +
                                                     '<div class="imToolbar" id="' + winId + '_toolbar" onmousemove="return false;" onselectstart="return false;">' + "\n" +
                                                     ' <a href="#" id="' + winId + '_first" onclick="ChatHistory.windows[\'' + recipient + '\'].first();return false;" onselectstart="return false;">'+Languages.get('firstPage')+'</a>&nbsp;'+
                                                     ' <a href="#" id="' + winId + '_prev" onclick="ChatHistory.windows[\'' + recipient + '\'].prev();return false;" onselectstart="return false;">'+Languages.get('prevPage')+'</a>&nbsp;'+
                                                     ' <a href="#" id="' + winId + '_next" onclick="ChatHistory.windows[\'' + recipient + '\'].next();return false;" onselectstart="return false;">'+Languages.get('nextPage')+'</a>&nbsp;'+
                                                     ' <a href="#" id="' + winId + '_last" onclick="ChatHistory.windows[\'' + recipient + '\'].last();return false;" onselectstart="return false;">'+Languages.get('lastPage')+'</a>'+
                                                     '</div>';
        
        this.windows[recipient].setRecipient(recipient);
        
        this.windows[recipient].setChatroom(chatroom);
        
        this.windows[recipient].last();
        
        $(winId + '_rcvd').setStyle({marginTop: '5px', height: (this.windows[recipient].getSize().height - 30) + 'px', width: (this.windows[recipient].getSize().width - 10) + 'px'});
        
        $(winId + '_toolbar').setStyle({marginTop: '5px', top:   (this.windows[recipient].getSize().height ) + 'px', width: (this.windows[recipient].getSize().width - 10) + 'px'});
        
        this.windows[recipient].show();
        
        this.windows[recipient].toFront();
        
        Windows.focusedWindow = this.windows[recipient];
        
   },
   
   /**
    *
    * Process ChatHistoryWindow window resize
    *
    * @arguments
    *   recipient(string) - ChatHistoryWindow recipient
    *
    * @author Augusto Mathias Adams
    * 
    **/
   
    handleResize: function(recipient) {
        
        if(!isNull(this.windows[recipient])){
            
            if(!isNull(this.windows[recipient].getId)){
                
                var winId = this.windows[recipient].getId();
                
                $(winId + '_rcvd').setStyle({marginTop: '5px', height: (this.windows[recipient].getSize().height - 103) + 'px', width: (this.windows[recipient].getSize().width - 20) + 'px'});
                
                $(winId + '_toolbar').setStyle({marginTop: '5px', top:   (this.windows[recipient].getSize().height - 73) + 'px', width: (this.windows[recipient].getSize().width - 20) + 'px'});
                
            }
            
        }
        
    },

    /**
     *
     * opens a chat history window
     *
     * @argument recipient (string) - the recipient of the Chat History
     * 
     * @argument chatroom (boolean) - whether is a chatroom or IM history window
     *
     * @author Augusto Mathias Adams <superflankerCTBA@gmail.com>
     * 
     **/
    
    openHistory: function(recipient,chatroom){
        
        if(isNull(ChatHistory.windows[recipient])){
            
            ChatHistory.create(recipient, chatroom);
            
        } else {
            
            if(!ChatHistory.windows[recipient].isVisible()) {
                
               ChatHistory.windows[recipient].show();
               
               ChatHistory.windows[recipient].last();
               
            }
            
        }
    },
    
   /**
    *
    * parses a page retrieved from server
    *
    * @argument
    *   room - room recipient user is entering
    *   response - data from the requested page
    *
    * @author Augusto Mathias Adams
    * 
    **/
   
    parseHistory: function(room,response) {
      
        if(!isNull(ChatHistory.windows[room])){
            
            if(!isNull(ChatHistory.windows[room].getId)){
                
                var winId = ChatHistory.windows[room].getId();
                
                //the window who receives the history messages
                
                ChatHistory.windows[room].setPage(response.page);
                
                ChatHistory.windows[room].setPages(response.pages);
                
                var messageCount = (typeof(response.messages) !== 'undefined' ? response.messages.length : 0);
                
                //the recv Box on a IM
                
                var curIM = $(winId + '_rcvd');
                
                //save the content of IM Box
                
                //fill the box with the history messages
                
                if(!isNull(curIM)){
                    
                    curIM.innerHTML = '';
                    
                    if(messageCount==0){
                        
                        curIM.innerHTML = '<span class="imHistory">'+Languages.get('noHistory')+'</span><br />';
                        
                        return true;
                        
                    }
                    
                    for(var i =0; i< messageCount; i++){
                        
                        var from = response.messages[i].sender;
                        
                        var data = response.messages[i].message;
                        
                        var stamp = response.messages[i].stamp;
                        
                        data = data.replace(/(\s|\n|>|^)(\w+:\/\/[^<\s\n]+)/, '$1<a href="$2" target="_blank">$2</a>');
                        
                        data = IM.emoteReplace(data, smilies);
                        
                        if(data.replace(/<([^>]+)>/ig, '').indexOf('/me') == 0){
                            
                            curIM.innerHTML += "<b class=\"user" + (from == user && ChatHistory.windows[room].chatroom ? 'A' : 'B') + "\">" + IM.getTimestamp(stamp) + " <i>" + from + ' ' + data.replace(/<([^>]+)>/ig, '').replace(/\/me/, '') + "</i></b><br>\n";
                            
                        }else{
                            
                            curIM.innerHTML += "<b class=\"user" + (from == user && ChatHistory.windows[room].chatroom ? 'A' : 'B') + "\">" + IM.getTimestamp(stamp) + " " + from + ":</b> " + data + "<br>\n";
                            
                        }
                        
                        curIM.scrollTop = curIM.scrollHeight - curIM.clientHeight + 6;
                        
                    }
                    
                    curIM.scrollTop = curIM.scrollHeight - curIM.clientHeight + 6;
                    
                    curIM = null;
                    
                }
                
            }
          
        }
        
        return true;
      
    }
   
};

/**
 *
 * ChatHistory Window Class
 * 
 * @author Augusto Mathias Adams
 * 
 **/

var ChatHistoryWindow = Class.create();
Object.extend(ChatHistoryWindow.prototype, IMWindow.prototype);
Object.extend(ChatHistoryWindow.prototype, {
    page: 1, //actual page viewed by the user
    pages: 1,//the number of pages that chat history contains

    /*
     *
     * sets the recipient of the chat history
     *
     * @argument recipient (string) - the name of the recipient
     *
     * @author Augusto Mathias Adams
     *
     */
    
    setRecipient: function(recipient){
        
        this.recipient = recipient;
        
    },
    
    /*
     *
     * set whether is a chatroom or not
     *
     * @argument chatroom (boolean) - whether a chat history window is a chat history or not
     *
     * @author Augusto Mathias Adams
     *
     */
    
    setChatroom: function(chatroom){
        
        this.chatroom = chatroom;
        
    },
    

    /*
     *
     * sets the atual page retrieved from the server
     *
     * @argument page (integer) - the age retrieved fro the server
     *
     * @author Augusto Mathias Adams
     *
     */
    
    setPage: function(page){
        
        this.page = page;
        
    },
    
    /*
     *
     * sets the number of pages in the chat history
     *
     * @argument pages (integer) - the total pages in the chat history
     *
     * @author Augusto Mathias Adams
     *
     */
    
    setPages: function(pages){
        
        this.pages = pages;
        
    },
    
    /*
     *
     * gets the first page of the history
     *
     * @author Augusto Mathias Adams
     *
     */
    
    first: function(){
        
        var recipient = this.recipient;
        
        this.page = 1;
        
        var xhConn = new XHConn();
        
        xhConn.connect(pingTo, "POST", "call=wholehistory&recipient="+recipient+"&page=1&chatroom="+(this.chatroom == true? 1:0),
            
            function(xh) {
                
                var response = xh.responseText.parseJSON();
                
                ChatHistory.parseHistory(recipient,response);
               
            });
        
        
    },
    
    /*
     *
     * gets the previous page of the history
     *
     * @author Augusto Mathias Adams
     *
     */
    
    prev: function(){

        var recipient = this.recipient;
        
        var prevpage = this.page - 1;
        
        if(prevpage<1){
            
            prevpage = 1;
            
        }
        
        this.page = prevpage;
        
        var xhConn = new XHConn();
        
        xhConn.connect(pingTo, "POST", "call=wholehistory&recipient="+recipient+"&page="+prevpage+"&chatroom="+(this.chatroom == true? 1:0),
            
            function(xh) {
                
                var response = xh.responseText.parseJSON();
                
                ChatHistory.parseHistory(recipient,response);
               
            });
        
    },
    
    /*
     *
     * gets the next page of the history
     *
     * @author Augusto Mathias Adams
     *
     */
    
    
    next: function(){
        
        var recipient = this.recipient;
        
        var nextpage = this.page + 1;
        
        if(nextpage>this.pages){
            
            nextpage = this.pages;
            
        }
        
        this.page = nextpage;
        
        var xhConn = new XHConn();
        
        xhConn.connect(pingTo, "POST", "call=wholehistory&recipient="+recipient+"&page="+nextpage+"&chatroom="+(this.chatroom == true? 1:0),
            
            function(xh) {
                
                var response = xh.responseText.parseJSON();
                
                ChatHistory.parseHistory(recipient,response);
               
            });
        
    },
    
    last: function(){
        
        var recipient = this.recipient;
        
        this.page = this.pages;
        
        var xhConn = new XHConn();
        
        xhConn.connect(pingTo, "POST", "call=wholehistory&recipient="+recipient+"&page=last&chatroom="+(this.chatroom == true? 1:0),
            
            function(xh) {
                
                var response = xh.responseText.parseJSON();
                
                ChatHistory.parseHistory(recipient,response);
               
            });
        
    }
});