function FormatString(f, s0, s1, s2, s3, s4, s5, s6, s7, s8, s9){
        var args = new Array(s0, s1, s2, s3, s4, s5, s6, s7, s8, s9);
        for (var i = 0; i < args.length; i++){
                if (args[i] != null){
                        var replacementText = "{" + i + "}";
                        while ( - 1 != f.indexOf(replacementText)){
                                f = f.replace(replacementText, args[i]);
                        }
                }
        }
        return f;
}
function Trim(s){
        return RTrim(LTrim(s));
}

function LTrim(s){
	try{
		do{
				if (null == s || s.length <= 0){
						break;
				}
				var whitespace = " \t\r\n";
				if (whitespace.indexOf(s.charAt(0)) >= 0){
						var len = s.length;
						var index;
						for (index = 0; index < len; ++index){
								if (whitespace.indexOf(s.charAt(index)) < 0){
										break;
								}
						};
						if (index < len){
								s = s.substring(index);
						}
						else{
								s = "";
						}
				}
		}
		while (false);
	}
	catch (exception){
			;
			s = "";
	}
	return s;
}

function RTrim(s){
	try{
			do{
					if (null == s || s.length <= 0){
							break;
					}
					var len = s.length;
					var whitespace = " \t\r\n";
					if (whitespace.indexOf(s.charAt(len - 1)) >= 0){
							var index;
							for (index = (len - 1); index >= 0; --index){
									if (whitespace.indexOf(s.charAt(index)) ==  - 1){
											break;
									}
							}
							if (index >= 0){
									s = s.substring(0, index + 1);
							}
							else{
									s = "";
							}
					}
			}
			while (false);
	}
	catch (exception){
			;
			s = "";
	}
	return s;
}


function onComposeKeyUp(e, textControl, sendButton){

	try{
			if (textControl != null && sendButton != null){
					var key = null;
					if (IsIE()){
							if ((null != e) && (null != e.keyCode)){
									key = e.keyCode;
							}
					}
					else{
							if ((null != e) && (null != e.which)){
									key = e.which;
							}
					}
					if (key != null){
							/*if (27 == e.keyCode){
									window.parent.close();
							}*/
					}
					var msg = Trim(textControl.value);             
					if (msg.length > 0){
							if (true == sendButton.disabled){
									sendButton.disabled = false;
									sendButton.className = "sendButtonEnabled";
							}
							if (msg.length > 400){
									textControl.value = msg.substring(0, 400);
							}
					}
					else{
							if (false == sendButton.disabled){
									sendButton.disabled = true;
									sendButton.className = "sendButtonDisabled";
							}
					}
			}
	}
	catch (exception){
			;
	}
}

function onComposePaste(e, textControl, sendButton){
	try{
			if (textControl != null && sendButton != null){
					if (true == sendButton.disabled){
							sendButton.disabled = false;
							sendButton.className = "sendButtonEnabled";
					}
					window.setTimeout("onAfterComposePaste();", 100);
			}
	}
	catch (exception){
			;
	}
}


function onAfterComposePaste(){
	var textControl = FindObject("textBox");
	var sendButton = FindObject("sendButton");
	;
	;
	try{
			if (textControl != null && sendButton != null){
					var msg = Trim(textControl.value);
					if (msg.length > 0){
							if (msg.length > 400){
									textControl.value = msg.substring(0, 400);
							}
					}
					else{
							if (false == sendButton.disabled){
									sendButton.disabled = true;
									sendButton.className = "sendButtonDisabled";
							}
					}
			}
	}
	catch (exception){
			;
	}
}

function onComposeKeyPressed(e){
	try{
                if (IsIE()){
                        if (13 == event.keyCode){
                                if (event.shiftKey){}
                                else{
                                	window.setTimeout("SubmitMessage();", 50);
                                        //SubmitMessage();
                                }
                        }
                }
                else if ((null != e) && (null != e.which)){
                        if (13 == e.which){
                                if (e.shiftKey){}
                                else{
                                	window.setTimeout("SubmitMessage();", 50);
                                        //SubmitMessage();
                                }
                        }
                }
        }
        catch (exception){
                ;
        }
	
        return true;
}

var iGetMsgCount=0;
function SubmitMessage(){
	var textBox = document.getElementById("textBox");
        var msgText = textBox.value;
        if (null == msgText){
                ;
        }
        else{
                if (Trim(msgText).length > 0){
                	
                	SendComposition();
                        //document.composeForm.submit();
                        //window.composeframe.composeForm.submit();
                        
                } else {
                	textBox.value = "";	
                }
        }
}

var request = false;

