/**
 * @author hasan
 */
 var chat_timer=false;
(function($){
	$.Comet = function(){
		$.Comet.connect();
	};
	
	$.extend($.Comet,{
		settings: {
	      timestamp     : 0,
	      url      		: './pages/chat_server.php',
	      noerror 		: true
		},
	  	initialize : function() { },
	
	  	connect: function()
	  	{
			if(chat_timer)
			{
			 $.ajax({
			   type: "post",
			   url: $.Comet.settings.url,
			   data: "timestamp="+new Date().getTime(),
			   complete: function(response)
			   {
			   		if (!$.Comet.settings.noerror)
		          // if a connection problem occurs, try to reconnect each 5 seconds
			          	setTimeout(function(){ $.Comet.connect() }, 5000); 
			        else
			          	$.Comet.connect();
			        $.Comet.settings.noerror = false;
			   },
			   success: function(response){
			   	try {
					$.Comet.handleResponse(response);
					$.Comet.settings.noerror = true;
				}
				catch(e)
				{
					return false;
				}
			   }
					
			 });
			}
			 
	  	},
	
		disconnect: function()
		{
		},
		
		handleResponse: function(response)
		{
			var user_id = $.evalJSON(response).from_id;
			var user_username = $.evalJSON(response).from_username;
			var msg_time = $.evalJSON(response).time;
			NewChat(user_id,user_username);
			if(msg_time)
			{
				$('#chat_float_'+user_id+' .text').append('<div class="chat-det">'+msg_time+' - <strong>' +user_username+'</strong></div><div>'+ $.evalJSON(response).msg + '</div>');
			}
			else
			{
				$('#chat_float_'+user_id+' .text').append('<div><strong>' +user_username+'</strong> :</div><div>'+ $.evalJSON(response).msg + '</div>');
			}
			$('#chat_float_'+user_id+' .text div').scrollTo('div:eq(10)',1000);
			
		},
		doRequest: function(to)
		{
			if(chat_timer)
			{
			var msg = jQuery.trim($('#chat_float_'+to+' .msg').val());
			if(msg)
			{
				$('#chat_float_'+to+' .msg').val('');
				$.ajax({
				   type: "post",
				   url: $.Comet.settings.url,
				   data: "to="+to+"&msg="+msg,
				   success: function(response){
						try {
							$.Comet.handleResponse(response);
							$.Comet.settings.noerror = true;
						}
						catch(e)
						{
							return false;
						}
				   }
				 });
			}
			}
		}  
	})
})(jQuery);
