﻿Type.registerNamespace('messer');
messer.messerChat = function(element) {
    messer.messerChat.initializeBase(this, [element]);
    this._btnSendclickDelegate = null;
    this._editorKeyPressDelegate = null;
    this._publishChatDelegate = null;
    
    this._markUserDelegate = null;
    this._refreshChatDelegate = null;
    this._clientSideTextChangedDelegate = null;
    this._btnBanclickDelegate = null;
    this._openPopUpChatDelegate = null;
    this.TabModuleId = 0;
    this.refreshRate = 5000;
    this.msgsList = null;
    this.userList = null;
    this.editor = null;
    this.chkScroll = null;
    this.chkSound = null;
    this.uColorPick = null;
    this.btnSend = null;
    this.roomList = null;
    this.btnBan = null;
    this.chatTimer = null;
    this.markedUser = null;
    this.btnPopUp = null;
}

messer.messerChat.prototype.initialize = function() {
    this.btnSend = $get(this.btnSend);
    this.userList = $get(this.userList);
    this.msgsList = $get(this.msgsList);
    this.chkScroll = $get(this.chkScroll);
    this.roomList = $get(this.roomList);
    this.uColorPick = $get(this.uColorPick);
    this.chkSound = $get(this.chkSound);
    Messer.Modules.MesSerChat.MesSerChatService.set_defaultFailedCallback(this.ChatErrorHandler);

    //var oDimsPal = new dnn.dom.positioning.dims(this.msgsList);
    //this.msgsList.style.width = oDimsPal.w + "px";

    this.uColorPick.value = this.uColorPick.value || this.uColorPick.style.backgroundColor;
    if (this._publishChatDelegate === null) {
        this._publishChatDelegate = Function.createDelegate(this, this.publishChat);
    }
    
    if (this._markUserDelegate === null) {
        this._markUserDelegate = Function.createDelegate(this, this.markUser);
    }
    if (this._refreshChatDelegate === null) {
        this._refreshChatDelegate = Function.createDelegate(this, this.refreshChat);
    }
    $addHandler(this.roomList, 'change', this._refreshChatDelegate);

    if (this._btnSendclickDelegate === null) {
        this._btnSendclickDelegate = Function.createDelegate(this, this._btnSendclickHandler);
    }
    $addHandler(this.btnSend, 'click', this._btnSendclickDelegate);

    if (this._clientSideTextChangedDelegate === null) {
        this._clientSideTextChangedDelegate = Function.createDelegate(this, this.ClientSideTextChanged);
    }
    this.btnBan = $get(this.btnBan);
    if (this.btnBan != null) {
        if (this._btnBanclickDelegate === null) {
            this._btnBanclickDelegate = Function.createDelegate(this, this._btnBanclickHandler);
        }
        $addHandler(this.btnBan, 'click', this._btnBanclickDelegate);
    }
    if (this.btnPopUp != null) {
        this.btnPopUp = $get(this.btnPopUp);
        if (this._openPopUpChatDelegate === null) {
            this._openPopUpChatDelegate = Function.createDelegate(this, this.openPopUpChat);
        }
        if (this.btnPopUp != null) {
            $addHandler(this.btnPopUp, 'click', this._openPopUpChatDelegate);
        }
    }
    this.startChat();
    if (this.chatTimer != null)
        window.clearInterval(this.chatTimer);
    this.chatTimer = window.setInterval(this._refreshChatDelegate, this.refreshRate);
    
    if (typeof (FTB_API) != 'undefined') {
   
        if (FTB_API[this.editor] == null) {
            window.setTimeout(Function.createDelegate(this, this.setEditor), 2000);
        }
        else {
            this.editor = FTB_API[this.editor];
            this.editor.getValue = function() { return this.GetHtml() };
            this.editor.clearValue = function() {this.SetHtml(""); this.Focus() };
            this.editor.clientSideTextChanged = this._clientSideTextChangedDelegate;
            this.ClientSideTextChanged(this.editor);
        }
    } else {
        this.editor = $get(this.editor);
        this.editor.getValue = function() { return dnn.smilePicker.codesToSmiles(this.value) };
        this.editor.clearValue = function() { this.value = "" };
    }
    this.setImgCheckBox(this.chkScroll);
    this.setImgCheckBox(this.chkSound);
    messer.messerChat.callBaseMethod(this, 'initialize');
}

