/* GLOBAL VARS(tm) */
var chatFrame;
var msgBoardDoc;
var jid;
var pass;
var DWBaseTime = new Date();
var IMSBaseTime = DWBaseTime;
var passedArgs = null;
var gXMPPProxy;
var gXMPPCore;
var gCaHandler;
var gSipWebCall = null;
var isFilledSatisfactionForm = false;
var maxPostWords = 1500;
var canSendNext = true;

/* debugging options */
var DEBUG = false; // turn debugging on
var DEBUG_LVL = 4; // debug-level 0..4 (4 = very noisy)
var Debug;

/* get parseArgs from url or cookie */
function parseArgs() {
	passedArgs = getArgs();
	
	assert(passedArgs['im800'],"im800 account is missing.");
	
	if(passedArgs['debug'] && passedArgs['debug'] == 'true') DEBUG = true;
}

/* connect to the server */
 function connect(){
	var oArgs = new Object();
	oArgs.httpbase = '/WebDW/JHB';
	oArgs.timerval = 2000;
	oArgs.oDbg = Debug;
	
	gXMPPCore = new XmppCore(oArgs);
	
	/* session events */
	gXMPPCore.session.registerHandler("onconnect", doConnected);
	gXMPPCore.session.registerHandler("onerror", doLogonError);
	
	/* account events */
	gXMPPCore.subIM800.onIM800Subscribe = doIM800Subscribe;
	
	oArgs.resource = jid.substring(jid.indexOf('/') + 1);
	oArgs.domain = Configure.getParameter('jabberServer');
	oArgs.username = jid.substring(0,jid.indexOf('@'));
	oArgs.pass = pass;
	oArgs.register = false;
	
	gXMPPCore.session.connect(oArgs);
}

function doXForm(){
	var messageFormURL = Configure.getXformURL('message');
	gXMPPCore.xmppXForm.form = null;
	gXMPPCore.xmppXForm.formType = "MessageForm";
	gXMPPCore.xmppXForm.closeWebDW = true;
	
	$('xformframe').src = messageFormURL;
	$('logondiv').style.display = 'none';
}

function doConnected() {
	gXMPPCore.connected = true;
	if(Configure.getParameter('status') == "offline"){
	//	doXForm();
		
		selectTab('xformdiv');
/*		$('xformdiv').style.display = '';
		$('chatdiv').style.display = 'none';*/
		
	}

	gXMPPCore.subIM800.subscribe(passedArgs['im800'], jid);
}

function doLogonError(arg) {
	showErrorPage(arg);
}

function doIM800Subscribe(aJSJaCPacket) {
	if (!aJSJaCPacket || aJSJaCPacket.getType() != 'result') {
		if (aJSJaCPacket)
			Debug.log("Error fetching im800:\n" + aJSJaCPacket.getDoc().xml,1);
		else
			if (aJSJaCPacket.getType() == 'error') {
				Debug.log("Error when sub im800", 1);
				//TODO:do something
			}
			else
				Debug.log("Error fetching im800",1);
	
		showErrorPage();
		return;
	}
	
	if(aJSJaCPacket.query('/iq/expresence/@type').stringValue() =='subscribed'){
		Debug.log('subscribed successed!\n',2);
		gXMPPProxy = new XMPPProxy(gXMPPCore);
		DWBaseTime = new Date();
		gXMPPCore.serverTime.getServerTime();
	}
}

/* init, runs when chat.jsp onLoad */
function init(titleUrl) {
	
	jScriptVersion();
	
	$('pleaseWait').innerHTML = prompt_pleaseWait;
	$('loadingToServer').innerHTML = prompt_loadingToServer;
	
//	var sW = window.screen.availWidth;
//	var sH = window.screen.availHeight;
//	var myW = 600;
//	var myH = 470;
//	var myLeft = (sW-myW)/2;
//	var myTop = (sH-myH)/2;
//	window.resizeTo(myW, myH);
//	window.moveTo(myLeft, myTop);
//	alert(titleUrl);
	if(null!=titleUrl && ''!=titleUrl){	//使用自定义TITLE的IFRAME
		$('customFrame').src= titleUrl;
	}else
		$('customFrame').src="custom.html"
	
	parseArgs();
	
	assert('undefined' != typeof getConfigure,'Get parameter failed.');
	
	assert(Configure.getParameter('dwServer')!='','Get dwServer failed.');
	assert(Configure.getParameter('jabberServer')!='','Get jabberServer failed.');
	
	jid = genVJID(passedArgs['im800']);
	assert(jid,"JID is missing.\nAborting...");
	assert(isValidJID(jid),"JID is invalid.");
	
	if(is.ie) Event.observe(window, 'unload', logout, false);
	
/*	if(Configure.getParameter('status') != "offline")
	{*/
		Aop.onAfter({
			srcFunc:"widgEditor",
			adviceFunc:"showChatDiv",
			once:true
		});
		widgInit();
		
		setButtonCaptions();
		chatFrame = chat.document;
		msgBoardDoc = msgboard.document;
		gCaHandler = new CustomCommandHandler($("chat").contentWindow.document);
//	}
	
	/* initialise and start debugger */
	if (!Debug || typeof(Debug) == 'undefined' || !Debug.start) {
		if (typeof(Debugger) != 'undefined')
			Debug = new Debugger(DEBUG_LVL, 'WebDW ' + cutResource(jid));
		else {
			Debug = new Object();
			Debug.log = function() {};
			Debug.start = function() {};
		}
	}
	if(DEBUG)
		Debug.start();
	
	connect();
	
	if(Configure.hasFeature('click_to_call') && Configure.getVoipProperties())
		gSipWebCall = new SipWebCall(Configure.getVoipProperties(), Debug);
	
	window.onbeforeunload = function() {
//		alert(gXMPPProxy.chat.getSecondParty());
//		alert(gXMPPProxy.chat.getTicketId());
//		alert(gXMPPProxy.chat._curMajorState);
//		alert(gXMPPProxy.chat._curMinorState);
		if( gXMPPProxy && !isFilledSatisfactionForm
			&& (gXMPPProxy.chat.canSendMessage() || gXMPPProxy.chat.closedSipCall.saved )
			&& gXMPPProxy.core.XFormsProperty.SatisfactionPop
			&& Configure.getXformURL('satisfaction') )
		{
			gXMPPCore.wanttoDisconnect = true;
			//gXMPPProxy.chat.stop();
			
			if ((gXMPPCore.xmppXForm.form) && (! gXMPPCore.xmppXForm.form.closed))
				gXMPPCore.xmppXForm.form.close();
			
			var satisfactionFormURL = Configure.getXformURL('satisfaction');
			gXMPPCore.xmppXForm.form = null;
			gXMPPCore.xmppXForm.formType = "satisfaction";
			gXMPPCore.xmppXForm.closeWebDW = true;
			
			//alert(satisfactionFormURL);
			selectTab('chatdiv');
			$('chatXformframe').src = satisfactionFormURL;
			$('chatXformdiv').style.display = '';
			$('chatCorediv').style.display = 'none';

			//openSatisfactionForm();

			//resizeXformdiv();			
			return prompt_fillSatisfactionFormOnLogout;
			
		} else if( $('xformdiv').style.display == 'none' && $('logonfailed').style.display == 'none' && !gXMPPCore.xmppXForm.closeWebDW) {
			return "";
//			return prompt_confirmCloseDW;
		}
	}
}


