/*---------------------------------------- GENERAL SETTINGS ----------------------------------------*/
var main_intvl = 20000;
var conv_intvl = 5000;
var conversations = new Object();
var isIE = (navigator.appName.toLowerCase() == "microsoft internet explorer");

function initDrag(cont,hndl) {
	var drag = ToolMan.drag()
	var boxHandle = document.getElementById(cont)
	drag.createSimpleGroup(boxHandle, document.getElementById(hndl))
}

function listRest(str,dlm){
	var foo = str.split(dlm);
		foo.shift();
	return foo.join(dlm);
}



// pass a handle elm to this to focus the entire div
function focus_up(elm){
	var DIVs = document.getElementsByTagName('DIV');
	for(var x=0;x<DIVs.length;x++){
		if(DIVs[x].style.zIndex == 10){
			DIVs[x].style.zIndex = 5;
			break;
		}
	}
	elm.offsetParent.style.zIndex = 10;
}


function playSound(soundname) {
	 var sound = eval("document." + soundname);
	 try {
	  sound.Stop();
	  sound.Rewind();
	 } catch (e) {
	 }
	
	 try {
	  sound.DoPlay();
	 } catch (e) {
	  sound.Play();
	 }
}

function showHide(id){
	var div = document.getElementById(id).offsetParent;
	var h1 = div.getElementsByTagName('H1')[0];
	var img = h1.getElementsByTagName('IMG')[0];
	var elm = div.getElementsByTagName('DIV')[0];
		
	h1.className = 'slvr';
//	alert(h1.style.backgroundImage);
	foo = '';
	for(x in h1.style)foo += (x+'='+h1.style[x]+'<br>');
	//document.write(foo);
	
	if(elm.style.display == 'none'){
		elm.style.display = 'block';
		img.src = '/chat/assets/min.gif';
	}else{
		elm.style.display ='none';
		img.src = '/chat/assets/max.gif';
	}		
}

function resize(h1){
	var h1 = document.getElementById(h1);
	if(h1.style.width == '200px') 
		h1.style.width = '400px'
	else
		h1.style.width = '200px'
	
}

function screenDims(){
	var r = new Object();
		r.height = (isIE) ? document.body.offsetHeight : window.innerHeight ;
		r.width = (isIE) ? document.body.offsetWidth : window.innerWidth ;
	return r;
}
/*---------------------------------------- INDEX PAGE ----------------------------------------*/
function init_chat(){
	if(!document.getElementById('main_IM')){
		buildMainDiv();
	}
	launchIM_request();	
}

function buildMainDiv(){
	var h ='<h1 id="hndl_main" class="slvr" onclick="focus_up(this);">';
		h +='<span class="lt">JSMXchat <span class="gray">beta</span></span> <span class="rt"><a href="javascript:showHide(\'hndl_main\');"><img id="main_content_icon" src="/chat/assets/min.gif" /></a><a href="javascript:end_IM();"><img src="/chat/assets/close.gif" /></a></span>';
		h +='</h1><div id="main_content"></div>';
	var DIVmain = document.createElement("DIV");
		DIVmain.id = "main_IM";
		DIVmain.className = "hide";
		DIVmain.innerHTML = h;
		DIVmain.style.left = (screenDims().width - 240)+'px';
		DIVmain.style.top = document.body.scrollTop+10;
	document.body.appendChild(DIVmain);	
}


function end_IM(){
	var DIVs = document.getElementsByTagName('DIV');
	
	//first clear all the chat sessions
	for(var x=DIVs.length-1;x>=0;x--){
		if(DIVs[x].className == 'convWin')
		end_conversation(listRest(DIVs[x].id,"_"));
	}
	
	if(typeof(statusGateway) != 'undefined') clearInterval(statusGateway);
	document.body.removeChild(document.getElementById('main_IM'));
//	logout_request();
	
}


function launchIM_request(){
	http('get','/chat/actions.cfc?method=startIM',launchIM_response);
}
function launchIM_response(obj){
	document.getElementById('main_IM').className = 'pop';
	document.getElementById('main_content').innerHTML = obj.html;
	if(parseInt(obj.start)) 
	init_main();
	initDrag('main_IM','hndl_main');
}

function logout_request(){ http('get','/chat/actions.cfc?method=logout',logout_response); }
function logout_response(obj){ /*- ignore response -*/ }

/*---------------------------------------- LOGIN PAGE ----------------------------------------*/
	function login_request(form){
		http( 'POST' , '/chat/actions.cfc?method=login' , login_response , form );
	}	
	function login_response(obj){
		if(parseInt(obj.success))
			launchIM_request()
		else
			alert(obj.msg);
	}


/*---------------------------------------- MAIN PAGE ----------------------------------------*/
function init_main(){
	statusGateway = setInterval('status_request()',main_intvl);
}

function init_newConv(n,s){
	foo = document.getElementById('conv_'+s);
	if(!foo){
		newConversation_request(s);	
	}
}
function buildConvDiv(s,h){
	DIV = document.createElement('DIV');
	DIV.id = "conv_"+s;
	DIV.className = "convWin";
	DIV.innerHTML = h;
	document.body.appendChild(DIV);
	initDrag('conv_'+s,'hndl_'+s);
	focus_up(document.getElementById('hndl_'+s));
	receive_request(s);
	
	target = document.getElementById(DIV.id);
	target.style.top = document.body.scrollTop+RanSpan(30,50);
	target.style.left = document.body.scrollLeft+RanSpan(30,50);
}


function Random(N) {
    return Math.floor(N * (Math.random() % 1));
}