messer.messerChat.prototype.setEditor = function() {
    if (FTB_API[this.editor] == null) {
        window.setTimeout(Function.createDelegate(this, this.setEditor), 2000);
        return;
    }
    this.editor = FTB_API[this.editor];
    this.editor.getValue = function() { return this.GetHtml() };
    this.editor.clearValue = function() { this.SetHtml(""); this.Focus(); };
    this.editor.clientSideTextChanged = this._clientSideTextChangedDelegate;
    this.ClientSideTextChanged(this.editor);
}

messer.messerChat.prototype.dispose = function (){
	if (this._btnSendclickDelegate) {
        $removeHandler(this.btnSend, 'click', this._btnSendclickDelegate);
        delete this._btnSendclickDelegate;
    }
    if (this._btnBanclickDelegate) {
        $removeHandler(this.btnBan, 'click', this._btnBanclickDelegate);
        delete this._btnBanclickDelegate;
    }    
    if (this._refreshChatDelegate) {
        $removeHandler(this.roomList, 'change', this._refreshChatDelegate);
        delete this._refreshChatDelegate;
    }  
	messer.messerChat.callBaseMethod(this, 'dispose');
}

messer.messerChat.prototype._btnSendclickHandler = function(event) {
    Messer.Modules.MesSerChat.MesSerChatService.SendMessage(this.TabModuleId, this.roomList.value, this.editor.getValue(), this.uColorPick.value == null ? "" : this.uColorPick.value, this.markedUser == null ? "" : this.markedUser.id, this._publishChatDelegate);
    this.editor.clearValue();
    if (this.editor.forecolor) {
        this.editor.ExecuteCommand('forecolor', '', this.editor.forecolor);
    }
    Messer.Modules.MesSerChat.MesSerChatService.RefreshChat(this.TabModuleId, this.roomList.value, this._publishChatDelegate);

}
messer.messerChat.prototype._btnBanclickHandler = function (event){  
    Messer.Modules.MesSerChat.MesSerChatService.BanUser(this.TabModuleId,this.markedUser==null?"":this.markedUser.id,this.roomList.value,this._publishChatDelegate);
}

messer.messerChat.prototype.ClientSideTextChanged = function(evtObj) {
    if (this.flag)
        return;
    if (FTB_Browser.isIE) {
        if (evtObj.designEditor.document.onkeypress == null)
            evtObj.designEditor.document.onkeypress = Function.createDelegate(this, function(e) { if (evtObj.designEditor.document.parentWindow.event.keyCode == 13) { this.btnSend.click(); return false; } });
    } else {
        evtObj.designEditor.addEventListener('keypress', Function.createDelegate(this, function(e) { if (e.which == 13 && !e.ctrlKey) { evtObj.CancelEvent(e); this.btnSend.click();return false;} }), true);
    }
    this.flag = true;
}  

messer.messerChat.prototype.startChat = function (evt){
    Messer.Modules.MesSerChat.MesSerChatService.StartChat(this.TabModuleId,this.roomList.value,this._publishChatDelegate);
}
messer.messerChat.prototype.refreshChat = function (evt){     
    if(evt!=null && evt.rawEvent!=null && evt.rawEvent.srcElement==this.roomList)
       this.msgsList.innerHTML="";
   Messer.Modules.MesSerChat.MesSerChatService.RefreshChat(this.TabModuleId, this.roomList.value, this._publishChatDelegate);
    
}
messer.messerChat.prototype.publishChat = function(resp, context) {
    
    try {
        resp = Sys.Serialization.JavaScriptSerializer.deserialize(resp);
        this.publishMessages(resp[0], context);
        this.publishUsers(resp[1], context);
    }
    catch (e) { }

}