/* check JavaScript engine version */
function jScriptVersion() {
	if('undefined' != typeof ScriptEngine)
		if(ScriptEngineMajorVersion()>5 || ( ScriptEngineMajorVersion()==5 && ScriptEngineMinorVersion()>=5 ))
			return true;
			
	if(navigator.appName != 'Microsoft Internet Explorer')
		return true;
	
	try {
		alert(prompt_jScriptVersionError);
	} catch(e) {
		alert("Sorry, this system must run in Internet Explorer 5.5 or higher.");
	}
	window.close();
	return false;
}

/* show Error Page */
function showErrorPage(arg) {
	if (arg)
	{
		new Insertion.Top('errorReport', prompt_Errors[arg.getAttribute("code")]);
	}
	$('logonfailed').style.display = '';
	$('logoning').style.display = 'none';
}		

/* show inChat Div */
function showChatDiv() {
	if($('logonfailed').style.display == '') return false;
	
	$('chatdiv').style.display = '';
	$('logondiv').style.display = 'none';
}		

/* logout, runs when chat.jsp onUnLoad */
function logout() {
	if ( (!gXMPPCore) || (!gXMPPCore.session.connected()) )
		return;
	
	try
	{
		gXMPPCore.wanttoDisconnect = true;
		
		if ( (gXMPPCore.xmppXForm.form) && (! gXMPPCore.xmppXForm.form.closed) )
		{
			gXMPPCore.xmppXForm.setFormClose(doCloseXForm);
			gXMPPCore.xmppXForm.form.close();
		}
		
		if (gXMPPProxy)
			gXMPPProxy.chat.stop();
	}
	finally
	{
		gXMPPCore.session.disconnect();
	}
	
	if (gSipWebCall)
		gSipWebCall.setOffline();
}

/* Put msg into chatFrame */
function putMsgHTML(msg, msgType) {
	if (!msg) return;
	
	var auto_scroll = false;
	if (chatFrame.body.scrollTop+chatFrame.body.clientHeight >= chatFrame.body.scrollHeight) // scrollbar at bottom
		auto_scroll = true;
	
	chatFrame.body.innerHTML += formatMsg(msgBoardDoc, msg, msgType);
	if (auto_scroll)
		chat.scrollTo(0,chatFrame.body.scrollHeight);
}

/* Action submit button clicked */
function submitClicked() {
	// check if can send or not
	if(! checkMessage()) {
		currentWidgEditor.theIframe.contentWindow.focus();
		return false;
	}
	
	// put it into chatFrame
	currentWidgEditor.updateWidgInput();
	var message = $("msgbox").value;
	putMsgHTML(message, "Visitor");
	// send it out
	message = processTxtEmoticons(msgBoardDoc, message);
	gXMPPProxy.chat.sendMessage(message);
	
	// can not send again in two second
	canSendNext = false;
	setTimeout( function(){canSendNext=true;}, 1000 * 2 );
	
	// delete the composing state
	gXMPPCore.xmppComposing.beComposing = false;
	
	// clear the inputArea and set color & Bold
	currentWidgEditor.theIframe.contentWindow.document.body.innerHTML = "";
	
	if(currentWidgEditor.lastBold) {
		currentWidgEditor.theIframe.contentWindow.document.execCommand("Bold", false, null);
	}
	if(currentWidgEditor.lastColor) {
		currentWidgEditor.theIframe.contentWindow.document.execCommand("ForeColor", false, currentWidgEditor.lastColor);
	}
	
	currentWidgEditor.theIframe.contentWindow.focus();
}

function resizeXformdiv() {
	$('xformdiv').width = xformframe.document.body.scrollWidth;
	$('xformdiv').height = $('xformframe').document.body.scrollHeight;
	
}

function showPreChat(preChatURL){
	selectTab('chatdiv');
	$('chatCorediv').style.display = 'none';
	$('chatXformdiv').style.display = '';
	$('chatXformframe').src=preChatURL;
}