function RanSpan(MinV, MaxV) {
    return MinV + Random(MaxV - MinV + 1);
}


function end_conversation(s){ 
	clearInterval(conversations[s].listener);
	document.body.removeChild(document.getElementById('conv_'+s));
}


/*---\\\ AJAX FOR MAIN DIV ///---*/
function status_request(){ http('GET','/chat/actions.cfc?method=contactStatusCheck',status_response); }
function status_response(o){
	if(parseInt(o.statuschange)){
		document.getElementById('listContainer').innerHTML = o.statuslist;
		playSound('hello');
	}
	for(var x=0;x<o.requests.length;x++) 
		init_newConv(o.requests[x].name,o.requests[x].session);
}

function logout_request(){ http('GET' , '/chat/actions.cfc?method=logout' , logout_response ); }
function logout_response(o){/*-- ignore response --*/}


function newConversation_request(id){ http('POST','/chat/actions.cfc?method=startConversation', newConversation_response , 'id='+id ); }
function newConversation_response(o){
	conversations[o.session] = new Conversation(o.session,o.alias);
	buildConvDiv(o.session,o.html); 
}

/*---\\\ AJAX FOR MAIN DIV ///---*/





/*---------------------------------------------- CONVERSATION PAGE ---------------------------------------------------------*/
var icons = new Object();
	icons["smile"] = "(:\\))";
	icons["Smile"] = "(:-\\))";
	icons["bigsmile"] = "(:D)";
	icons["bigSmile"] = "(:d)";
	icons["oh"] = "(:-O)";
	icons["OH"] = "(:o)";
	icons["tongue"] = "(:-P)";
	icons["Tongue"] = "(:p)";
	icons["TOngue"] = "(:P)";
	icons["wink"] = "(;\\))";
	icons["Wink"] = "(;-\\))";
	icons["sad"] = "(:\\()";
	icons["Sad"] = "(:-\\()";
	icons["Crazy"] = "(:-S)";
	icons["crazy"] = "(:s)";
	icons["shock"] = "(:-\\|)";
	icons["Shock"] = "(:\\|)";
	icons["cry"] = "(:'\\()";
	icons["shy"] = "(:\\$)";
	icons["Shy"] = "(:-\\$)";
	icons["cool"] = "(\\(H\\))";
	icons["Cool"] = "(\\(h\\))";
	icons["angry"] = "(:@)";
	icons["Angry"] = "(:-@)";
/**/
	
function Conversation(id,sn){ 
	this.session = id;
	this.ScrNm = sn;
	this.send = send_request;
	this.listener = setInterval("receive_request('"+id+"')",conv_intvl);
}

function sendIt(fld){
	var id = fld.form.name.split('.')[1];
	var nTxt = fld.value;
	var xSession = conversations[id];
//	alert(.session);
	addMessageToBody(xSession.session,xSession.ScrNm,nTxt);
	playSound('send');
	fld.value = '';
	fld.focus();
	xSession.send(nTxt);
}

function convertIcon(nm){
	var ieClass = (isIE) ? 'class="ie"' : '' ;
	var bImg = '<img src="/chat/assets/smileys/~.gif" '+ieClass+' />';
	var icon = bImg.replace('~',nm.toLowerCase());
return icon;
}

function prepareText(txt){
	var nTxt = txt;
		nTxt = nTxt.replace(/[<]/g,'&lt;');
		nTxt = nTxt.replace(/[>]/g,'&gt;');	
		for(x in icons){
			try{
			rex = new RegExp(icons[x], "g");
			}catch(e){alert(icons[x]);}
  			nTxt = nTxt.replace(rex,convertIcon(x));
		}
	return nTxt;	
}

function addMessageToBody(id,usr,txt){
	var msgArray = document.getElementById('msgList_'+id);
	var LI = document.createElement('LI');
	var nm = document.createElement('LI');
	var msg = document.createElement('LI');
	var UL = document.createElement('UL');
		nm.innerHTML = usr+' says:';
		msg.innerHTML = prepareText(txt);
		nm.className = 'lbl';
		msg.className = 'msg';
		UL.className='subMsg';
		UL.appendChild(nm);
		UL.appendChild(msg);
		
		LI.appendChild(UL);
		msgArray.appendChild(LI);
		
		document.getElementById("msgBox_"+id).scrollTop = 99999;
}


/*------------------------------- AJAX ----------------------------------------------*/
function send_request(txt){
	var params = new Object();
		params.msg = txt;
		params.id = this.session;
		http( 'POST' , '/chat/actions.cfc?method=send' , send_response , params );
}
function send_response(o){ /*-- ignore response --*/ }

function receive_request(id){ http( 'POST' , '/chat/actions.cfc?method=receive' , receive_response , 'id='+id ); }
function receive_response(o){
	document.getElementById('typing_'+o.id).innerHTML = ''
	for(var x=0;x < o.msgs.length;x++){
		addMessageToBody(o.id,o.alias,o.msgs[x].msg);
		
		d = document.getElementById('conv_'+o.id+'_content');
		if(d.style.display == 'none')
		document.getElementById('hndl_'+o.id).className = 'alrt';
			
		playSound('receive');
	}
	if(parseInt(o.typing)){
		document.getElementById('typing_'+o.id).innerHTML = o.alias+' is typing a message';
		clearStatus = setTimeout("document.getElementById('typing_"+o.id+"').innerHTML = ''",conv_intvl);
	}
	
}

function typing_request(id){ http( 'POST' , '/chat/actions.cfc?method=typing' , typing_response , 'id='+id ); }
function typing_response(o){ /*-- ignore response --*/ }
