var $ = function (name) {
	return document.getElementById(name);
};

function createHupooXmlHttpObject() {
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/

  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try { xmlhttp = new XMLHttpRequest(); } catch (e) { xmlhttp = false; }
  }
  return xmlhttp;
}

function ajax_sendmsg(url,async,method,para,feedback){
   var dateStr = "&date="+new Date().getTime();
   if (url.indexOf("http") == 0) {	//cross domain, use proxy
   	 url = "proxy.do?url=" + encodeURIComponent(url)
   }
   var sendUrl=url + dateStr;
   var xmlhttp=createHupooXmlHttpObject();
   if (xmlhttp.readyState == 4 || xmlhttp.readyState == 0) {
	 xmlhttp.open(method,sendUrl,async);
	 xmlhttp.onreadystatechange = function () {
		if (xmlhttp.readyState == 4){
			var strResponse=xmlhttp.responseText;
			if(xmlhttp.status==200){
				if (feedback !=null&&feedback !=undefined){
					feedback(strResponse);
				}
			}
			delete xmlhttp;
			xmlhttp = null;
		}
     }
  	 if(method=="GET") {
		xmlhttp.send(null);
 	 } else {  
 	 	xmlhttp.send(para); 
 	 }
   }
}

//effects
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function CW_showDiv(divID) {
	var divObj = $(divID);
	if (divObj != null && divObj != undefined) {
		divObj.style.display = "block";
	}
}

function CW_divVisible(divID) {
	var divObj = $(divID);
	if (divObj != null && divObj != undefined) {
		if (divObj.style.display == "block" || divObj.style.display == "inline") {
			return true;
		}
	}
	return false;
}

function CW_hideDiv(divID) {
	var divObj = $(divID);
	if (divObj != null && divObj != undefined) {
		divObj.style.display = "none";
	}
}

function CW_setDivText(divID, text) {
	var divObj = $(divID);
	if (divObj != null && divObj != undefined) {
		divObj.innerText = text;
	}
}

//=============================== i18n text ==============================
var I18N_MSG_VOICE_CONNECT = "Connecting...";
var I18N_SYSTEM_MSG = "System Message";
var I18N_FILE_SEND_ERROR = "Failed to send file.";
var I18N_IMAGE_SEND_ERROR = "Failed to send image.";
var I18N_INVALID_FILE_TYPE = "Invalid file type. Failed to send.";
var I18N_FILE_SEND = "File has been send: ";

var I18N_RECEIVE_FILE_MESSAGE = "send a file to you:";

var I18N_FREE_CALL_SEND = "Call has heen sent successfully. Please wait...";
var I18N_FREE_CALL_FAILED = "Call failed.";
var I18N_FREE_CALL_FAILED_ERR_TIMEOUT = "Call failed. Time out.";
var I18N_FREE_CALL_FAILED_ERR_NOMONEY = "Call failed. No money.";

var I18N_NOT_SUPPORTED = "Not supported by your browser.";
var I18N_SOUND_NOT_SUPPORTED = "Sound not supported by your browser.";
var I18N_VOICE_ENGINE_CONFIRM = "No voice engine installed, install now?";

var I18N_JINGLE_INCOMING_CALL = "Incoming call. Accept?";
var I18N_JINGLE_REJECT_CALL = "Agent has reject your call.";
var I18N_JINGLE_TERMINATE_CALL = "Call has been terminated.";
var I18N_JINGLE_OVERTIME = "Call overtime.";

var I18N_LOG_SEND_SUCCESS_MSG = "Chat log has been successfully send to: ";
var I18N_LOG_SEND_FAIL_MSG = "Send chat log failed to: ";
//=============================== interface =============================
var __chatID;
var __agentID;
var __workgroup;
var __email;	//visitor email;
var __lang;
var __dwrObj;
var __webchatHost;
var __websiteHost;//www.imcaller.com
var __domain;
var __uploadFolder;
var __userNickname;

var __voiceFileUrl;	//voice file url

