﻿var chatui_sendmsgtimes=[];
var chatui_floodmsgsend=false;

function ChatUI_CheckFloodControl()
{
	var count = 5;
	var maxms = 10 * 1000;
	if(chatui_sendmsgtimes.length>=count)
	{
		var timespan=new Date().getTime()-chatui_sendmsgtimes[chatui_sendmsgtimes.length-count];
		if(timespan < maxms)
		{
			if(!chatui_floodmsgsend)
			{
				var floodmsg={};
				floodmsg.MessageType="LOCAL";
				floodmsg.MessageText=TEXT("UI_FloodControlMessage");
				_InvokeChatEvent("MESSAGE",["MESSAGE","NEW",floodmsg]);
				chatui_floodmsgsend=true;
			}
			return false;
		}
		//reset while 100 sent messages
		if(chatui_sendmsgtimes.length>100)
		{
			chatui_sendmsgtimes.splice(0,90);
		}
	}
	chatui_floodmsgsend=false;
    return true;
}

function ChatUI_SendMessageWithFloodControl(text,html)
{
	if(text && text.substr(0,1)=="/")
	{
		//TODO:
		return ChatUI_HandleSplashCommand(text.substring(1));
	}
	if( ! ChatUI_CheckFloodControl() )
	{
		return false;
	}	
	var sended=SendMessage(text,html);
	if(sended)
	{
		chatui_sendmsgtimes[chatui_sendmsgtimes.length]=new Date().getTime();
	}
	return sended;
}

function ChatUI_AppendMessage(div,msg,mode)
{
	var playSound = false;
	
	switch(msg.MessageType)
	{
		case "EMOTION":
			var className="EmotionMessage";
			var table=window.document.createElement("TABLE");
			table.border=0;table.cellSpacing=0;table.cellPadding=1;
			var tr=table.insertRow(-1);
			var td=tr.insertCell(-1);
			if(msg.Sender.DisplayName==GetMyInfo().DisplayName)
			{
				className+=" MyMessage";
			}
			//ChatUI_AppendUser(td,msg.Sender);
			if(mode=="INSTANTMAIN" && msg.Sender.DisplayName==GetMyInfo().DisplayName )
			{
				td.appendChild(document.createTextNode(TEXT("MSG_TO")));
				//ChatUI_AppendUser(td,msg.ToUser)
			}
			td.appendChild(document.createTextNode(" - "));
			td=tr.insertCell(-1);
			td.innerHTML=Html_Encode(msg.MessageText);
			table.className=className;
			div.appendChild(table);
			break;
		case "USER":
            var className="UserMessage";
            if(msg.Whisper&&mode=="GENERAL")
	            className="WhisperUserMessage";
            var table=window.document.createElement("TABLE");
            table.border=0;table.cellSpacing=0;table.cellPadding=1;
            var tr=table.insertRow(-1);
            var td=tr.insertCell(-1);
            if (msg.Sender)
            {
                if(msg.Sender.DisplayName == getChatObject().myInfo.DisplayName)
                {
	                className+=" MyMessage";	                
                }
                if(msg.Message.Sender.IsOperator)
                {
	                className+=" OperatorMessage";
	                playSound = true;
                }
            }
            ChatUI_AppendUser(td,msg.Sender);
            td.appendChild(document.createTextNode(": "));
            td=tr.insertCell(-1);
            if(msg.MessageHtml)
	            td.innerHTML=ChatUI_TranslateHtml(msg.MessageHtml);
            else td.innerHTML=ChatUI_TranslateText(msg.MessageText);			

            if(msg.Font)
            {
	            if(msg.Font.Bold)td.style.fontWeight='bold';
	            if(msg.Font.Italic)td.style.fontStyle='italic';
	            if(msg.Font.Underline)td.style.textDecoration='underline';
	            if(msg.Font.FontName)td.style.fontFamily=msg.Font.FontName;
	            if(msg.Font.FontSize)td.style.fontSize=msg.Font.FontSize;
	            if(msg.Font.FontColor)td.style.color=msg.Font.FontColor;
            }
            table.className=className;
            div.appendChild(table);
			break;
		case "SYSTEM":
			var span=document.createElement("span");
			if(msg.MessageHtml)
				span.innerHTML=msg.MessageHtml;
			else
				span.innerHTML=ChatUI_TranslateText(msg.MessageText);
			span.className="System"
			div.appendChild(span);
			if (!msg.soundSupress)
			    playSound = true;
			break;

		case "LOCAL":
			//for example - ChatUI_SendMessageWithFloodControl
			var span=document.createElement("span");
			if(msg.MessageHtml)
				span.innerHTML=msg.MessageHtml;
			else span.innerHTML=ChatUI_TranslateText(msg.MessageText);

			if(msg.MessageCss)
				span.className=msg.MessageCss;
			div.appendChild(span);
			break;
		default:
			var span=document.createElement("span");
			span.innerHTML=msg.MessageType+" : "+msg.MessageHtml||Html_Encode(msg.MessageText);
			div.appendChild(span);
			break;

	}
	
	/* 
	by Gabriel@dsn - em 26/09/2007 - Esta verificação foi criada porque antes, quando o usuário
	estava digitando e recebia uma mensagem do operador, o cursor saía da sua posição, conforme o processo
	de número 0012054505 explanou. 
	*/
	if (getChatObject().chatEditor.get_Text() == "")
	{
	    getChatWin().focus();
        getChatObject().chatEditor.setFocus();	
	}	
	
	if ((playSound == true) && getChatObject().playSounds)
	    ChatUI_PlaySound("Media/vocerecebeuumanovamensagem2.wav");	
}

