(function($) { 
 $.chatSupportChannel =function(options) {
    this.options = $.extend({}, $.chatSupportChannel.DEFAULTS, options || {});  
	this.win = false;
    this.channel = options.token;
    this.members = options.members;
	this.messageCounter = 0;
	this.lastMessage    = "";
	this.timer          = 0;
	this.initiated      = false;
	this.ttimer         = 0;
	this.messages       = [];
	this.popwin         = false;
	this.offlineDialog  = false;		
    this.creatLayout();    
    var self = this; 
    this.editor = new $.chatEditor(this.win.getContent().find("textarea"),{channel: this.channel,  button: this.win.getContent().find("input.send"), typeSend: 0 });
    this.showMember();
};

jQuery.extend($.chatSupportChannel, {    
    DEFAULTS: {ispopout:false }
});

$.chatSupportChannel.prototype= {
    status:function(s){
       if(s){
          this.win.getContent().find("div.status").html(s);
       }
    },	
	creatLayout:function(){
	    var popstr = '';
		if(this.options.ispopout) 
		   popstr= '<a href="javascript:void(0);" class="popin"><img src="/im/images/popin.gif" alt="pop in"></img></a>';
		else 
		  popstr = '<a href="javascript:void(0);" class="popout"><img src="/im/images/popout.gif" alt="pop out"></img></a>';
			
		var commandbar = '<ul class="statusbar lt_statusbar">';
		    commandbar += '<li class="mute"><img src="/im/images/mute.gif" alt="" onclick="parent.chat.mute(this);" /></li>';
		    commandbar += '<li class="pop">'+popstr+'</li>';
		    commandbar += '<li class="status"><div class="status"></div></li>'
		var content = '<div class="names member"></div>';
            content += '<div class="channel">';
            content += '<div class="messages">';
            content += '<div class="messages_content"></div>';
            content += commandbar;
            content+= ' </div><div class="send"><textarea class="editor" style="z-index:10003" ></textarea></div></div>';
 
	   var self = this;
       this.win = new Boxy("<div>"+content+"</div>", { title: 'CellSwapper.com Live Transfer',beforeUnload:function(){  	       
	          self.initiated=false;
	          self.left();
	       return true;
	   }});
	   
	},

	serialize:function(){
	   this.win.unload();
	   return this;
	},
	
	changeStatus:function(s){
	   if(this.editor) 
	      this.editor.enable();
	   if(this.to!=null) {
	      if(s == 1){
		     this.setTitle('<img src="/im/images/available_white1.gif" alt="" />'+this.to.Name);
           }else if(s == 2){
		     this.setTitle('<img src="/im/images/idle_white1.gif" alt="" />'+this.to.Name);
           } else if(s == 3){
	            this.setTitle('<img src="/im/images/busy_white1.gif" alt="" />'+this.to.Name);
	       }else if(s == 4){
	           this.setTitle('<img src="/im/images/idle_white1.gif" alt="" />'+this.to.Name);
	       }else if(s== 99){
	           this.setTitle('<img src="/im/images/offline_white1.gif" alt="" />'+this.to.Name);
	           this.disable();
	       }
	   }
	},
	
	disable:function(){
	   if(this.editor)this.editor.disable();
	},
	
	add: function(message) {
	    this.messages.push(message);
		if (this.messageCounter >= 500) {
			for (var i = 0 ; i < 10 ; i++) {
				$(this.divMsgContent).removeChild($(this.divMsgContent).firstChild);
			}
			this.messageCounter -= 10;
		}
		if(message!=null)
		    this.lastMessage = message;  
		if(this.timer>0)   window.clearTimeout(this.timer);	
		
		this.add2(message);
	},

	member: function(Id) {
		for (i = 0; i < this.members.length; i++) {
			if (this.members[i].Id == Id) {
				return this.members[i];
			}
	    }
		return undefined;
	},
	
	remove:function(Id){
	   for (i = 0; i < this.members.length; i++) {
			if (this.members[i].Id == Id) {
			var r  = this.members[i]
				this.members.splice(i,1);
				return r ;
			}
	    }
	    return false;
	},
	
	indexOf:function(Id){
	   	for (i = 0; i < this.members.length; i++) {
			if (this.members[i].Id == Id) {
				return i;
			}
	    }
		return -1;
	},
	
	formatMember:function(member){
	  var r = member.Name + "(";
	  if(member.Role == "admin"){
	       r+="Support";
	  } 
	  else r+= "Visitor";
	  
	  if(member.Role != "admin")
	      r+=  member.Id +")";
	  else r+=")";
	  return r;
	},
	
	showMember:function(){
	   var e = this.win.getContent().find(".member").html('');
	   var self = this;
	   $(this.members).each(function(i){
	      var m = $(this).get(0);
	      e.append($("<span />").html('<img src="/images/online.png" alt=""/>' + self.formatMember(m)));
	   });
	},
	
	onJoin:function(member){
	     if( this.indexOf(member.Id)<0)
	        this.members.push(member);
	     chat.add(this.channel, '<span class="notice">Notice : '+this.formatMember(member)+' has joined.</span>');
	     this.showMember();
	},
	
	onLeft:function(uid){
	     var m = this.remove(uid);
	     if(!m) return;
	     chat.add(this.channel, '<span class="notice">Notice : '+this.formatMember(m)+' has left.</span>');	  
	        
	     this.showMember();
	  
	},
	left:function(){
	   chat.removeChannel(this.channel);
       $.postJSON("/live.ashx",{action: "left", Id: chat.account.Id, channel: this.channel });
	},
	
     onTyping:function(from){
         this.status(this.member(from).Name + " is typing... ");
         var self = this;
         this.ttimer = window.setTimeout(function(){self.status('&nbsp');},5000);
     },
     
     toggleTyping:function(){
        this.status("&nbsp;");
        clearTimeout(this.ttimer);
     },
   
	add2:function(){		
		var msgs = this.win.getContent().find(".messages_content");
        msgs.append($("<div />").html(this.lastMessage).addClass("message"));
        var last = msgs.find("div:last");
        if (last.offset())
            msgs.attr("scrollTop", last.offset().top);
        this.messageCounter++;
        $(".live .title-bar").addClass("title-on");
	},
	toString:function(){
	    var content = '  ' ;
        for(i=0;i<this.members.length;i++){
	       content+= ', '+  this.formatMember(this.members[i]);
	    }
	    
	    return content;
	}
}

function onMessage(channel) {
    chat.current = channel;
	var msg = jQuery( 'channel_input_message_' + channel).value;
	if (msg && msg != '') {
		chat.message(msg);
	}
}
	
 
})(jQuery);