var __emotions;
var __AllEmotions;

var __red5Host;
var __surveyUrl;

var __lastSuveryJid;
var __hideContactPanel;	//hide panel

//============================== chat common ============================
var soundFlag = false;
function funcSupported() {
	if (document.all) return true;
	return false;
}

//detect ff sound plugin
function hasSoundPlugin() {
	if (funcSupported()) return true;
	var plugins = navigator.plugins;
	if( plugins.length == 0 ) {
        return false;
    }
	var i;
	for(i=0;i<plugins.length;i++){
		if (plugins[i]==null||plugins[i]=="undefined")continue;
		if (plugins[i].name.indexOf("QuickTime")>=0) {
			return true;
		}
	}
    return false;
}

//set tag
function setShowMessage() {
	if (!hasSoundPlugin()) {
	     alert(I18N_SOUND_NOT_SUPPORTED);
	     return;
	}
	var sounds = $("tb_sound");
	if (sounds != null) {
		soundFlag = !soundFlag;
		var col = "";
		var imgSrc = "tool_nosound.gif";
		if (soundFlag) {
			col = "#AAD7EE";
			imgSrc = "tool_sound.gif";
			
			if (!funcSupported()) {//firefox
				if ($("msg_snd_div")==null) {
					var divObj = document.createElement("div");
					if (divObj != null) {
						divObj.id = "msg_snd_div";
						divObj.innerHTML = "<embed src='sound/msg.wav' type='audio/wav' autostart='false' name='msg_snd_ff' width='0' height='0'></embed>";
						document.body.appendChild(divObj);
					} 
				}
			}
		}
		sounds.style.backgroundColor = col;
		$("snd_img").src = "skin/new/" + imgSrc;
	}
}

function iePlaySnd(){
	var obj = $("msg_snd");
	if (obj == null) {
		obj = document.createElement("bgsound");
		if (obj != null) {
			obj.loop="1";
			obj.id = "msg_snd";
			obj.style.display="none";
			document.body.appendChild(obj);
		} 
	}
	obj.src="sound/msg.wav";
}

function showMessageHint() {
	window.focus();
    if (soundFlag) {
    	if (funcSupported()) {	//ie
    		iePlaySnd();
    	} else {	//ff
    		try{ eval("document.msg_snd_ff.Play()"); }catch(e){}
    	}
    }
}

var counter = 0;

function isTypingNotification() {
   __dwrObj.customerIsTyping(__chatID);
}

function chatHasEnded(){
  //do chat end
}

function handleKeyEvent(evt) {
    evt = (evt) ? evt : ((window.event) ? window.event : "");
    var enterPressed = ((document.all) ? evt.keyCode==13 : evt.which==13);
    //alert(evt.keyCode);
    if (enterPressed) {
    	//alert("enter");
        submitMessage();
    }
    else {
      if( counter == 5 ) {
        isTypingNotification();
        counter = 0;
      } else {
        counter++;
      }
    }
}

function addDisplayText(from, body) {
  addChatText(window.frames['yak'], from, body);	//in common.js
  scrollYakToEnd(window.frames['yak']);
}

var delta = 0;
function adjustMsgWindow(smaller, divId) {
  var ele = $("chatFrame");
  if (ele != null) {
  	
  	if (divId!=null) {
  		delta = $(divId).offsetHeight;
  	}
    if (smaller) {
    	ele.style.height = ele.offsetHeight - delta;
    } else { ele.style.height = ele.offsetHeight + delta;
    delta=0; };
  }
  scrollYakToEnd(window.frames['yak']);
}

function submitMessage() {
    var val = _chatEditor.getContent();
	visitorSendMessage(val);
    // reset the chatbox textarea
    _chatEditor.clear();
}