messer.messerChat.prototype.publishMessages = function (msgsObj,context){
	for (var i=0;i<msgsObj.length;i++){
	    var msg=msgsObj[i]
	    var msgHtml = String.format("{0} <font style='color:{1}'>{2}:{3}</font> {4}", this.chatLocalTime(msg.H), msg.C, msg.N, chatLocal[msg.T], msg.M);
	    var msgContainer=document.createElement("DIV");
        msgContainer.innerHTML=msgHtml;
	    this.msgsList.appendChild(msgContainer);
	    if(this.msgsList.childNodes.length>100){
			this.msgsList.removeChild(this.msgsList.firstChild);
		}	
	}
	this.scrollToLastMsg();
	if(i>0 && typeof(playSound)!='undefined')playSound();
}
messer.messerChat.prototype.scrollToLastMsg = function (){
    if (this.chkScroll.checked)
        this.msgsList.scrollTop = this.msgsList.scrollHeight;
}
messer.messerChat.prototype.chatLocalTime = function (dateObj){
  return dateObj.format("HH:mm");
}
messer.messerChat.prototype.publishUsers = function (usersObj,context){
    if(usersObj==null){return;}
    var serverUsers=usersObj;
	var clientUsers=this.userList.childNodes;
	for (var i=clientUsers.length-1;i>=0;i--){
	    var cltUser=clientUsers[i];
		var srvUser=serverUsers[cltUser.id];
		if(srvUser==null){
		    this.userList.removeChild(cltUser);
		    if(cltUser==this.markedUser){this.markedUser=null;}
		    //if(cltUser.id==dnn.getVar('PRIVATE')){
			//	dnn.setVar('PRIVATE', '');
			//	//alert("private user out of chat");
			//}	
		}else{//User exist in chat user list
		    if(srvUser.B)
		        cltUser.style.textDecoration='line-through';
		    else
		        cltUser.style.textDecoration='none';
		    
		    serverUsers[cltUser.id]=null;    
		}
	}
	for (var ii in serverUsers){
	    if(serverUsers[ii]!=null){
	        var user = document.createElement("DIV");
		    user.id=ii;//serverUsers[i].Id;
		    user.className="User";
		    user.title=chatLocal.usertitle;
		    if(serverUsers[ii].B) user.style.textDecoration='line-through';
		    $addHandler(user, "click", this._markUserDelegate);
		    var displayName=serverUsers[ii].N==null?ii:serverUsers[ii].N;
		    user.innerHTML=String.format("<span><img src='{0}/images/flags/{1}.png'/></span>&nbsp;{2}",moduleUrl,serverUsers[ii].C,displayName);
		    this.userList.appendChild(user);
	    }
	}	
}

messer.messerChat.prototype.markUser = function (evt){
   var user=evt.target;
   while (user.tagName != null && user.tagName.toUpperCase()!="DIV") {
       user=user.parentNode;
   }
   if(user!=null){
       if(this.markedUser!=null)
           this.markedUser.className='User';
       if(this.markedUser==user){
           this.markedUser=null;
       }else{
           this.markedUser=user;
           this.markedUser.className='PrivateUser';
       }
   }
}

messer.messerChat.prototype.setImgCheckBox = function (chk){
    var imgChecked = new Image();
	var imgUnChecked = new Image();
	imgChecked.src = chk.parentNode.getAttribute('src');
    imgUnChecked.src =chk.parentNode.getAttribute('chk');
    var oImg = document.createElement('img');
    chk.checked ? oImg.src = imgChecked.src : oImg.src = imgUnChecked.src;
    oImg.style.top = '0px';
	oImg.style.left = '0px';
	oImg.style.display = 'none';
	chk.parentNode.appendChild(oImg);
	chk.style.display="none";		
    oImg.style.display="block";
	$addHandler(oImg, "click", function(){chk.checked?chk.checked=false:chk.checked=true;chk.checked?this.src=imgChecked.src:this.src=imgUnChecked.src;});
}

messer.messerChat.prototype.openPopUpChat = function (event){
    var element = this.get_element();
	var bounds=Sys.UI.DomElement.getBounds(element);
	var params="status=no,toolbar=no,menubar=no,location=no,width="+bounds.width+"px,height="+(bounds.height+20)+"px,top="+(bounds.y)+"px,left="+bounds.x+"px";
	var pickerWin = window.open(moduleUrl+"/PopUp.aspx?TabModuleId="+this.TabModuleId,"chatPopUpWin",params);
	if (pickerWin) {pickerWin.focus();} 
	else {alert("Please turn off your PopUp blocking software");return;}
}
messer.messerChat.prototype.ChatErrorHandler = function (resp,context){
    if(resp.get_message()=='USERNAMEISEMPTY'){
        document.location=document.location; 
    }
}
messer.messerChat.registerClass('messer.messerChat',Sys.UI.Control);
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
