var I18N_INPUT_REQUIRED = "required";
var I18N_DEPT_ONLINE_STATUS = "online";
var I18N_DEPT_OFFLINE_STATUS = "offline";

// ----------- visitor information input --------------
function getNickName() {
	return $("nickname_input").value;
}
function getEmail() {
	return $("email_input").value;
}
function handleVisitorInfo(vInfo){
	__email = vInfo.email;
	if (vInfo.nickName!=""&&cid!=vInfo.nickName){
		__userNickname = vInfo.nickName;
		$("nickname_input").value = __userNickname;
	} else {
		__userNickname="";
	}
	$("email_input").value = __email;
	
	CW_showDiv("input_info_div");
	CW_hideDiv("connection_div");
	$("nickname_input").focus();
}
function showInputInfoDiv(queueInfos) {
	chatHelper.getVisitorInfo(cid, __workgroup, handleVisitorInfo);
	if (__queueID == null || __queueID =="") {
		var html = "";
		var i;
		for (i=0;i<queueInfos.length;i++) {
			if(i==0)
				html += "<input checked type='radio' name='qr' id='" + queueInfos[i].ID + "' ></input>";
			else
				html += "<input type='radio' name='qr' id='" + queueInfos[i].ID + "' ></input>";
			if (queueInfos[i].online){
				html += queueInfos[i].name + "(" + I18N_DEPT_ONLINE_STATUS + ")";
			} else {
				html += "<font color='#CCCCCC'>"+queueInfos[i].name+"("+I18N_DEPT_OFFLINE_STATUS+")"+"</font>";
			}
			html += "<br/>";
		}
		CW_showDiv("queue_block");
		$("queue_area").innerHTML=html;
	} else {
		$("question_input").style.height = "190px";
	}
}

function checkAndStart() {
	var inputNick = getNickName();
	$("nick_required_field").innerHTML = "*";
	$("question_required_field").innerHTML = "*";
	if (inputNick == null||inputNick==""){
		$("nickname_input").focus();
		$("nick_required_field").innerHTML = "(" + I18N_INPUT_REQUIRED + ")";
		return;
	}
	__question = $("question_input").value;
	if (__question == null||__question==""){
		$("question_input").focus();
		$("question_required_field").innerHTML = "(" + I18N_INPUT_REQUIRED + ")";
		return;
	}
	
	CW_hideDiv("input_info_div");
	var needUpdate = false;
	if (inputNick!=__userNickname || getEmail() != __email) {
		needUpdate = true;
	}
	setUserNickname(inputNick);
	__email = getEmail();
	if (needUpdate) {
		chatHelper.updateVisitorInfo(cid, __workgroup, inputNick, __email);
	}
	
	var qrs = document.getElementsByName("qr");
	var i;
	for(i=0;i<qrs.length;i++){
		if (qrs[i].checked){
			__queueID=qrs[i].id;
			break;
		}
	}
	
	startChat();
}

function closeChatWindow() {
	window.close();
}

// -------------------main chat flow -------------
var isRedirecting = false;
var chatStartedProgress = 0;

function checkUnload(){
	stopVoice();
	if (chatStartedProgress == 0) return;
	DWREngine.setAsync(false);
	if (chatStartedProgress == 2) {
		chatHelper.broadcastStopChatStatus(cid, __workgroup); 
	}
	if(!isRedirecting && chatStartedProgress > 0){ //if visitor close the chat
		chatHelper.closeChat(__chatID);
	}
}
   
function handleWelcomeMsg(msg) {
	CW_hideDiv("queue_div");
    CW_showDiv("chat_area");
   
	addDisplayText('', msg);
	checkForNewMessages();
 	checkIfAgentTyping();
 	checkJingleMessage();
 	
 	visitorSendMessage(__question);
}

function doit() {
	chatHelper.getWelcomeMessage(__chatID, __lang, __workgroup, handleWelcomeMsg);
	chatHelper.broadcastStartChatStatus(cid, __workgroup, ""); 
	chatStartedProgress = 2;
}