function visitorSendMessage(msg) {
	if (msg == null) return;
	var chatText = msg.trim(); 
	if (chatText != "") {
         //replace <p>&nbsp;</p>, <p>, </p>
        var brIdx=chatText.lastIndexOf("<br><br>");
        if (brIdx > 0) {
        	chatText = chatText.substring(0, brIdx);
        }
        chatText = chatText.replace(/<P>&nbsp;<\/P>/gi,"");
		chatText = chatText.replace(/<P>/gi,"");
		chatText = chatText.replace(/<\/P>/gi,"");
		
		chatText = chatText.trim();
		if (chatText!="") {
	        chatText = "<div style=\"" + _chatEditor.getEditorStyle() + "\">"+chatText+"</div>";
				  
            var selfMsg = "<div style=\"margin-left:12px;\">" + chatText + "</div>";
            __dwrObj.sendMessage(__chatID, chatText, chatText); //msg, rtf
            addDisplayText(__userNickname, selfMsg);
        }
    }
}

function receiveMessage(message) {
	__lastSuveryJid = message.jid;	//save last jid for survey
	var from = message.from;
	var body = message.body;
	var rtf = message.rtf;
	var msgType = message.msgType;
	//check message type
	if (msgType == 1){
		var pos1 = body.lastIndexOf("/")+1;
		var filename = body.substring(pos1,body.length);
               
		body = "<div style='margin-left: 12px;'>" + I18N_RECEIVE_FILE_MESSAGE + 
			"<a href='"+message.body+"' target='_blank'>"+filename+"</a></div>";

		addDisplayText(from, body);

		showMessageHint();
	} else if (msgType==2){ //check if message is image, replace same id
		try {
			var url = body;
			var id1 = url.lastIndexOf("/")+1;
			var imgId = url.substring(id1,url.length);
		} catch(e){ 
			alert(e.message);
		}
		var o=$("chatFrame").contentWindow.document.getElementById(imgId);

		if (o!=null){
			o.src = url;
 			o.id = "";
		} 
	} else {
		rtf = ReplaceEmotion(rtf);
		rtf = "<div style=\"margin-left: 12px;\">" + rtf + "</div>";
		addDisplayText(from, rtf);

		showMessageHint();
	}
}

function resizeWindow(){
	var body_height = document.body.clientHeight + 60;	//no toolbar	
	
	if(body_height<470) body_height=470;
		
	var ad_div_height = 0;
	if ($("main_ad_frame").src!="about:blank") ad_div_height= 60;
	var bannerDelta=0;
	if ($("main_chat_logo")) bannerDelta = 75;
	var cmpinfo_div = $("company_info");
	var browser_dif = 2;
	if (document.all) browser_dif = 0;
	var cmpInfoHeight=body_height-127 + browser_dif -bannerDelta - ad_div_height;
	cmpinfo_div.style.height=cmpInfoHeight+"px";
	
	$("video_area").style.height=cmpinfo_div.style.height;
	$("video_chat_frame").style.height=(cmpInfoHeight-30)+"px";
	
	$("queue_div").style.height = (body_height-127 -bannerDelta + browser_dif - ad_div_height)+"px";
	$("chatFrame").style.height = (body_height-266 -bannerDelta-delta + browser_dif - ad_div_height)+"px";
	$("message_window").style.height = (body_height-239-bannerDelta + browser_dif - ad_div_height)+"px";
	
	//width
	var body_width = document.body.clientWidth;
	var videoWidth=0;
	if (CW_divVisible("video_area")) {
		videoWidth=223;
	}
	//var mainWidth=(body_width-172-videoWidth)+"px";
}

function showLeftPanel() {
	CW_showDiv("left_bar");
	$("chat_area").style.marginLeft="160px";
	$("queue_div").style.marginLeft="160px";
}
function hideLeftPanel() {
	if (__hideContactPanel) {
		CW_hideDiv("left_bar");
		$("chat_area").style.marginLeft="0px";
		$("queue_div").style.marginLeft="0px";
	}
}
//=============================== tool bar ==========================
var font_toolbar_shown = false;
var upload_toolbar_shown = false;
var emotion_panel_shown = false;
var freePhone_panel_shown = false;

