var openid = "";
var visitorid = "";
var sessionid = "";
var userid = 0;
var showname = "";

var sendtype = "enter";

var httpRequestTimerObj = null;

var g_timeout_id = null;
var g_oldtitle = '';

function lTrim(str)  
{  
  if (str.charAt(0) == " ")  
  {  
    //如果字串左边第一个字符为空格  
    str = str.slice(1);//将空格从字串中去掉  
    //这一句也可改成 str = str.substring(1, str.length);  
    str = lTrim(str);    //递归调用  
  }  
  return str;  
}  
//rTrim()去掉字串右边的空格  
function rTrim(str)  
{  
  var iLength;  
  iLength = str.length;  
  if (str.charAt(iLength - 1) == " ")  
  {  
    //如果字串右边第一个字符为空格  
    str = str.slice(0, iLength - 1);//将空格从字串中去掉  
    //这一句也可改成 str = str.substring(0, iLength - 1);  
    str = rTrim(str);    //递归调用  
  }  
  return str;  
}  
//trim()去掉字串两边的空格  
function trim(str)  
{  
  return lTrim(rTrim(str));  
}   
//时间格式
Date.prototype.format = function(format) { 
  var o = { 
    "M+" : this.getMonth()+1, //month 
    "d+" : this.getDate(),    //day 
    "h+" : this.getHours(),   //hour 
    "m+" : this.getMinutes(), //minute 
    "s+" : this.getSeconds(), //second 
    "q+" : Math.floor((this.getMonth()+3)/3),  //quarter 
    "S" : this.getMilliseconds() //millisecond 
  } 
  if(/(y+)/.test(format)) format=format.replace(RegExp.$1, 
    (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
  for(var k in o)if(new RegExp("("+ k +")").test(format)) 
    format = format.replace(RegExp.$1, 
      RegExp.$1.length==1 ? o[k] : 
        ("00"+ o[k]).substr((""+ o[k]).length)); 
  return format; 
} 
//字符串replaceAll
String.prototype.replaceAll = function(s1,s2){   
var r = new RegExp(s1.replace(/([\(\)\[\]\{\}\^\$\+\-\*\?\.\"\'\|\/\\])/g,"\\$1"),"ig");
return this.replace(r,s2);
}
//获取对象位置X
function getX(obj) {  
	var parObj=obj;    
	var left=obj.offsetLeft;    
	while(parObj=parObj.offsetParent){    
		left+=parObj.offsetLeft;    
	}    
	return left;    
}    
//获取对象位置Y
function getY(obj) {    
	var parObj=obj;    
	var top=obj.offsetTop;    
	while(parObj = parObj.offsetParent){    
		top+=parObj.offsetTop;    
	}    
	return top;    
}  
//取InnerText(兼容)
function GetInnerText(obj) {
	if (typeof obj.innerText == "undefined") {
		return obj.textContent;
	} else {
		return obj.innerText;
	}
}
//设置InnerText(兼容)
function SetInnerText(obj, text) {
	if (typeof obj.innerText == "undefined") {
		obj.textContent = text;
	} else {
		obj.innerText = text;
	}
}
//比较字符串
function CompareStr(s1, s2) {
	var len = s1.length;
	if (len > s2.length) len = s2.length;
	
	for (var i=0; i<len; i++) {
		if (s1.charCodeAt(i) > s2.charCodeAt(i)) {
			return 1;
		} else if (s1.charCodeAt(i) < s2.charCodeAt(i)) {
			return -1;
		}
	}
	return (s1.length > s2.length) ? 1 : 0;
}
//取url参数
function GetRequest() { 
   var url = location.search; //获取url中"?"符后的字串 
   var theRequest = new Object(); 
   if (url.indexOf("?") != -1) {  
      var str = url.substr(1); 
      strs = str.split("&"); 
      for(var i = 0; i < strs.length; i ++) {  
         theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]); 
      } 
   } 
   return theRequest; 
} 
//添加监听
function addListener(element,e,fn) {
	element.addEventListener?element.addEventListener(e,fn,false):element.attachEvent("on" + e,fn);
}   
//删除监听
function removeListener(element,e,fn) { 
	element.removeEventListener?element.removeEventListener(e,fn,false):element.detachEvent("on" + e,fn);
}
//统计字符数量
function countCharacters(str) {
    var totalCount = 0;  
    for (var i=0; i<str.length; i++) {  
        var c = str.charCodeAt(i);  
    if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {  
           totalCount++;  
        }else {     
            totalCount+=2;  
        }  
    }
    return totalCount;
}
//IconBtnMouseOver
function IconBtnMouseOver(div) {
	div.className = 'IconBtnHover';
}
//IconBtnMouseDown
function IconBtnMouseDown(div) {
	div.className = 'IconBtnDown';
}
//IconBtnMouseUp
function IconBtnMouseUp(div) {
	div.className = 'IconBtnHover';
}
//IconBtnMouseOut
function IconBtnMouseOut(div) {
	div.className = 'IconBtn';
}
//IconBtnMouseOver_Max
function IconBtnMouseOver_Max(div) {
	div.className = 'IconBtnHover_Max';
}
//IconBtnMouseDown_Max
function IconBtnMouseDown_Max(div) {
	div.className = 'IconBtnDown_Max';
}
//IconBtnMouseUp_Max
function IconBtnMouseUp_Max(div) {
	div.className = 'IconBtnHover_Max';
}
//IconBtnMouseOut_Max
function IconBtnMouseOut_Max(div) {
	div.className = 'IconBtn_Max';
}
//清除窗口闪烁
function clearblinktitle() {
  clearInterval(g_timeout_id);
  g_timeout_id = null;
  document.title = g_oldtitle;
}
//窗口闪烁
function blinktitle(msg) {
  if (typeof(g_timeout_id) != "undefined" && g_timeout_id) {
    clearInterval(g_timeout_id);
  }
  g_timeout_id = setInterval(function() {
      document.title = (document.title == msg) ? g_oldtitle : msg;
    }, 500);
}
//保存聊天记录
function SaveText(filename, content) {
	var objForm = document.getElementById('__SaveTextForm__'); 
	if (objForm) document.body.removeChild(objForm);

	objForm = document.createElement("FORM");
	objForm.id = '__SaveTextForm__';
	objForm.action = 'savetext.php';
	objForm.method = 'post';
	objForm.target  = '_blank';

	var objTextInput = document.createElement("INPUT");
	objTextInput.type = 'text';
	objTextInput.name = 'filename';
	objTextInput.value = filename;
	objForm.appendChild(objTextInput);

	var objTextArea = document.createElement("TEXTAREA");
	objTextArea.name = 'content';
	objTextArea.value = content;
	objForm.appendChild(objTextArea);

	document.body.appendChild(objForm);

	objForm.submit();
}
//生成聊天消息格式文本
function makeTalkingMessage(SenderName, MsgContext, MsgTime, IsHistory) {
	var strHeadColor = "#00a2e8";
	var strMsgContextColor = "#00a2e8";
	if (SenderName == "") {
		 strHeadColor = "#22b14c";
		 strMsgContextColor = "#22b14c";
		 SenderName = "访客" + visitorid;
	}

    if (IsHistory == true) {
		strHeadColor = "#c0c0c0";
		strMsgContextColor = "#c0c0c0";
    }

	var dateformat = "yyyy-MM-dd ";
	var shortmsgtime = MsgTime.substr(dateformat.length);
    var strHead = SenderName + '&nbsp;<font style="color:' + strHeadColor + ';font-weight:normal;">' + shortmsgtime + '</font>';

    var strHtml = '<div style="clear:both;margin:0;padding:2px 0 0 0;overflow:hidden;text-align:left;font-family:宋体,Arial;color:'+
		strHeadColor+';font-size:11pt;font-weight:bold;">' + strHead + '</div>' +
        '<div style="clear:both;margin:0;padding:2px 0 2px 16px;width:500px;overflow:hidden;text-align:left;font-family:宋体,Arial;color:'+
		strMsgContextColor+';font-size:11pt;word-break:break-all;">' + MsgContext + '</div>';
    return strHtml;
}
//过滤聊天表情
function FilterEmotionHtml(msgText) {
	if (msgText.indexOf("[EM]") != -1)
	{
		for (var i=0; i<EmotionNameArray.length; i++)
		{
			var imghtml = '<img src="images/emotions/' + EmotionFileArray[i] + '" border="0"/>';
			msgText = msgText.replaceAll(EmotionNameArray[i], imghtml);
		}
	}
	return msgText;
}
//添加聊天消息
function addMessage(msgText) {
	var objDiv = document.getElementById('Chatboard');
	objDiv.innerHTML = objDiv.innerHTML + FilterEmotionHtml(msgText);
	objDiv.scrollTop = objDiv.scrollHeight;
}
//发送聊天消息回调
var sendMessageWhenDone = function(oXML) { 
	//var strStatus = oXML.responseText;
};
//发送聊天消息
function sendMessage() {	
	var objTxtEdit = document.getElementById('txtEdit');

	var msg = trim(objTxtEdit.value);
	msg = msg.replaceAll('&', '&amp;');
	msg = msg.replaceAll('<', '&lt;');
	msg = msg.replaceAll('>', '&gt;');
	msg = msg.replaceAll('"', '&quot;');
	msg = msg.replaceAll("\'", '&apos;');
	msg = msg.replaceAll("\r\n", "<br>");
	msg = msg.replaceAll("\r", "<br>");
	msg = msg.replaceAll("\n", "<br>");	
	if (msg == "") return;

	var msg_send = trim(objTxtEdit.value);
	msg_send = msg_send.replaceAll('&', '&amp;');
	msg_send = msg_send.replaceAll('<', '&lt;');
	msg_send = msg_send.replaceAll('>', '&gt;');
	msg_send = msg_send.replaceAll('"', '&quot;');
	msg_send = msg_send.replaceAll("\'", '&apos;');
	if (msg_send == "") return;

	var msgtime = new Date().format("yyyy-MM-dd hh:mm:ss");

	addMessage(makeTalkingMessage("", msg, msgtime, false));
	objTxtEdit.value = "";
	objTxtEdit.focus();

	var myConn = new XHConn();
	if (!myConn) return;

	var sVars = "content=%visitorid%:" + visitorid + "%to%:" + userid + 
	    "%showname%:" + showname + "%message%:" + msg_send + "%msgtime%:" + msgtime;
	myConn.connect("sendmessage.php", "POST", sVars, sendMessageWhenDone);
}
//更改发送按键
function changeSendType() {
	if (sendtype == "enter") {
		sendtype = "ctrl-enter";
		SetInnerText(document.getElementById('sendTypeText'), "Ctrl+Enter");
	} else {
		sendtype = "enter";
		SetInnerText(document.getElementById('sendTypeText'), "Enter");
	}
}
//按键事件
function checkKeyUp(evt) {
	evt = (evt) ? evt : ((window.event) ? window.event : "");
	var ctrlKey = (evt.ctrlKey) ? evt.ctrlKey : (evt.which == 17);
	var keyCode = evt.keyCode ? evt.keyCode : evt.charCode;

	if (sendtype == "enter") {
		if (keyCode == 13) {
			sendMessage();
			if(typeof(evt.cancelBubble)!=undefined && evt.cancelBubble!=null)
				evt.cancelBubble = true;
			else 
				evt.preventDefault();
		}
	} else {
		if (ctrlKey && (keyCode == 13)) {
			sendMessage();
			if(typeof(evt.cancelBubble)!=undefined && evt.cancelBubble!=null)
				evt.cancelBubble = true;
			else 
				evt.preventDefault();
		}
	}//if
}
//选择表情
function SelectEmotions()
{
	var RW_bodywidth = document.body.offsetWidth;
	var RW_bodyheight = document.body.offsetHeight;

	var btn = document.getElementById('EmotionBtn');
	var BtnLeft = getX(btn);
	var BtnTop = getY(btn);

	var win = document.getElementById('EmotionSelectWin');
	win.style.left = BtnLeft + 'px';
	win.style.top = (BtnTop - 212) + 'px';
	win.style.display = 'block';
	document.getElementById('EmotionSelectFrame').src = 'emotions.html';
}
//保存按钮
function SaveChatText()
{
	var objChatboard = document.getElementById('Chatboard');
	var subdivs = objChatboard.getElementsByTagName('DIV');
	var strContent = '';
	for (var i=1;i<subdivs.length;i++)
	{
		strContent += GetInnerText(subdivs[i]) + '<br/>';
	}
	SaveText('你与 '+showname+'('+userid+') 的聊天记录', strContent);
}
//服务评价
function ServiceEvaluate()
{
	var RW_bodywidth = document.body.offsetWidth;
	var RW_bodyheight = document.body.offsetHeight;

	var win = document.getElementById('ServiceEvaluteWin');
	win.style.left = parseInt((RW_bodywidth - 400) / 2) + 'px';
	win.style.top = parseInt((RW_bodyheight - 62) / 2) + 'px';
	win.style.display = 'block';
	document.getElementById('ServiceEvaluteFrame').src = 'evaluate.php';
}
//激发一个表情被选择事件
function emotion_handler_click(div)
{
	HideAllToolWin();
	var emotion = div.innerHTML;
	document.getElementById('txtEdit').value += emotion;
	document.getElementById("txtEdit").focus();
}
//隐藏所有ToolWin
function HideAllToolWin()
{
	if (document.getElementById('EmotionSelectWin').style.display != 'none')
	{
		document.getElementById('EmotionSelectWin').style.display = 'none';
		document.getElementById('EmotionSelectFrame').src = '';
	}

	if (document.getElementById('ServiceEvaluteWin').style.display != 'none')
	{
		document.getElementById('ServiceEvaluteWin').style.display = 'none';
		document.getElementById('ServiceEvaluteFrame').src = '';
	}
}
//鼠标按下事件
function onmousedown(e) 
{
	var evt = e?e:((window.event)?window.event:null);
	if (!evt) return false;

	var targ;
	if (evt.target) targ = evt.target;
	else if (evt.srcElement) targ = evt.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
	   targ = targ.parentNode;

	clearblinktitle();
	HideAllToolWin();
}
//会话心跳态状
var httpWhenDone_GetSessionStatus = function(oXML) { 
	var strStatus = oXML.responseText;

	var lIndex = -1;

	//Message
	lIndex = strStatus.indexOf("%Message%=");
	if (lIndex >= 0) {
		var strTemp = "%Message%=";
		var strMessage = strStatus.substr(strTemp.length, strStatus.length - strTemp.length);
		if (typeof strMessage == "undefined") return;
		if (strMessage.length == 0) return;
		
		var MessageArray = strMessage.split('|');
		
		var strMessage = trim(MessageArray[0]);
		var strDateTime = trim(MessageArray[1]);

		strMessage = strMessage.replaceAll("%split%", "|");
		strMessage = strMessage.replaceAll("%enter%", "<br>");

		if (strMessage != '') {
			blinktitle("有新消息！");
			addMessage(makeTalkingMessage(showname, strMessage, strDateTime, false));
		}
		return;
	}

	//Loss
	lIndex = strStatus.indexOf("%LOSS%");
	if (lIndex >= 0) {
		clearInterval(httpRequestTimerObj);
		window.opener=null;window.open('','_self');window.close();
		return;
	}
};
//心跳时钟
function httpRequestTimer() {
	var myConn = new XHConn();
	if (!myConn) return;
	
	var strUrl = "getsessionstatus.php?random=" + Math.random();

	myConn.connect(strUrl, "POST", "openid=" + openid, httpWhenDone_GetSessionStatus);
}
//页面关闭退出回调
var httpWhenDone_OnPageUnload = function(oXML) {
	//var strStatus = oXML.responseText;
}
//页面加载事件
function OnPageLoad() {
	httpRequestTimerObj = setInterval(httpRequestTimer, 1000);
}
//页面关闭事件
function OnPageUnload() {
	if (httpRequestTimerObj) {
		clearInterval(httpRequestTimerObj);
		httpRequestTimerObj = null;
	}

	var myConn = new XHConn();
	if (!myConn) return;

	var strUrl = "endsession.php?random=" + Math.random();

	myConn.connect(strUrl, "POST", "visitorid=" + visitorid, httpWhenDone_OnPageUnload);
}
window.onunload = function () {
	//OnPageUnload();
};
document.onkeydown = function() { 
	clearblinktitle(); 
};
document.onmousedown = onmousedown;  // for all others