function createRequest() {
	try {
		request = new XMLHttpRequest();
	} catch (trymicrosoft) {

		try {
			request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (othermicrosoft) {
			try {
				request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (failed) {
				request = false;
			}
		}
	}
	if (!request)
		alert("Error initializing XMLHttpRequest!");
}
createRequest();

function Get_AI_Result(strMsg,strProxy){

	var url="/FunnyAI2.aspx";
	var pars = "msg="+encodeURIComponent(strMsg)+"&AI=1&Proxy="+strProxy;
	
	//onLoading: loading
	var pAjax = new Ajax.Request(    
		url,    
		{    
			method: 'POST',    
			parameters: pars,
			asynchronous: true,
			onComplete: Post_CallBack    
		}
	);

}

var iGetMsgCount_Max=30;
var iLoop=0;
function Loop_Get_Msg(){
	Get_AI_Result("SYS_Get_Msg","SYS");
	iLoop=1;
	iGetMsgCount+=1;
	
	if (iGetMsgCount>iGetMsgCount_Max)
	{
		iLoop=0;
	}else if (iGetMsgCount<8){
		setTimeout(function(){
				Loop_Get_Msg();
			},500*(1+iGetMsgCount));
	}else{
		setTimeout(function(){
				Loop_Get_Msg();
			},4000);
	}
}

function Post_CallBack(originalRequest) {
	var strReturn=originalRequest.responseText;

	strReturn=strReturn.replace(/<br>/gi,"\r\n");

	if (strReturn.indexOf("SYS_Get_Msg")>-1){
		if (iGetMsgCount==0 && iLoop==0)
		{
			//iLoop=0代表没有线程读取东西
			Loop_Get_Msg();
		}
	}else{
		iGetMsgCount=iGetMsgCount_Max-1;
		AI_Return(strReturn);
	}

}

function AI_Return(strMsg){
	var format = new MessageFormat(null, null, null, "#0000FF");

	var conversation = null;
	try {
		conversation =  window.parent.conversationWindow;
	}
	catch (e) {}
	if (conversation == null) {
		try {
			conversation =  window.conversationWindow;
		}
		catch(e) {}
	}
	conversation.InsertMessageFromBot("",L_IDS_DISPLAYNAME_BOT, strMsg, format);
}


function OnProcessComplete(){
	if (xmlhttp.readyState == 4) { 
			if (xmlhttp.status == 200) { 
				var conversation = null;
				try {
					conversation =  window.parent.conversationWindow;
				}
				catch (e) {}
				if (conversation == null) {
				try {
					conversation =  window.conversationWindow;
				}
				catch(e) {}
			}
			if (conversation != null) {
				var messageList = xmlhttp.responseXML.getElementsByTagName("message"); 
				for (i = 0;i < messageList.length;i++) {
					var message = messageList[i];
					var f = message.getAttribute("fontName");	
					var c = message.getAttribute("fontColor");	
					var s = message.getAttribute("styleCode");
					var fc = message.firstChild;
					
					if (fc) {
						var msgText = fc.data;
						var format = new MessageFormat(f, null, s, c);
						
						 conversation.InsertMessageFromBot("",L_IDS_DISPLAYNAME_BOT, msgText, format);
					}
				}
			}
		}
	}
}


function SetText(strMsg){
	//返回的一些选择主题。
	var conversation = null;
	try {
		conversation =  window.parent.conversationWindow;
	}
	catch (e) {}
	if (conversation == null) {
		try {
			conversation =  window.conversationWindow;
		}
		catch(e) {}
	}
	strMsg=strMsg.replace("<br/>","\r\n");
	strMsg=strMsg.replace("<br>","\r\n");
	conversation.InsertComposeString(strMsg);
}


function SendComposition(){
	iGetMsgCount=0;
	//发送给服务器处理
	var textBox = document.getElementById("textBox");
	var sendButton = document.getElementById("sendButton");
	var composeframe = window.frames["composeframe"];

	if (textBox != null){
		var msgText = Trim(textBox.value);
 
		if (msgText != null && msgText.length > 0){
				var conversation = parent.conversationWindow;
				if (conversation != null){
						var format = null;
						var f = document.getElementById("font");
						var c = document.getElementById("fontColor");
						var b = document.getElementById("bold");
						var i = document.getElementById("italic");
						var u = document.getElementById("underline");
						var t = document.getElementById("messageText");
						;
						var font = null;
						var color = null;
						var styleCode = "";
						var size = null;
						t.value = msgText;
						//composeframe.composeForm.messageText.value = NewlineReplace(LinkReplace(EmoticonReplace(EntityReplace(msgText))));
						//composeframe.composeForm.messageText.value = msgText;
					   
						textBox.value = "";
						//sendButton.disabled = true;
		
						if (f != null){
								font = f.value;
						}
						if (c != null){
								color = c.value;
						}
						if (b != null && b.value == '1'){
								styleCode += "B";
						}
						if (i != null && i.value == '1'){
								styleCode += "I";
						}
						if (u != null && u.value == '1'){
								styleCode += "U";
						}
						
						//RequestProcess(msgText,font ,color, styleCode);
						Get_AI_Result(msgText);
						format = new MessageFormat(font, size, styleCode, color);
						conversation.InsertMessageFrom("",L_IDS_DISPLAYNAME_ME, msgText, format);
						textBox.focus();
						
			  }
		}
	}
}



function SetCaretAtEnd(textControl){
        try{
                do{
                        if (null == textControl){
                                ;
                                break;
                        }
                        if (textControl.createTextRange){
                                var r = textControl.createTextRange();
                                r.moveStart('character', textControl.value.length);
                                r.collapse();
                                r.select();
                        }
                        else if (typeof textControl.selectionStart != "undefined"){
                                textControl.selectionStart = textControl.value.length;
                                textControl.selectionEnd = textControl.value.length;
                        }
                }
                while (false);
        }
        catch (exception){
                ;
        }
}


function FindObject(id){
        var o = null;
        try{
                ;
                if (id != null){
                        o = document.getElementById(id);
                        if (o == null){
                                o = FindObjectInWindow(id, top);
                        }
                }
        }
        catch (exception){
                ;
                o = null;
        }
        return o;
}

function FindObjectInWindow(id, w){
        var o = null;
        try{
                if ((null != w) && (null != w.document) && (null != id)){
                        o = w.document.getElementById(id);
                        if (o != null){}
                        else if (w.frames.length > 0){
                                var count;
                                for (count = 0; count < w.frames.length; ++count){
                                        o = FindObjectInWindow(id, w.frames[count]);
                                        if (o != null){
                                                break;
                                        }
                                }
                        }
                }
        }
        catch (exception){
                ;
                o = null;
        }
        return o;
}

function IsVisible(obj){
        ;
        var result = false;
        if (obj != null && obj.style != null){
                var d = obj.style.display;
                result = (d != null && d != "none");
        }
        return result;
}

function ShowHide(obj, show){
        if (obj != null){
                var visible = IsVisible(obj);
                if (visible != show){
                        obj.style.display = show ? "block" : "none";
                }
        }
}


function IsIE(version){
        var rc = false;
        if (navigator.userAgent.indexOf('MSIE') >  - 1){
                if (navigator.userAgent.indexOf("Opera") == ( - 1)){
                        if (null != version){
                                if (navigator.userAgent.indexOf(version) >  - 1){
                                        rc = true;
                                }
                        }
                        else{
                                rc = true;
                        }
                }
        }
        return rc;
}


function LinkReplace(input){
	var s=input;var output="";
	if(IsIE()){
		var linkExpression=/(http|https|ftp):\/\/([\w-]+\.)+[\w-]+([\w-.\/?=;!*%$]*)?([\w-&=;!*%$]*)?/gi;
		var match=linkExpression.exec(s);
		while(null !=match){
			var s1=match.index>0?s.substring(0,match.index):"";
			var s2=s.substring(match.index,match.lastIndex);
			var s3="";if(s2!=null){
				if(s2.length>0){
					if(s2.lastIndexOf(".")==(s2.length-1)){
						s2=s2.substring(0,s2.length-1);s3="."
					}
				}
			}
			s3+=s.substring(match.lastIndex);
			output+=s1+"<a href='"+s2+"' target='_new'>"+s2+"</a>";s=s3;
			linkExpression=/(http|https|ftp):\/\/([\w-]+\.)+[\w-]+([\w-.\/?=;!*%$]*)?([\w-&=;!*%$]*)?/gi;
			match=linkExpression.exec(s);
		}
		output+=s;
		if(output.length<=0){
			output=input;
		}
	}
	else{
		output=s.replace(/(http|https|ftp):\/\/([\w-]+\.)+[\w-]+([\w-.\/?=;!*%$]*)?([\w-&=;!*%$]*)?/gi, "<a href='$&' target='_new'>$&</a>");
	}
	return output;
}


var newlineRegExp = new RegExp("(\r\n|\n)", "g");
function NewlineReplace(str){
        ;
        result = "";
        if (str != null){
                result = str.replace(newlineRegExp, "<br>");
        }
        return result;
}


var entityList = new Array();
entityList["<"] = "&lt;";
entityList["\uff1c"] = "&lt;";
entityList[">"] = "&gt;";
entityList["\uff1e"] = "&gt;";
entityList["&"] = "&amp;";
entityList["\uff06"] = "&amp;";
entityList["\""] = "&quot;";
entityList["\uff02"] = "&quot;";

function EmoticonInfo(image, keys, length, description){
        this.IsLeaf = true;
        this.EmoticonToHtml = function(){
                return "<img width=\"19\" height=\"19\" src=\"Images/Im/" + image + "\" title=\"" + (description == null ? keys : description) + "\">";
        };
        this.Length = function(){
                return length;
        };
}



function EntityReplace(str){
        ;
        var result = "";
        if (str != null){
                var len = str.length;
                var i = 0;
                while (i < len){
                        var j = i;
                        var e = entityList[str.charAt(j)];
                        while (j < len && null == e){
                                j++;
                                e = entityList[str.charAt(j)];
                        }
                        result += str.substr(i, j - i);
                        if (e != null){
                                result += e;
                                j++;
                        }
                        i = j;
                }
        }
        return result;
}


function Emoticons(){
        var root = new Array();
        function InsertHelper(tree, e, keys, index){
                ;
                ;
                var current = keys.charAt(index);
                if (index < keys.length - 1){
                        if (tree[current] == null){
                                tree[current] = new Array();
                        }
                        InsertHelper(tree[current], e, keys, index + 1);
                }
                else{
                        tree[current] = e;
                }
        }
        
        
        function Insert(image, keys){
                ;
                ;
                var htmlKeys = EntityReplace(keys);
                var e = new EmoticonInfo(image, keys, htmlKeys.length, null);
                InsertHelper(root, e, htmlKeys, 0);
        }
        this.Insert = Insert;

        function Initialize(){

                Insert("airplane.gif", "(ap)");
                Insert("help.gif", "(?)");
                Insert("bat.gif", ":[");
                Insert("bat.gif", ":-[");
                Insert("beer.gif", "(b)");
                Insert("beer.gif", "(B)");
                Insert("blacksheep.gif", "(bah)");
                Insert("bowl.gif", "(||)");
                Insert("cake.gif", "(^)");
                Insert("camera.gif", "(p)");
                Insert("camera.gif", "(P)");
                Insert("car.gif", "(au)");
                Insert("cat.gif", "(@)");
                Insert("clap.gif", "(h5)");
                Insert("clock.gif", "(o)");
                Insert("clock.gif", "(O)");
                Insert("clock.gif", "(0)");
                Insert("cloud_lightning.gif", "(li)");
                Insert("cloud_rain.gif", "(st)");
                Insert("coffee.gif", "(c)");
                Insert("coffee.gif", "(C)");
                Insert("computer.gif", "(co)");
                Insert("dog.gif", "(&)");
                Insert("envelope.gif", "(e)");
                Insert("envelope.gif", "(E)");
                Insert("film.gif", "(~)");
                Insert("fingerscrossed.gif", "(yn)");
                Insert("girl_handsacrossamerica.gif", "(x)");
                Insert("girl_handsacrossamerica.gif", "(X)");
                Insert("guy_handsacrossamerica.gif", "(z)");
                Insert("guy_handsacrossamerica.gif", "(Z)");
                Insert("handcuffs.gif", "(%)");
                Insert("heart.gif", "(L)");
                Insert("heart.gif", "(l)");
                Insert("heart_broken.gif", "(U)");
                Insert("heart_broken.gif", "(u)");
                Insert("hug_dude.gif", "({)");
                Insert("hug_girl.gif", "(})");
                Insert("island.gif", "(ip)");
                Insert("kiss.gif", "(k)");
                Insert("kiss.gif", "(K)");
                Insert("lightbulb.gif", "(i)");
                Insert("lightbulb.gif", "(I)");
                Insert("martini.gif", "(d)");
                Insert("martini.gif", "(D)");
                Insert("messenger.gif", "(M)");
                Insert("messenger.gif", "(m)");
                Insert("mobile.gif", "(mp)");
                Insert("money.gif", "(mo)");
                Insert("moon.gif", "(S)");
                Insert("music_note.gif", "(8)");
                Insert("phone.gif", "(t)");
                Insert("phone.gif", "(T)");
                Insert("pizza.gif", "(pi)");
                Insert("plate.gif", "(pl)");
                Insert("present.gif", "(g)");
                Insert("present.gif", "(G)");
                Insert("rainbow.gif", "(r)");
                Insert("rainbow.gif", "(R)");
                Insert("rose.gif", "(f)");
                Insert("rose.gif", "(F)");
                Insert("rose_wilted.gif", "(w)");
                Insert("rose_wilted.gif", "(W)");
                Insert("smile_angel.gif", "(a)");
                Insert("smile_angel.gif", "(A)");
                Insert("smile_angry.gif", ":@");
                Insert("smile_angry.gif", ":-@");
                Insert("smile_baringteeth.gif", "8o|");
                Insert("smile_confused.gif", ":s");
                Insert("smile_confused.gif", ":S");
                Insert("smile_confused.gif", ":-s");
                Insert("smile_confused.gif", ":-S");
                Insert("smile_cry.gif", ":'(");
                Insert("smile_devil.gif", "(6)");
                Insert("smile_embaressed.gif", ":$");
                Insert("smile_embaressed.gif", ":-$");
                Insert("smile_eyeroll.gif", "8-)");
                Insert("smile_nerd.gif", "8-|");
                Insert("smile_omg.gif", ":-O");
                Insert("smile_omg.gif", ":-o");
                Insert("smile_omg.gif", ":O");
                Insert("smile_omg.gif", ":o");
                Insert("smile_party.gif", "<:o)");
                Insert("smile_regular.gif", ":)");
                Insert("smile_regular.gif", ":-)");
                Insert("smile_sad.gif", ":(");
                Insert("smile_sad.gif", ":-(");
                Insert("smile_sad.gif", ":<");
                Insert("smile_sad.gif", ":-<");
                Insert("smile_sarcastic.gif", "^o)");
                Insert("smile_secret.gif", ":-*");
                Insert("smile_shades.gif", "(h)");
                Insert("smile_shades.gif", "(H)");
                Insert("smile_sick.gif", "+o(");
                Insert("smile_sniff.gif", ":^)");
                Insert("smile_speedy.gif", "(brb)");
                Insert("smile_teeth.gif", ":D");
                Insert("smile_teeth.gif", ":-D");
                Insert("smile_teeth.gif", ":d");
                Insert("smile_teeth.gif", ":-d");
                Insert("smile_thinking.gif", "*-)");
                Insert("smile_tongue.gif", ":p");
                Insert("smile_tongue.gif", ":-p");
                Insert("smile_tongue.gif", ":P");
                Insert("smile_tongue.gif", ":-P");
                Insert("smile_whatchutalkingabout.gif", ":|");
                Insert("smile_whatchutalkingabout.gif", ":-|");
                Insert("smile_wink.gif", ";-)");
                Insert("smile_wink.gif", ";)");
                Insert("smile_yawn.gif", "|-)");
                Insert("smile_zipit.gif", ":-#");
                Insert("smoking.gif", "(ci)");
                Insert("snail.gif", "(sn)");
                Insert("soccerball.gif", "(so)");
                Insert("star.gif", "(*)");
                Insert("sun.gif", "(#)");
                Insert("thumbs_down.gif", "(n)");
                Insert("thumbs_down.gif", "(N)");
                Insert("thumbs_up.gif", "(y)");
                Insert("thumbs_up.gif", "(Y)");
                Insert("turtle.gif", "(tu)");
                Insert("umbrella.gif", "(um)");
                Insert("xbox.gif", "(xx)");
                
                Insert("new.png", "(new)");
                Insert("hot.png", "(hot)");
                
        }
        function WideCharToChar(c){
                ;
                ;
                if (c.charCodeAt != null && String.fromCharCode != null){
                        var charCode = c.charCodeAt(0);
                        if (charCode > 0xfee0){
                                c = String.fromCharCode(charCode - 0xfee0);
                        }
                }
                return c;
        }
        function Match(tree, str, index){
                ;
                ;
                if (tree == null){
                        return null;
                }
                else if (tree.IsLeaf){
                        return tree;
                }
                else if (index >= str.length || index < 0){
                        return null;
                }
                else if (typeof(tree) == "object"){
                        var currentChar = str.charAt(index);
                        currentChar = WideCharToChar(currentChar);
                        return Match(tree[currentChar], str, index + 1);
                };
                return null;
        }
       function HopCount(str, index){
                ;
                if ("&" != str.charAt(index)){
                        return 1;
                }
                var result = 0;
                MainLoop:
                while (index < str.length && "&" == str.charAt(index)){
                        for (var p in entityList){
                                var entity = entityList[p];
                                if (index + entity.length <= str.length &&
                                        entity == str.substr(index,
                                        entity.length)){
                                        result += entity.length;
                                        index += result;
                                        continue MainLoop;
                                }
                        };
                }
                return result;
        }

        this.Replace = function(str){
                ;
                var result = "";
                if (str != null){
                        var i = 0;
                        var len = str.length;
                        while (i < len){
                                var j = i;
                                var e = Match(root, str, j);
                                while (j < len && null == e){
                                        j += HopCount(str, j);
                                        e = Match(root, str, j);
                                }
                                result += str.substr(i, j - i);
                                if (e != null){
                                        ;
                                        result += e.EmoticonToHtml();
                                  	
                                        j += e.Length();
                                }
                                i = j;
                        }
                }
                return result;
        };
        Initialize();
}
var globalEmoticons;
function EmoticonReplace(s){
        if (globalEmoticons == null){
                globalEmoticons = new Emoticons();
        }
        return globalEmoticons.Replace(s);
}

function MessageFormat(font, size, styleCode, color){
        this.font = font;
        this.size = size;
        this.styleCode = (styleCode == null ? "" : styleCode);
        this.color = color;
        this.ToggleStyle = function(styleCodeToggle){
                ;
                var result = false;
                if (styleCodeToggle.length == 1){
                        if (this.styleCode != null){
                                var index = this.styleCode.indexOf(styleCodeToggle);
                                if ( - 1 == index){
                                        result = true;
                                        this.styleCode += styleCodeToggle;
                                }
                                else{
                                        this.styleCode = this.styleCode.substring(0, index) + this.styleCode.substring(index + 1, this.styleCode.length);
                                }
                        }
                        else{
                                result = true;
                                this.styleCode = styleCodeToggle;
                        }
                }
                return result;
        };
        this.IsBold = function(){
                return ( - 1 != this.styleCode.indexOf("B"));
        };
        this.IsItalic = function(){
                return ( - 1 != this.styleCode.indexOf("I"));
        };
        this.IsStrikethrough = function(){
                return ( - 1 != this.styleCode.indexOf("S"));
        };
        this.IsUnderline = function(){
                return ( - 1 != this.styleCode.indexOf("U"));
        };
        this.ApplyForm = function(form){
                form.font.value = this.font;
                form.fontColor.value = this.color == null ? "black" : this.color;
                form.bold.value = this.IsBold() ? 1 : 0;
                form.underline.value = this.IsUnderline() ? 1 : 0;
                form.italic.value = this.IsItalic() ? 1 : 0;
        };
        this.ApplyStyle = function(obj){
                if (obj != null && typeof(obj.style) != "undefined"){
                        obj.style.fontFamily = this.font;
                        obj.style.fontSize = (this.size + "pt");
                        obj.style.color = this.color;
                        obj.style.fontStyle = this.IsItalic() ? "italic" : "";
                        obj.style.fontWeight = this.IsBold() ? "bold" : "";
                        var textDecoration = "";
                        if (this.IsUnderline()){
                                textDecoration += "underline ";
                        }
                        if (this.IsStrikethrough()){
                                textDecoration += "line-through";
                        }
                        obj.style.textDecoration = textDecoration;
                }
        };
        this.ApplyFormat = function(str){
                var f = "<span style=\"";
                if (this.font != null){
                        f += "font-family:" + EntityReplace(this.font) + "; ";
                }
                if (this.color != null){
                        f += "color:" + EntityReplace(this.color) + "; ";
                }
                if (this.IsBold()){
                        f += "font-weight:bold; ";
                }
                if (this.IsItalic()){
                        f += "font-style:italic; ";
                }
                if (this.IsUnderline() || this.IsStrikethrough()){
                        f += "text-decoration:";
                        if (this.IsUnderline()){
                                f += "underline ";
                        }
                        if (this.IsStrikethrough()){
                                f += "line-through";
                        }
                        f += "; ";
                }
                str = f + "\">" + str + "</span>";
                return str;
        };
}

function MessageFormat(font, size, styleCode, color){
        this.font = font;
        this.size = size;
        this.styleCode = (styleCode == null ? "" : styleCode);
        this.color = color;
        this.ToggleStyle = function(styleCodeToggle){
                ;
                ;
                var result = false;
                if (styleCodeToggle.length == 1){
                        if (this.styleCode != null){
                                var index = this.styleCode.indexOf(styleCodeToggle);
                                if ( - 1 == index){
                                        result = true;
                                        this.styleCode += styleCodeToggle;
                                }
                                else{
                                        this.styleCode = this.styleCode.substring(0, index) + this.styleCode.substring(index + 1, this.styleCode.length);
                                }
                        }
                        else{
                                result = true;
                                this.styleCode = styleCodeToggle;
                        }
                }
                return result;
        };
        this.IsBold = function(){
                return ( - 1 != this.styleCode.indexOf("B"));
        };
        this.IsItalic = function(){
                return ( - 1 != this.styleCode.indexOf("I"));
        };
        this.IsStrikethrough = function(){
                return ( - 1 != this.styleCode.indexOf("S"));
        };
        this.IsUnderline = function(){
                return ( - 1 != this.styleCode.indexOf("U"));
        };
        this.ApplyForm = function(form){
                form.font.value = this.font;
                form.fontColor.value = this.color == null ? "black" : this.color;
                form.bold.value = this.IsBold() ? 1 : 0;
                form.underline.value = this.IsUnderline() ? 1 : 0;
                form.italic.value = this.IsItalic() ? 1 : 0;
        };
        this.ApplyStyle = function(obj){
                ;
                ;
                if (obj != null && typeof(obj.style) != "undefined"){
                        obj.style.fontFamily = this.font;
                        obj.style.fontSize = (this.size + "pt");
                        obj.style.color = this.color;
                        obj.style.fontStyle = this.IsItalic() ? "italic" : "";
                        obj.style.fontWeight = this.IsBold() ? "bold" : "";
                        var textDecoration = "";
                        if (this.IsUnderline()){
                                textDecoration += "underline ";
                        }
                        if (this.IsStrikethrough()){
                                textDecoration += "line-through";
                        }
                        obj.style.textDecoration = textDecoration;
                }
        };
        this.ApplyFormat = function(str){
                var f = "<span style=\"";
                if (this.font != null){
                        f += "font-family:" + EntityReplace(this.font) + "; ";
                }
                if (this.color != null){
                        f += "color:" + EntityReplace(this.color) + "; ";
                }
                if (this.IsBold()){
                        f += "font-weight:bold; ";
                }
                if (this.IsItalic()){
                        f += "font-style:italic; ";
                }
                if (this.IsUnderline() || this.IsStrikethrough()){
                        f += "text-decoration:";
                        if (this.IsUnderline()){
                                f += "underline ";
                        }
                        if (this.IsStrikethrough()){
                                f += "line-through";
                        }
                        f += "; ";
                }
                str = f + "\">" + str + "</span>";
                return str;
        };
}


function ConversationWindow(){
	var transcriptDiv = null;
	var transcriptBody = null;
	var colorDiv = null;
	var emoticonDiv = null;
	var convToolbar = null;
	var format = new MessageFormat(L_IDS_COMPOSE_DEFAULT_FONT, L_IDS_COMPOSE_DEFAULT_SIZE, "", "black");

	this.SetFont = function(f){
			var format = this.GetConversationFormat();
			format.font = f;
			this.SetConversationFormat(format);
	};
	this.OnClickEmoticonPopup = function(cell){
			;
			;
			var title = cell.getAttribute("title");
			;
			;
			this.InsertComposeString(title);
			this.ShowEmoticonPopup(false);
	};
	this.OnClickColorPopup = function(cell){
			;
			;
			var color = cell.getAttribute("bgcolor");
			;
			;
			this.SetColor(color);
			this.ShowColorPopup(false);
	};
	this.SetColor = function(c){
			var format = this.GetConversationFormat();
			format.color = c;
			this.SetConversationFormat(format);
	};
	this.SetSize = function(s){
			var f = this.GetConversationFormat();
			f.size = s;
			this.SetConversationFormat(f);
	};
	this.ToggleStyle = function(styleCode){
			;
			var result = false;
			var f = this.GetConversationFormat();
			result = f.ToggleStyle(styleCode);
			this.SetConversationFormat(format);
			return result;
	};

	this.InsertMessageFrom = function(passport, displayname, msgText, format){
			; 
			if (msgText != null && msgText.length > 0){
					var nameHtml = "<span class=\"messageText\" title=\"" + EntityReplace(passport) + "\">" + EmoticonReplace(EntityReplace(FormatString(L_IDS_MSGR_NEW_IM_TEXT, displayname))) + "</span>";
					var msgHtml = NewlineReplace(LinkReplace(EmoticonReplace(EntityReplace(msgText))));
					if (format != null){
							msgHtml = format.ApplyFormat(msgHtml);
					}
					var d = new Date();
					msgHtml = "<div title=\"" + EntityReplace(d.toString()) + "\" style=\"padding-left:15px\">" + msgHtml + "</div>";
					this.InsertMessageHtml(FormatString(L_IDS_MSGR_NEW_IM_FORMAT, nameHtml, msgHtml));
			}
	};
	
	this.InsertMessageFromBot = function(passport, displayname, msgText, format){
		if (msgText != null && msgText.length > 0){
			//alert(msgText);
			var nameHtml = "<span class=\"messageText\" title=\"" + EntityReplace(passport) + "\">" + EmoticonReplace(EntityReplace(FormatString(L_IDS_MSGR_NEW_IM_TEXT, displayname))) + "</span>";
			//var exp = new RegExp("<IHTML>([.\\n]*)</IHTML>", "gi");
			var exp = new RegExp("<IHTML>(.|\n)*</IHTML>", "gi");
			var temp = msgText.match(exp);
			var msgHtml = ""; 
			if (temp == null) {
				if (msgText.substring(0,7)=="<IHTML>"){
					msgHtml=msgText.substring(7,msgText.length-8);
				}else{
					msgHtml = NewlineReplace(LinkReplace(EmoticonReplace(EntityReplace(msgText))));
				}
			} else {
				msgHtml = msgText.replace(temp[0],"$IHTML$");
				msgHtml = NewlineReplace(LinkReplace(EmoticonReplace(EntityReplace(msgHtml))));
				msgHtml = msgHtml.replace("$IHTML$",temp[0].substring(7,temp[0].length-8));
			}
			if (format != null){
				msgHtml = format.ApplyFormat(msgHtml);
			}
			var d = new Date();
			
			msgHtml = "<div title=\"" + EntityReplace(d.toString()) + "\" style=\"padding-left:15px\">" + msgHtml + "</div>";
			this.InsertMessageHtml(FormatString(L_IDS_MSGR_NEW_IM_FORMAT, nameHtml, msgHtml));
		}
	};
	
	this.ScrollToBottom = function(){
			;
			transcriptBody.scrollTop = 32000;
	};
	this.InsertMessageHtml = function(msgHtml){
			;
			transcriptDiv.innerHTML += msgHtml;
			this.ScrollToBottom();
	};
	this.UpdateConvToolbar = function(){
			if (convToolbar != null){
					convToolbar.UpdateBlockButton();
			}
	};

	this.SetTitle = function(title){
			try{
					;
					window.document.title = title;
			}
			catch (exception){
					;
			}
	};

this.OnLoad = function() {
	Get_AI_Result("help","SYS");
	//qingqiu dwr
// 		{k1:v1,k2:v2,....}
   /*var js = document.createElement("script");
   js.setAttribute("src","/robotcrm/resource/showEmoticon.do?jsonp=emoticon_callback");
   //body.head.appendChild(js);
   js.setAttribute("type","text/javascript");
   js.setAttribute("language","Javascript");
   document.getElementsByTagName("head")[0].appendChild(js);*/
   var req= new Ajax.Request("/robotcrm/resource/showEmoticon.do?jsonp=emoticon_callback",
			{
				method:"get",
				onSuccess:function(res){
					eval(res.responseText)
				}
			}
   );
   //emoticon_callback({"1158904759078.dat":"jay","1161603218375.dat":"bk","1158904541750.dat":"admin"});;
}



	this.OnUnload = function(){
		   
	};
	this.OnClickColor = function(){
			this.ShowEmoticonPopup(false);
			this.ShowColorPopup(!IsVisible(colorDiv));
	};
	this.OnClickEmoticon = function(){
			this.ShowColorPopup(false);
			this.ShowEmoticonPopup(!IsVisible(emoticonDiv));
	};
	this.HidePopups = function(){
			this.ShowColorPopup(false);
			this.ShowEmoticonPopup(false);
	};
	this.InsertComposeString = function(s){
			;
			;
			var composeBox = this.GetComposeBox();
			if (composeBox != null && composeBox.disabled == false){
					composeBox.value += s;
					this.DisableSendButton(false);
					var composeToolbar = this.GetComposeToolbar();
					;
					if (null != composeToolbar){
							;
							composeToolbar.SetFocus();
					}
			}
	};

	this.DisableSendButton = function(disableFlag){
			var sendButton = this.GetSendButton();
			if (sendButton != null){
					if (sendButton.disabled != disableFlag){
							sendButton.disabled = disableFlag;
							sendButton.className = disableFlag ? "sendButtonDisabled" : "sendButtonEnabled";
					}
			}
	};
	this.DisableComposeBox = function(disableFlag){
			var composeBox = this.GetComposeBox();
			if (composeBox != null){
					composeBox.disabled = disableFlag;
					composeBox.style.backgroundColor = disableFlag ? "#E0E0E0" : "white";
			}
	};
	this.DisableTranscript = function(disableFlag){
			if (IsTranscriptLoaded()){
					transcriptBody.className = disableFlag ? "disabledTranscript" : "enabledTranscript";
			}
	};
	this.ShowEmoticonPopup = function(showFlag){
			;
			if (emoticonDiv != null){
					if (showFlag){
							var emoticonPopupLeft = (6+32+32+24+24);
							var toolbarFrame = window.frames["composetoolbar"];
							;
							if (toolbarFrame != null){
									var emoticonImage = toolbarFrame.document.getElementById("emoticonImage");
									if (emoticonImage != null){
											emoticonPopupLeft = 6+emoticonImage.offsetLeft;
									}
							}
							if (transcriptBody != null){
									var b = transcriptBody;
									;
									;
									;
									emoticonDiv.style.left = Math.max(0, Math.min(b.clientWidth - 240-20, emoticonPopupLeft));
									emoticonDiv.style.top = Math.max(b.scrollHeight, b.clientHeight) - 151-6;
							}
					}
					
					ShowHide(emoticonDiv, showFlag);
			}
	};
	this.ShowColorPopup = function(showFlag){
			;
			if (colorDiv != null){
					if (showFlag){
							var colorPopupLeft = (6+32+32+24);
							var toolbarFrame = window.frames["composetoolbar"];
							;
							if (toolbarFrame != null){
									var colorImage = toolbarFrame.document.getElementById("colorImage");
									;
									if (colorImage != null){
											colorPopupLeft = 6+colorImage.offsetLeft;
									}
							}
							if (transcriptBody != null){
									var b = transcriptBody;
									;
									;
									;
									colorDiv.style.left = Math.max(0, Math.min(b.clientWidth - 100-20, colorPopupLeft));
									colorDiv.style.top = Math.max(b.clientHeight, b.scrollHeight) - 64-6;
							}
					}
					ShowHide(colorDiv, showFlag);
			}
	};
	this.OnTranscriptLoaded = function(div, body, color, emoticon){
			transcriptDiv = div;
			transcriptBody = body;
			colorDiv = color;
			emoticonDiv = emoticon;
			//this.SetConversationFormat(format);
			this.OnLoad();
	};
	this.OnToolbarLoaded = function(tb){
			convToolbar = tb;
			this.UpdateConvToolbar();
	};
	this.GetConvToolbar = function(){
			return convToolbar;
	};
	this.GetConversationFormat = function(){
			return format;
	};
	this.GetSendButton = function(){
			var result = null;
			var composeFrame = window.frames["compose"];
			if (composeFrame != null){
					var composeDocument = composeFrame.document;
					if (composeDocument != null){
							result = composeDocument.getElementById("sendButton");
					}
			}
			return result;
	};
	this.GetComposeToolbar = function(){
			var result = null;
			var toolbarFrame = window.frames["composetoolbar"];
			if (toolbarFrame != null){
					result = toolbarFrame.composeToolbar;
			}
			return result;
	};
	this.GetComposeBox = function(){
			var result = null;
			var composeFrame = window.frames["compose"];
			if (composeFrame != null){
					var composeDocument = composeFrame.document;
					if (composeDocument != null){
							result = composeDocument.getElementById("textBox");
					}
			}
			return result;
	};
	this.GetComposeForm = function(){
			var result = null;
			var composeFrame = window.frames["compose"];
			if (composeFrame != null){
					var composeDocument = composeFrame.document;
					if (composeDocument != null){
							result = composeDocument.forms["composeForm"];
					}
			}
			return result;
	};
	this.OnChatWindowResize = function(){
	this.ScrollToBottom();
	};
	this.SetConversationFormat = function(f){
			this.HidePopups();
			;
			if (f != null){
					var composeForm = this.GetComposeForm();
					if (composeForm != null){
							f.ApplyForm(composeForm);
					}
					var composeBox = this.GetComposeBox();
					if (composeBox != null){
							f.ApplyStyle(composeBox);
					}
					var composeToolbar = this.GetComposeToolbar();
					if (null != composeToolbar){
							composeToolbar.SetFormat(f);
					}
					if (transcriptDiv != null){
							transcriptDiv.style.fontSize = (f.size + "pt");
					}
					this.ScrollToBottom();
			}
	};
	
	
	this.SetTitle(L_IDS_COVERSATION_TITLE);
	
}

function ComposeToolbar(){
        var conversationWindow = null;
        var selectFont = null;
        var selectSize = null;
        var cellItalic = null;
        var cellBold = null;
        var cellUnderline = null;
        this.SetFont = function(f){
                if (conversationWindow != null){
                        conversationWindow.SetFont(f);
                }
        };
        this.SetSize = function(s){
                ;
                if (conversationWindow != null){
                        conversationWindow.SetSize(s);
                }
        };
        this.ToggleStyle = function(styleCode, cell){
                if (conversationWindow != null){
                        var styleToggle = conversationWindow.ToggleStyle(styleCode);
                        if (cell != null){
                                cell.style.background = styleToggle ? "#2053C8" : "#EBF1FA";
                        }
                        this.SetFocus();
                }
        };
        this.SetFocus = function(){
                var messageText = FindObject("textBox");
                if (null != messageText && messageText.focus != null && messageText.disabled == false){
                        if (IsIE("MSIE 6")){
                                messageText.focus();
                                SetCaretAtEnd(messageText);
                        }
                        setTimeout(function(){
                                messageText.focus();
                        }
                        , 100);
                }
                else{
                        ;
                }
        };
        this.SetFormat = function(format){
                if (format != null){
                        selectFont.value = format.font;
                        selectSize.value = format.size;
                        cellItalic.style.background = format.IsItalic() ? "#2053C8" : "#e7f0df";
                        cellBold.style.background = format.IsBold() ? "#2053C8" : "#e7f0df";
                        cellUnderline.style.background = format.IsUnderline() ? "#2053C8" : "#e7f0df";
                }
        };
        this.Initialize = function(){
              
                var format = null;
                if (window.parent != null){
                        conversationWindow = window.parent.conversationWindow;
                        ;
                        if (conversationWindow != null){
                                format = conversationWindow.GetConversationFormat();
                        }
                }
                selectFont = document.getElementById("selectFont");
                selectSize = document.getElementById("selectSize");
                cellItalic = document.getElementById("cellItalic");
                cellBold = document.getElementById("cellBold");
                cellUnderline = document.getElementById("cellUnderline");
                ;
                ;
                var sizes = L_IDS_COMPOSE_SIZES.split(",");
                 for (var i=0;i<sizes.length;i++){
                        var o = document.createElement("option");
                        o.text = sizes[i];
                        o.value = sizes[i];
                        selectSize.options.add(o);
                }
                var sizeCell = document.getElementById("sizeCell");
                ;
                if (sizeCell != null){
                        sizeCell.width = selectSize.clientWidth;
                }
                var fonts = L_IDS_COMPOSE_FONTS.split(",");
                for (var i=0;i<fonts.length;i++){
                        var o = document.createElement("option");
                        o.text = fonts[i];
                        o.value = fonts[i];
                        selectFont.options.add(o);
                }
                var fontCell = document.getElementById("fontCell");
                ;
                if (fontCell != null){
                        fontCell.width = selectFont.clientWidth;
                }
                this.SetFormat(format);
        };
        this.Initialize();
}

function show_help(){
	OpenWindow=window.open("http://www.funnyai.com/AI/help.aspx");
}
function emoticon_callback(data) {
	if (globalEmoticons == null)
	 globalEmoticons = new Emoticons();
	for (var key in data) {
		globalEmoticons.Insert(key,data[key]);
	}
}