function setBtnChecked(btnId, checked) {
	var col = "";
	if (checked) col = "#9ABACF";
	$(btnId).style.backgroundColor = col;
}

//=============================== print, mail & save =======================
function openSurveyUrl() {
	window.open(__surveyUrl + __lastSuveryJid, 'surveywin', 'width=560,height=450,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');
}

function submitChatLog(method) {
	var f = $("cw_save_form");
	if(f==null) { 
		alert("Save chat log error.");
		return;
	}
	var sc = $("cw_save_content");
	sc.value = window.frames['yak'].document.body.innerHTML;
	var sm = $("cw_save_method");
	sm.value=method;
	if (method=="save" && (document.all)) {
		f.target="_blank";
	} else {
		f.target="log_frame";
	}
	f.submit();
}
function saveChat(){
  	submitChatLog("save");
}

var firstShowMailDiv = true;

function showMailDiv(show) {
	if (show) {
		if (firstShowMailDiv) {
			$('chat_log_mail_input').value=__email;
			firstShowMailDiv = false;
		}
		CW_showDiv('chat_log_mail_div');
	} else {
		CW_hideDiv('chat_log_mail_div')
	}
}

function mailChat() {
	__email = $('chat_log_mail_input').value;
	if (__email != null && __email.length>0) {
		submitChatLog(__email);
	} else {
		$('chat_log_mail_input').focus();
	}
}

function mailChatFinished(success) {
	var msg = "";
	if (success) {
		msg = I18N_LOG_SEND_SUCCESS_MSG + __email;
	} else {
		msg = I18N_LOG_SEND_FAIL_MSG + __email;
	}
	addDisplayText(I18N_SYSTEM_MSG, msg);
}

function printChat() {
	window.frames['yak'].print();
}
//============================== end print, mail & save =====================

//============================== free phone ==========================
function showFreePhoneBar(visible) {
  if (visible) { //show
	if (!freePhone_panel_shown) {
		CW_showDiv("freePhoneDiv");
		adjustMsgWindow(true, "freePhoneDiv");
		freePhone_panel_shown = true;
		setBtnChecked("tb_phone", true);
	} 
  } else { //hide
  	if (freePhone_panel_shown) {
		adjustMsgWindow(false, "freePhoneDiv");
		CW_hideDiv("freePhoneDiv");
		freePhone_panel_shown = false;
		setBtnChecked("tb_phone", false);
	} 
  }
}

function switchFreePhoneBar() {
	showUploadBar(false);
	showEmotionPanel(false);
	showFontBar(false);
	showFreePhoneBar(!freePhone_panel_shown);
	hidePalette();
}

function callResponse(rsTxt) {
    if ("OK"==rsTxt.trim()) {
    	addDisplayText(I18N_SYSTEM_MSG, I18N_FREE_CALL_SEND);
    } else if ("ERROR_2"==rsTxt.trim()) {
    	addDisplayText(I18N_SYSTEM_MSG, I18N_FREE_CALL_FAILED_ERR_TIMEOUT);
    } else if ("ERROR_5"==rsTxt.trim()) {
    	addDisplayText(I18N_SYSTEM_MSG, I18N_FREE_CALL_FAILED_ERR_NOMONEY);
    } else {
    	addDisplayText(I18N_SYSTEM_MSG, I18N_FREE_CALL_FAILED);
    } 
}

function freeCall() {
    var tel = $("phone_input_area").value;
    if (tel != null && tel.length > 5) {
		var url="http://" + __websiteHost + "/leavemessage/sendcaller.aspx?workgroup=" + __workgroup + "&tel=" + tel;
		//alert(url);
		ajax_sendmsg(url,true,"GET","",callResponse);
	} else {
		$("phone_input_area").focus();
	}
}

//

//============================== emotions =============================

var emotionInited = false;
function appendEmotions() {
  if (!emotionInited) {
  	emotionInited = true;
  	var emotionHtml="";
	for(var i=0;i< __emotions.length;i++) {
	  emotionHtml+="<img onclick=\"selectEmotion('"+
	    __emotions[i].sign+"')\" src=\""+ __emotions[i].imgsrc+"\">";
	}
	$("emotiondiv").innerHTML=emotionHtml;
  }
}