function ChatUI_TranslateText(text)
{
	if(text==null)return "";

	for(var i=0;i<msnimgregexps.length;i++)
	{
		var o=msnimgregexps[i];
		text=text.replace(o.r,o.t);
	}
	text=Html_Encode(text);
	text=text.split("\n").join("<br/>");
	text=text.replace(/(\S+:\/\/\S+)/ig,"<a target='_blank' href='$1'>$1</a>");
	text=ChatUI_TranslateHtml(text);
	return text;
}

function ChatUI_TranslateHtml(html)
{
	if(html==null)return "";
	//html=html.replace(/\[Emotion=([^\[\]=\s]+)\]/ig,"<img src="+CuteChatUrlBase+"images/emotions/$1>");
	//html=html.replace(/\[MsnImage=([^\[\]=\s]+)\]/ig,"<img src="+CuteChatUrlBase+"images/msn/$1>");
	return html;
}

/****************************************************************\

	MSN Images

\****************************************************************/

//the data map the text to the image index

//http://messenger.msn.com/resource/Emoticons.aspx

var msnimagesarr=[
	{i:1,t:":)"},
	{i:1,t:":-)"},
	{i:2,t:":D"},
	{i:2,t:":-D"},
	{i:3,t:":O"},
	{i:3,t:":-O"},
	{i:4,t:":P"},
	{i:4,t:":-P"},
	{i:5,t:";-)"},
	{i:5,t:";)"},
	{i:6,t:":-("},
	{i:6,t:":("},
	{i:7,t:":S"},
	{i:7,t:":-S"},
	{i:8,t:":|"},
	{i:8,t:":-|"},
	{i:9,t:":'("},
	{i:10,t:":$"},
	{i:10,t:":-$"},
	{i:11,t:"(H)"},
	{i:12,t:":-@"},
	{i:12,t:":@"},
	{i:13,t:"(A)"},
	{i:14,t:"(6)"},
	{i:15,t:":-#"},
	{i:16,t:"8O|"},
	{i:17,t:"8-|"},
	{i:18,t:"^O)"},
	{i:19,t:":-*"},
	{i:20,t:"+O("},
	{i:21,t:":^)"},
	{i:22,t:"*-)"},
	{i:23,t:"<O:)"},
	{i:24,t:"8-)"},
	{i:25,t:"|-)"},
	//others
	{i:26,t:"(C)"},
	{i:27,t:"(Y)"},
	{i:28,t:"(N)"},
	{i:29,t:"(B)"},
	{i:30,t:"(D)"},
	{i:31,t:"(X)"},
	{i:32,t:"(Z)"},
	{i:33,t:"({)"},
	{i:34,t:"(})"},
	{i:35,t:":-["},
	{i:35,t:":["},
	{i:36,t:"(^)"},
	{i:37,t:"(L)"},
	{i:38,t:"(U)"},
	{i:39,t:"(K)"},
	{i:40,t:"(G)"},
	{i:41,t:"(F)"},
	{i:42,t:"(W)"},
	{i:43,t:"(P)"},
	{i:44,t:"(~)"},
	{i:45,t:"(@)"},
	{i:46,t:"(&)"},
	{i:47,t:"(T)"},
	{i:48,t:"(I)"},
	{i:49,t:"(8)"},
	{i:50,t:"(S)"},
	{i:51,t:"(*)"},
	{i:52,t:"(E)"},
	{i:53,t:"(O)"},
	{i:54,t:"(M)"},
	{i:55,t:"(SN)"},
	{i:56,t:"(BAH)"},
	{i:57,t:"(PL)"},
	{i:58,t:"(||)"},
	{i:59,t:"(PI)"},
	{i:60,t:"(SO)"},
	{i:61,t:"(AU)"},
	{i:62,t:"(AP)"},
	{i:63,t:"(UM)"},
	{i:64,t:"(IP)"},
	{i:65,t:"(CO)"},
	{i:66,t:"(MP)"},
	{i:67,t:"(ST)"},
	{i:68,t:"(LI)"},
	{i:69,t:"(MO)"}
	];