function init() {    	
	applyInputBoxSetting();
	setTimeout("appendEmotions()", 100);	//fix ie6 gif bug
}

function handleWorkgroupOnline(online) {
	if (online) {
		chatHelper.getCompanyInfo(__workgroup, handleCompanyInfo);
	} else {
		//alert(leaveMessageUrl);
		window.location = leaveMessageUrl;
	}
}

function startChat() {
	CW_hideDiv("chat_area");
   	CW_showDiv("main_div");
   	CW_showDiv("queue_div");     		
   	chatHelper.startChat(__workgroup, __queueID, __chatID, __agentID, __lang, cid, __question, __email, handleChatStarted);
}
function handleCompanyInfo(cmpInfo) {
	if (cmpInfo.showQuestionUI) {
		showInputInfoDiv(cmpInfo.queueInfos);
	} else {
		CW_hideDiv("connection_div");
		startChat();
	}
	
	if (cmpInfo.hideContactInfo) {
		//in talkaction.js
		__hideContactPanel = true;
		hideLeftPanel();
	}
	
	document.title = cmpInfo.companyName + " - " + document.title;
	
	if(cmpInfo.largeLogoUrl!="") {
		if ($("pre_chat_logo")) {
			$("pre_chat_logo").src=cmpInfo.largeLogoUrl;
		}
		if ($("main_chat_logo")) {
			$("main_chat_logo").src=cmpInfo.largeLogoUrl;
		}
	}
	
	$("cmp_info_name").innerHTML=cmpInfo.companyName;
	$("cmp_info_contact").innerHTML=cmpInfo.contactName;
	$("cmp_info_phone").innerHTML=cmpInfo.tel;
	$("cmp_phone_num").innerHTML=cmpInfo.tel;
	$("cmp_info_fax").innerHTML=cmpInfo.fax;
	$("cmp_info_email").innerHTML="<a href='mailto:" + cmpInfo.email + "'>" + cmpInfo.email + "</a>";
	$("cmp_info_site").innerHTML="<a href='" + cmpInfo.website + "' target='_blank'>" + cmpInfo.website + "</a>";
	$("cmp_info_addr").innerHTML=cmpInfo.address;
	$("cmp_info_zip").innerHTML=cmpInfo.zip;
	var strArray = cmpInfo.version.split(":");
	try{
		if(strArray[0]<=1){
			var showAdv = false;
			if (preChatAdURL!=null&&preChatAdURL.length>0){
				showPreChatAdURL(preChatAdURL);
				showAdv = true;
			}
			if (adURL!=null&&adURL.length>0){
				showAdvertisement(adURL);
				showAdv = true;
			}
			if (queueAdURL!=null&&queueAdURL.length>0){
				showQueueAdURL(queueAdURL);
			}
			if (showAdv) {
				//var upPx=35;
				//if(document.all) upPx=0;
				resizeTo(579,600);
			}
		}
	}catch(e){}
}

function handleChatStarted(success) {
	if (!success) {
		window.location = leaveMessageUrl;
	} else {
		//chatHelper.getUserNickName(__chatID, setUserNickname);
		startQueueChecking();
		chatStartedProgress = 1;
	}
}

function setUserNickname(name) {
	if (name==null||name.length<=0) name=defaultNick;
	__userNickname = name;
	nickname = __userNickname;	//common.js
}

//------------------ check message, muc chat -------------
var mucChatTimeOut;
function checkForNewMessages(){
	room.getAllMessages(__chatID, insertMessages);
}