function hideEmotionDiv() {
	showEmotionPanel(false);
}

function showEmotionPanel(visible) { 
  if (visible) { //show
	if (!emotion_panel_shown) {
		appendEmotions();
		CW_showDiv("emotiondiv");
		adjustMsgWindow(true, "emotiondiv");
		emotion_panel_shown = true;
		setBtnChecked("tb_emotion", true);
	} 
  } else { //hide
  	if (emotion_panel_shown) {
		adjustMsgWindow(false, "emotiondiv");
		CW_hideDiv("emotiondiv");
		emotion_panel_shown = false;
		setBtnChecked("tb_emotion", false);
	} 
  }
}

function switchEmotionPanel() {
	showUploadBar(false);
	showFontBar(false);
	showFreePhoneBar(false);
	showEmotionPanel(!emotion_panel_shown);
	hidePalette();
}

function replace(str,replace_what,replace_with) {
	var ndx=str.indexOf(replace_what);
	var delta=replace_with.length - replace_what.length;
	while(ndx >= 0) {
		var prefix = str.substring(0, ndx);
		var spaceBegin = prefix.lastIndexOf(" ");
		if (spaceBegin <0) spaceBegin = 0;
		var urlPrefix = prefix.substring(spaceBegin, ndx);
		if (urlPrefix.indexOf("://") <= 0 && urlPrefix.indexOf("www.")<=0) {
			str=str.substring(0,ndx)+replace_with+str.substring(ndx+replace_what.length);
		}
		ndx=str.indexOf(replace_what,ndx+delta+1);
	}
	return str;
}

function ReplaceEmotion(body){
	if (body == null) body = "";
    body = replace(body, "\/:&lt;", "\/:<");
	body = replace(body, "\/:&gt;", "\/:>");
    for (var i = 0; i<=__AllEmotions.length-1; i++) {
        var emotion = __AllEmotions[i].sign.replace("\\'","'");
		body = replace(body,emotion, "<img src='" +__webchatHost + __AllEmotions[i].imgsrc+"' border=0>"); 
	 }
	 return body;
}

function selectEmotion(sign) {
	_chatEditor.add(ReplaceEmotion(sign));
	hideEmotionDiv();
}
//============================= end emotions ==========================

//============================= fonts & bar ===========================
function showFontBar(visible) {
  if (visible) { //show
	if (!font_toolbar_shown) {
		CW_showDiv("fontDiv");
		adjustMsgWindow(true, "fontDiv");
		font_toolbar_shown = true;
		setBtnChecked("tb_font", true);
	} 
  } else { //hide
  	if (font_toolbar_shown) {
		adjustMsgWindow(false, "fontDiv");
		CW_hideDiv("fontDiv");
		font_toolbar_shown = false;
		setBtnChecked("tb_font", false);
	} 
  }
}

function switchFontBar() {
	showUploadBar(false);
	showEmotionPanel(false);
	showFreePhoneBar(false);
	showFontBar(!font_toolbar_shown);
	hidePalette();
}

function applyInputBoxSetting() {
	_chatEditor.applyStyle();
	_chatEditor.addKeyEvent(handleKeyEvent);
}

function changeInputStyle() {
	var fontSize = $("fontsize").value;
	var fontName = $("fontname").value;

	_chatEditor.setFont(fontName, fontSize);
}

function setFontBold() {
	var ret = _chatEditor.setFontBold();
	setBtnChecked("fb_bold", ret);
}

function setFontStyle() {
	var ret = _chatEditor.setFontItalic();
	setBtnChecked("fb_italic", ret);
}

function setUnderLine() {
	var ret = _chatEditor.setUnderline();
	setBtnChecked("fb_underline", ret);
}

function handleSelectColor(color) {
	colorimg.style.backgroundColor = color;
	_chatEditor.setFontColor(color);
}