var msnimagesarr2=[];
var msnimagesarr3=[];
var msnimagesarr4=[];
var msnimagesarr5=[];
var msnimagesarr6=[];
var msnimgregexps=[];


function ChatUI_AppendUser(div,user,where)
{
    if (!div) return;
    if (!user) return;

	//user=UserToUser(user);
	var p=document.createElement("NOBR");
	var img=document.createElement("IMG");
	
	if(user.IsOperator)
	{
		img.src="Images/support_chat2.gif";		
	}
	else 
	{
		img.src="Images/contact22.gif";
	}
	
	if(where=="USERLIST"||'True'=='True')
	{
		if(img.src)
		{
			img.align='absmiddle';
			if(img.width>19||img.height>19)
			{
				img.width="24";
				img.height="24";			
			}
			p.appendChild(img);
			p.appendChild(document.createTextNode(" "));
		}
	}

	var span=document.createElement("SPAN");
	//if(UserEquals(user,GetMyInfo()))
	if(user.UserCode == getChatObject().myInfo.UserCode)
	{
		span.className="You";
		span.innerHTML=Html_Encode(user.DisplayName);
		//ChatUI_SetContextMenu(p,new Function("event","if(Html_FCM(event))ChatUI_ShowMyInfoEvent(event)"));
	}
	else
	{
		span.className="User";
		span.innerHTML=Html_Encode(user.DisplayName);

     	p.style.cursor="hand";
		//p.onclick=new Function("event","ChatUI_SelectUserExp('"+CodeEncode(ChatUI_UserToExp(user))+"',event)");
		//p.ondblclick=new Function("event","ChatUI_DoUserDefaultActionExp('"+CodeEncode(ChatUI_UserToExp(user))+"',event)");
		//ChatUI_SetContextMenu(p,new Function("event","if(Html_FCM(event))ChatUI_ShowUserMenuExp('"+CodeEncode(ChatUI_UserToExp(user))+"',event);"));
	}

	if(user.IsAdmin)
	{
		span.className="Admin "+span.className;
	}

	p.appendChild(span);
	div.appendChild(p);
}


/****************************************************************\

	Sound Functions

\****************************************************************/



var _lastsoundplaytime=0;