function insertMessages(messages){
	if(messages == null){
		clearTimeout(mucChatTimeOut);
        chatHasEnded();
		room.getEndMessage(__chatID, __workgroup, showEndMessage);
		return;
	}
	try{
		for(i=0; i<messages.length;i++){
			if(messages[i].cobrowsing){
				if(cobrowseWin && !cobrowseWin.closed){
					cobrowseWin.location.href= messages[i].urlToPush;
					cobrowseWin.focus();
				} else if(messages[i].body != null) {
					var urlToPush = messages[i].urlToPush;
					addDisplayText('', "<a href=javascript:parent.showCobrowser('"+urlToPush+"')>You have received a Cobrowsing invitation. Click to initiate a Cobrowser session.</a>");
				}
			} else {
				receiveMessage(messages[i]);
			}
		}    
      
      	/*
		if(messages.length > 0 && !messages[0].cobrowsing){
			scrollYakToEnd(window.frames['yak']);
			$("typingAgent").innerHTML = "";
			room.clearAgentTyping(__chatID);
			
			showMessageHint();
		}
		*/
	}catch(ex){
		alert(ex.message);
	}
	mucChatTimeOut = setTimeout("checkForNewMessages()", 2000);
}

function showEndMessage(message){
	isRedirecting = true;
	freeVoiceEngine();
	showChatEndPage(); 
} 

//--------------------queue opt----------------
var isClosing = true;
var isClosed = false;
function checkQueue() {
    room.getChatQueue(__chatID, handleQueue);
}
function handleQueue(queue) {
    if (isClosed) {
    	return;
    }
    if (queue == null) {
        return;
    }
    if (queue.connectionDropped) {
        showNoAnswer();
        return;
    }else if (queue.routed) {
        redirectForChat();
        return;
    }else if (queue.queueTime > 0 && queue.queuePosition > 0) {
        updateQueuePosition(queue.queuePosition);
        updateQueueTime(queue.queueTimeForHtml);
    }
    setTimeout("checkQueue()", 500);
}
// Redirect For Chat
function redirectForChat() {
	isClosing = false;
	doit();
}
// Updates the queue position text on the queue page
function updateQueuePosition(position) {
    var posSpan = $('queue_position');
    if (posSpan) {
        posSpan.innerHTML = position;
        CW_showDiv("queue_info");
    }
}
// Updates the queue wait time. Time should be in seconds.
function updateQueueTime(time) {
    var timeSpan = $('queue_time');
    if (timeSpan) {
        timeSpan.innerHTML = time;
        CW_showDiv("queue_info");
    }
}

function isWindowClosing() {
	if (isClosing) {
		isClosed = true;
		chatHelper.closeChat(__chatID);
	}
}

function checkLeaving(){
    var ok = confirm(I18N_LEAVE_QUEUE_MSG);
    if(ok){
        isClosing = false;
    }
    return ok;
}
     
function showLeaveMessage() {
	isClosing = false;
	window.location.href=leaveMessageUrl;
}

function showNoAnswer() {
	window.location.href=leaveMessageUrl;
}
   
function startQueueChecking() {
	CW_showDiv("queue_div");
	checkQueue();
}

//------------- chat end ------------------
function showChatEndPage() {
	CW_showDiv("chat_end_div");
	setTimeout("window.close()",3000);
}


//-------------- add advertisement ----------
function showAdvertisement(url){
	CW_showDiv("advertisement_bar");
	$("main_ad_frame").src=url;
}
function showPreChatAdURL(url){
	CW_showDiv("preChatAD_bar");
	$("pre_ad_frame").src=url;
}
function showQueueAdURL(url){
	CW_showDiv("queueAD_bar");
	$("queue_ad_frame").src=url;
}
//------------- disable keys ---------------
function disableKeys() {
	//disable right btn
	document.oncontextmenu=function(e){return false;} 
	document.onkeydown=function(evt) {
    	var evt = (evt) ? evt : ((window.event) ? window.event : "");
    	var keycode = ((document.all) ? evt.keyCode : evt.which);
    	if (document.all && evt.ctrlKey && keycode== 78) {
    		evt.keyCode=0;
		    evt.returnValue=false;
		    return;
    	}
    	if (keycode==116) {                 //disable f5
    		if (document.all) {
	     		evt.keyCode=0;
	     		evt.returnValue=false;
     		} else {
     			return false;
     		}
     	}
  	}
}