function getColor(el) {
    showPalette(handleSelectColor, el);
}

function setDefaultFontName(fName) {
	_chatEditor.setInitFontName(fName);
}
//=========================== end fonts & bar =========================

//================================ upload file ==========================
var uploadFile = true;

function getUploadFile(){
	return uploadFile;
}

function uploadInvalidFile(){
   	addDisplayText(I18N_SYSTEM_MSG , I18N_INVALID_FILE_TYPE);
}
   	
function uploadCom(subPath, fileName){
	if(uploadFile)
		uploadComplete(subPath, fileName);
	else
		transmissionImage(subPath, fileName);
	
	showMessageHint();
}
    
function uploadComplete(subPath, fileName){
	var url = __uploadFolder + subPath + fileName;
	var message = "<a href=\"" + url+"\" target=\"_blank\">"+fileName+"</a>";
	
	try{
	  __dwrObj.sendFileTransfer(__chatID, url);
	} catch(e){
	  alert(e.message);
	}
	
	//alert(message);
	addDisplayText(__userNickname, I18N_FILE_SEND + fileName);
}
    
function transmissionImage(subPath, fileName){
	var message = "<img src='" + __uploadFolder + subPath + fileName + "'/>";
	__dwrObj.sendMessage(__chatID, message, message);
	addDisplayText(__userNickname, message);
}

function uploadFail(){
	var message;
	if(uploadFile){ message = I18N_FILE_SEND_ERROR; }
	else{ message = I18N_IMAGE_SEND_ERROR; }
	addDisplayText(I18N_SYSTEM_MSG, message);
}

function showUploadBar(visible) {
  if (visible) {
	if (!upload_toolbar_shown) {
		CW_showDiv("uploadDiv");
		adjustMsgWindow(true, "uploadDiv");
		upload_toolbar_shown = true;
		if (uploadFile) {
			setBtnChecked("tb_file", true);
		} else {
			setBtnChecked("tb_image", true);
		}
	}
  } else {
	if (upload_toolbar_shown) {
		adjustMsgWindow(false, "uploadDiv");
		CW_hideDiv("uploadDiv");
		upload_toolbar_shown = false;
		if (uploadFile) {
			setBtnChecked("tb_file", false);
		} else {
			setBtnChecked("tb_image", false);
		}
	}
  }
}

function switchFileUploadBar() {
	if (upload_toolbar_shown && uploadFile) {
		showUploadBar(false);
		return;
	}
	uploadFile = true;
	showFontBar(false);
	showEmotionPanel(false);
	showFreePhoneBar(false);
	if (!upload_toolbar_shown) {
		showUploadBar(true);
	} else {
		setBtnChecked("tb_file", true);
		setBtnChecked("tb_image", false);
	}
	hidePalette();
}

function switchImageUploadBar() {
	if (upload_toolbar_shown && !uploadFile) {
		showUploadBar(false);
		return;
	}
	uploadFile = false;	
	showFontBar(false);
	showEmotionPanel(false);
	showFreePhoneBar(false);
	if (!upload_toolbar_shown) {
		showUploadBar(true);
	} else {
		setBtnChecked("tb_file", false);
		setBtnChecked("tb_image", true);
	}
}

//=================================voice=================================
//voice chat time
var voiceTime = 0;
var bdelay = 0;

// is start voice talk?
var bTalking = false;

//voice time handler
var timerHandle = null;

var isIncomingCall = false;

function showTimeDiv(bshow) {
  //alert("showTime");
  if (bshow){
    CW_hideDiv("connectDiv");
    CW_showDiv("timeDiv");
  } else {
    CW_showDiv("connectDiv");
    CW_hideDiv("timeDiv");
  }
}