function ChatUI_PlaySound(soundfile)
{
	if( ! ChatUI_GetEnableSound() ) return;

	if(soundfile.substr(0,1)!="/")
	    soundfile = soundfile;

	//don't play sound in 2 seconds
	if(_lastsoundplaytime+2000>new Date().getTime())
		return;

	_lastsoundplaytime=new Date().getTime();
	//TODO: FireFox doesn't work..
	var bgsound=document.createElement("BGSOUND");
	document.body.appendChild(bgsound);
	bgsound.loop=1;
	bgsound.src=soundfile;

	//remove it 5 second later
	function RemoveBGSound()
	{
		bgsound.parentNode.removeChild(bgsound);
	}
	setTimeout(RemoveBGSound,5000);

}

function ChatUI_SetEnableSound(enable)
{
	enable=_SL_ToBoolean(enable);
	if(enable)
	{
		SetCookie("CCNoSound","false",-1);
	}
	else
	{
		SetCookie("CCNoSound","true",3600*24*365);
	}
}

function ChatUI_GetEnableSound()
{
	var v=GetCookie("CCNoSound");
	if(v=="true")
		return false;
	return true;		//default allow sound..
}



/****************************************************************\

	Cookie Functions

\****************************************************************/

function SetCookie(name,value,seconds)
{
	var cookie=name+"="+escape(value)+"; path=/;";
	if(seconds)
	{
		var d=new Date();
		d.setSeconds(d.getSeconds()+seconds);
		cookie+=" expires="+d.toUTCString()+";";
	}
	document.cookie=cookie;
}

function GetCookie(name)
{
	var cookies=document.cookie.split(';');
	for(var i=0;i<cookies.length;i++)
	{
		var parts=cookies[i].split('=');
		if(name==parts[0].replace(/\s/g,''))
			return unescape(parts[1])
	}
	//return undefined..
}

function GetCookieDictionary()
{
	var dict={};
	var cookies=document.cookie.split(';');
	for(var i=0;i<cookies.length;i++)
	{
		var parts=cookies[i].split('=');
		dict[parts[0].replace(/\s/g,'')]=unescape(parts[1]);
	}
	return dict;
}

function GetCookieArray()
{
	var arr=[];
	var cookies=document.cookie.split(';');
	for(var i=0;i<cookies.length;i++)
	{
		var parts=cookies[i].split('=');
		var cookie={name:parts[0].replace(/\s/g,''),value:unescape(parts[1])};
		arr[arr.length]=cookie;
	}
	return arr;
}

// JScript File
function SetResize() 
{
    resizeDiv();   
    window.onresize=function() {
      resizeDiv();      
    }
}
// Código retirado do SpreadSheets do Google
function resizeDiv() 
{
    // client detection and page height/width
    var agent = navigator.userAgent.toLowerCase();
    var is_ie = (agent.indexOf('msie') != -1);
    var is_mac = (agent.indexOf('macintosh') != -1);
    var pageWidth = is_ie ? window.document.body.clientWidth : window.innerWidth;
    var pageHeight = is_ie ? window.document.body.clientHeight : window.innerHeight;

    // fix 1-way scrollbars in Firefox
    if (!is_ie) {
        var scrollbarSize = is_mac ? 15 : 19;
        if (pageWidth < minWidth) pageHeight -= scrollbarSize;
        if (pageHeight < minHeight) pageWidth -= scrollbarSize;
    }
    var minWidth = 500;
    var minHeight = 300;
    if (pageWidth >= minWidth && pageHeight >= minHeight) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = 'auto';
    }
}

function TEXT(text)
{
	text=GetString(text);
	for(var i=1;i < arguments.length;i++)
	{
		var item=""+arguments[i];
		text=text.replace(new RegExp("\\{"+(i-1)+"\\}","ig"),item);
	}
	return text;
}

function GetString(name)
{
	var upper=name.toUpperCase();
	var v=__cc_strings[upper];
	if(v!=null)
		return v;
	v=__cc_global["TEXT_"+upper];
	if(v!=null)
		return v;
	return "[("+name+")]";
}