// $Id: discuss.js 93 2006-09-10 18:30:31Z yosha_01 $

/////////////
// Discuss //
/////////////

var Discuss = Class.create();
Discuss.prototype = {

	initialize: function(discuss_id){

        // settings.
        this.discuss_id      = discuss_id;
        this.refreshInterval = 1500;

        // properties.
        this._ajax = new Discuss.Ajax(this.discuss_id);
                        
        // initialize form status.
        $('discuss_tarea').value = "";
        $('discuss_tarea').focus();
        this.changeButtonStatus();        

        // set event listeners.
        document.onkeyup    = this.changeButtonStatus.bindAsEventListener(this);
        document.onkeypress = this.sendMessageByKey.bindAsEventListener(this);
        $('discuss_send').onclick = this.sendMessageByButton.bindAsEventListener(this);
        
        // start timer.
        this.start();
         
    },
	
	start: function(){
        setTimeout(this.start.bind(this), this.refreshInterval);
        try{this._ajax.get(this.update);} catch(e){}
    },
	
    changeButtonStatus: function(){
        if($('discuss_tarea').value != ""){
            $('discuss_send').disabled = false;
        } else {
            $('discuss_send').disabled = true;
        }
    },
	
    sendMessageByKey: function(e){
        var element = Event.element(e);
        if (e.keyCode == 13 && element.name == 'discuss_tarea' && $('discuss_tarea').value != ""){
            //@TODO first enter-hit is not captured though input area is blank. not critical.
            this._ajax.post(this.messgage_id, this.update);
            $('discuss_tarea').value = "";
            this.changeButtonStatus();
            Event.stop(e);
        }
    },

    sendMessageByButton: function(){
        this._ajax.post(this.update);
        $('discuss_tarea').value = '';
        $('discuss_tarea').focus();
        this.changeButtonStatus();        
    },
    
    update: function(request){

        //for( var i in this ){ document.write(i); document.writeln("<br>"); }
        var xmlDoc  = request.responseXML;
        if (xmlDoc.documentElement) {

            /* Message Handling */

            var messages = xmlDoc.documentElement.childNodes[0];
            for(i = 0; i < messages.childNodes.length; i++){

                var message = new Discuss.Message();
                message.id      = messages.childNodes[i].childNodes[0].firstChild.data;
                message.uname   = messages.childNodes[i].childNodes[1].firstChild.data;
                message.message = String(messages.childNodes[i].childNodes[2].firstChild.data);
                message.color   = messages.childNodes[i].childNodes[3].firstChild.data;
                message.timestamp = String(messages.childNodes[i].childNodes[4].firstChild.data);

                if($('discuss_message_'+ message.id) == null){
                    message.show();
                    // and scroll down.
                    $('discuss_messages').scrollTop = $('discuss_messages').scrollHeight - $('discuss_messages').offsetHeight; 
                }
                //@TODO better destroy a message object.
            }

            /* Member Handling */

            var board = new Discuss.Board();

            var members = xmlDoc.documentElement.childNodes[1];
            for(i =0; i < members.childNodes.length; i++){
                var member = new Discuss.Board.Member();
                member.id    = members.childNodes[i].childNodes[0].firstChild.data;
                member.uname = members.childNodes[i].childNodes[2].firstChild.data;

                if(!board.has(member)){
                    member.join_on();
                }
            }
            // garbage collect.
            board.update();
        }
    }
}

//////////
// Ajax //
//////////

Discuss.Ajax = Class.create();
Discuss.Ajax.prototype = {

	initialize: function(disucuss_id){
        this.discuss_id = discuss_id;
	},

	get: function(handler){
    	var url = 'ajax_get.php';
    	var pars = 'discuss_id=' + this.discuss_id;	
    	var discussAjax = new Ajax.Request(url, {method: 'get', parameters: pars, onComplete: handler});
	},
	
	post: function(handler){
        var message = encodeURIComponent($('discuss_tarea').value);
        var color = '000000';
        for (i=1;;i++) {
            if (!$('color' + i)) break;
            if ( $('color' + i).checked == true){
                color = $('color' + i).value;
            }
        }
        var url = 'ajax_post.php';
        var pars = 'msg=' + message + '&discuss_id=' + this.discuss_id + '&color=' +color;
        var discussAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete: handler});
    }
}