function showVoiceTime() {
  if (bdelay<=5) {
    bdelay = bdelay + 1;
    return;
  }
  var hour=parseInt(voiceTime/3600);
  if (hour<10) hour = "0"+hour;
  var min = parseInt((voiceTime-hour*3600)/60);
  if (min<10) min = "0"+min;
  var sec= voiceTime-hour*3600-min*60;
  if (sec<10) sec = "0"+sec;
  CW_setDivText("timeDiv", hour+":"+min+":"+sec);
  voiceTime = voiceTime+1;
}

//download voice plugin
function downloadVoiceX() {
	var card=$("Voice_DIV");
	if(card==null) {
	  var div=document.createElement("<DIV id='Voice_DIV' style='display:none'></DIV>");
	  document.body.appendChild(div);
	  div.innerHTML="<OBJECT ID='voiceEngine' CLASSID='CLSID:52C9B445-7CAC-4C81-ADAD-B7A8569A8B92' CODEBASE='" + __voiceFileUrl + "'></OBJECT>";
	}
}

function voiceEngineInstalled() {
	var voicexObj = null;
    try {
    	voicexObj = new ActiveXObject("QFVoiceX.VoiceEngine");
    } catch (e) {}
    return voicexObj != null;
}

//process click on start voice button
function handleVoice() {
    if (!funcSupported()) {
		alert(I18N_NOT_SUPPORTED);
		return;
    }
    if (!voiceEngineInstalled()) {
    	if (confirm(I18N_VOICE_ENGINE_CONFIRM)) {
    		window.open("voiceEngine.jsp");
    	}
    	return;
    }
    createVoiceEngine();
    if (!bTalking){
       __dwrObj.sendInitiate(__chatID, __agentID + "/IMX");
       isIncomingCall = false;
	   startVoice();
	}
}

function startVoice() {
	voiceTime = 0;
	bdelay = 0;
	CW_setDivText("timeDiv", I18N_MSG_VOICE_CONNECT);
	showLeftPanel();
	CW_showDiv("voiceDiv");
	showTimeDiv(false);
    bTalking = true;
}

function stopVoice() {
	bTalking = false;
	//alert("stop");
	CW_hideDiv("voiceDiv");
	hideLeftPanel();
	__dwrObj.sendTerminate(__chatID, __agentID + "/IMX");
	clearInterval(timerHandle); 
    freeVoiceEngine();
}

function createVoiceEngine(){
   downloadVoiceX();
}

function freeVoiceEngine(){
   if (typeof(voiceEngine)=="undefined") return;
   if(voiceEngine!=null)  {
   	  try{
		voiceEngine.StopVoice();
		//delete voiceEngine;
	  } catch (e) {
	  }
   }
}

function startUpdateVoiceTime() {
	timerHandle = setInterval("showVoiceTime()",1000);	
}
//================================ end voice ========================

//============================ video ================================
function startVideoChat() {
	if (!flashInstalled()) {
    	return;
    }
    if (!bTalking){
       __dwrObj.sendInitiate(__chatID, __agentID + "/IMX");
       isIncomingCall = false;
       addDisplayText(I18N_SYSTEM_MSG, "Send video chat request");
	}
}

function acceptVideoChat() {
	if (bTalking) return;
	bTalking = true;
	CW_showDiv("video_area");
	resizeWindow();
	$("video_chat_frame").src="video/?server=" + __red5Host + "&room=" + __chatID + "&self=visitor&other=agent";
	//alert($("video_chat_frame").src);
}

function stopVideoChat() {
	bTalking = false;
	CW_hideDiv("video_area");
	resizeWindow();
	$("video_chat_frame").src="about:blank";
}

function flashInstalled() {
	var hasProductInstall = DetectFlashVer(6, 0, 65);
	
	if (!hasProductInstall) {
    	if (confirm(I18N_VOICE_ENGINE_CONFIRM)) {
    		window.open("flash.jsp");
    	}
    	return false;
    }
    return true;
}

//============================ jingle =================================
var jingleTimeOut;
 
function checkJingleMessage() {
	__dwrObj.getAllJingleMessages(__chatID, processJingEvent);
}