/////////////
// Message //
/////////////

Discuss.Message = Class.create();
Discuss.Message.prototype = {

	initialize: function(){
    	this.message;
    	this.uname;
    	this.color;
    	this.timestamp;
	},
	
	show: function(){
	    var messageContainer = document.createElement('p');
	    messageContainer.id = 'discuss_message_'+this.id;

	    if (this.color!='' && this.color!='00000') {
		    messageContainer.style.color = "#"+this.color;
        }
		
	    var usernameContainer = document.createElement('b');
	    var usernameText = document.createTextNode(this.uname+": ");
	    usernameContainer.insertBefore(usernameText, null);
	    messageContainer.insertBefore(usernameContainer, null); 
	    	    
  	    var url = this.message.match(/((?:https?|ftp|news):\/\/[!~*'();\/?:\@&=+\$,%#\w.-]+)/g); //'
      	if(url){
            var messageText = this._hyperlink(String(url))
      	} else {
    		var messageText = document.createTextNode(this.message);
    	}
        messageContainer.insertBefore(messageText, null);
        
	    if(this.timestamp != "-"){
		    var timestampContainer = document.createElement('span');
		    timestampContainer.className = 'timestamp';
		    var timestampText = document.createTextNode('('+this.timestamp+')');
		    timestampContainer.insertBefore(timestampText,null);
		    messageContainer.insertBefore(timestampContainer,null);
	    }
        $('discuss_messages').insertBefore(messageContainer, null);
    },

    _hyperlink: function(url){
        var url_len = 50;
        var linkHref = document.createElement("a");
        linkHref.setAttribute('href', url);
        linkHref.setAttribute('target', '_blank');
        if(url.length > url_len){
            url = url.substr(0, 40) + '...';
        }
        var linkText = document.createTextNode(url);
        linkHref.appendChild(linkText);	
        return linkHref;
    }
}

////////////
// Member //
////////////

Discuss.Board = Class.create();
Discuss.Board.prototype = {

    initialize: function(){
        var board = $('discuss_members');
        this.members_stack = $A(board.getElementsByTagName('span'));
    },
    
    has: function(member){
        var flag = this.members_stack.find(function(member_in_stack){
           return (member_in_stack.id == 'discuss_member_' + member.id);
        });
        
        if(flag){
            this._delete_from_stack(member);
            return true;
        } else {
            return false;
        }
    },

    update: function(){    
 	    if(this.members_stack.length > 0){
		    this.members_stack.each(function(member_in_stack){
			    $('discuss_members').removeChild(member_in_stack);
		    });
	    }
    },

    _delete_from_stack: function(member){
        var index = null;
        this.members_stack.each(function(member_in_stack,i){
           if(member_in_stack.id == 'discuss_member_' + member.id){
               index = i;
           };
        });
        this.members_stack.splice(index,1);
    }

}

Discuss.Board.Member = Class.create();
Discuss.Board.Member.prototype = {

	initialize: function(id, uname){
	    this.id    = id;
	    this.uname = uname;
	},
    
    join_on: function(){
        var member_container = document.createElement("span");
        member_container.id = 'discuss_member_' + this.id;
        var member_text = document.createTextNode(this.uname + " ");
        member_container.insertBefore(member_text, null);
        $('discuss_members').appendChild(member_container);        
    }
}

/////////////
// Command //
/////////////

Discuss.Command = Class.create();
Discuss.Command.prototype = {

	initialize: function(){
	    // Not implemented yet.
	}
}

///////////
// Debug //
///////////

Discuss.Debug = Class.create();
Discuss.Debug.prototype = {

	initialize: function(mode){
    if(mode == true){
            var debug_container = document.createElement("div");
            debug_container.id = 'discuss_debug';
            document.body.appendChild(debug_container); 
            debug_w = $('discuss_debug');   
	    }
    },

    show: function(message){
            var messageContainer = document.createElement("div");
            var messageText = document.createTextNode(now.toLocaleString()+" : "+message);
            messageContainer.insertBefore(messageText, null);
            var br = document.createElement("br");   
            messageContainer.insertBefore(br, null);         
            debug_w.appendChild(messageContainer);
	}
	
}