function sendNegotiateMsg(msg) {
	__dwrObj.sendNegotiate(__chatID, msg.jid, voiceEngine.LocalIP, voiceEngine.LocalPort+"",voiceEngine.NATIP,voiceEngine.NATPort);
//	__dwrObj.sendNegotiate(__chatID, msg.jid, "", "", "", "");
}

function processJingEvent(messages) {
	if(messages == null){	
       clearTimeout(jingleTimeOut);
       chatHasEnded();
       //__dwrObj.getEndMessage(__lang, __chatID, __workgroup, showEndMessage);
       return;
    }
    for(i=0; i<messages.length;i++) {
		var msg = messages[i];
		if(msg.eventType=="IncomingCall") {
			window.focus();
			if (!confirm(I18N_JINGLE_INCOMING_CALL)){
				__dwrObj.sendReject(__chatID, msg.jid, msg.id);
			} else {
				if (!voiceEngineInstalled()) {
			    	if (confirm(I18N_VOICE_ENGINE_CONFIRM)) {
			    		window.open("voiceEngine.jsp");
			    	}
			    	return;
			    }
//				if (!flashInstalled()) {
//			    	return;
//			    }
				isIncomingCall = true;	
				voiceTime = 0;	
				CW_setDivText("timeDiv", I18N_MSG_VOICE_CONNECT);
	            __dwrObj.sendAccept(__chatID, msg.jid, msg.id);
				createVoiceEngine();
				startVoice();
	            if (voiceEngine != null){
	          		voiceEngine.GetStunInfo(); 
	            }
//	            acceptVideoChat();
				sendNegotiateMsg(msg);
	        }
		} else if (msg.eventType=="AcceptCall") {
			sendNegotiateMsg(msg);
		} else if (msg.eventType=="NegotiateCall") {
			if (!isIncomingCall) {	//visitor call
				createVoiceEngine();
				sendNegotiateMsg(msg);
			}
			showTimeDiv(true);
			startUpdateVoiceTime();	   
			if (voiceEngine.NATIP==msg.remoteIp) {
				voiceEngine.StartVoice(msg.localIp, msg.localPort); 
			} else {
				voiceEngine.StartVoice(msg.remoteIp, msg.remotePort);
			}
//			acceptVideoChat();
		} else if (msg.eventType=="RejectCall") {
		 	addDisplayText(I18N_SYSTEM_MSG, I18N_JINGLE_REJECT_CALL);
			stopVoice();
		} else if (messages[i].eventType=="TerminateCall") {
			addDisplayText(I18N_SYSTEM_MSG, I18N_JINGLE_TERMINATE_CALL);
			stopVoice();
		} else if (messages[i].eventType=="OccurError") {
			addDisplayText(I18N_SYSTEM_MSG, I18N_JINGLE_OVERTIME);
			stopVoice();
		}
	}
	jingleTimeOut = setTimeout("checkJingleMessage()", 2000);        
}

//================================ cobrowsing, not used now =============================
var cobrowseWin;

function showCobrowser(url){
  var width = 800;
  var height = 700;
  var defaultOptions = "location=yes,status=no,toolbar=no,personalbar=no,menubar=no,directories=no,";
  var winleft = (screen.width - width) / 2;
  var winUp = (screen.height - height) / 2;

  defaultOptions += "scrollbars=yes,resizable=yes,top=" + winUp + ",left=" + winleft + ",";
  defaultOptions += "width=" + width + ",height=" + height;
  cobrowseWin = window.open(url, 'cobrowser', defaultOptions);

  __dwrObj.sendMessage(__chatID, 'I have accepted the Cobrowse invitation for '+url);
}

//================================ agent/customer typing ================================
function checkIfAgentTyping(){
  __dwrObj.isAgentTyping(__chatID, isTyping);
}

function isTyping(agentIsTyping){
  if(agentIsTyping){
	  CW_showDiv("typingAgent");
  } else {
	  CW_hideDiv("typingAgent");
  }
  setTimeout("checkIfAgentTyping()", 2000);
}