/**
 * Saeven|CRM Chat-check proxy
 * V2.0, RC3
 *
 * use this tool to add a chat icon to your secondary sites, that ties
 * into the main helpdesk installation.
 */
var ChatStatus = function(){	
	var cdiv 			= null;
	var chat_div_name 	= "chat_div";
	var image_online	= "/sys/templates/system/visual/images/chat_online.png";
	var	image_offline	= "/sys/templates/system/visual/images/chat_offline.png";
	var image_wait		= "/sys/templates/system/visual/images/wait.gif";
	var portal_url		= "http://sys.prof1xer.com/portals/siteportal.php";
	var	firstCheck		= true;
	var updateTask		= null;
	var helpdesk_url	= "http://sys.prof1xer.com/";
	var chat_category	= "C1";
	
	/**
	 * Proxy page for the chat script
	 * @var string
	 */
	var chat_proxy		= null;
	
	/**
	 * Used as passback random salt, don't alter
	 */
	var date			= 0;
		
	// show the chat popup
	var showChatWindow	= function(){
		window.open( helpdesk_url + "chatpane.php","chat","width=500,height=500,top=150,left=150,resizable=yes,scrollbars=no,menubar=no,toolbar=no,status=no,location=no" );	
	};	
	
	// check to see if an admin is available for chat
	var checkResult 	= function( options, success, transport ){
		if( success ){
			var json = Ext.util.JSON.decode( transport.responseText );
			cdiv.update( "<img src='" + (json.online == 1 ? image_online : image_offline ) + "'>" );	
			
			if( json.online == 1 ){
				cdiv.on( 'click', showChatWindow );
				cdiv.setStyle( "cursor", "pointer" );
			}
			
			//if( json.invite )
			//	alert( json.text );	
			
			if( json.date )
				date = json.date;
			
			updateTask.delay( 45000, portalCheck );			
		}
		else{
			cdiv.update( "<img src='" + image_offline + "'>" );	
			updateTask.delay( 10000, portalCheck );
		}		
	};
	
	var portalCheck	= function(){
		updateTask	= new Ext.util.DelayedTask();
		var c 		= new Ext.data.Connection();		
		c.timeout	= 3000;
		c.request({
			url: chat_proxy ? chat_proxy : portal_url,
			method: 'post',
			params: { 	action: 'chatcheck', 
						mimetype: "json", 
						category: chat_category, 
						"date" : date,
						scrmproxy: portal_url
			},
			headers: { 'Accept' : 'application/json' },
			callback: checkResult
		});		
	};

	
	return {	
		// setters
		setDivName: function( s ){ chat_div_name = s; },
		setOnlineImage: function( s ){ image_online = s; },
		setOfflineImage: function( s ){ image_offline = s; },
		setWaitImage: function( s ){ image_wait = s; },
		setPortalURL: function( s ){ portal_url = s; },
		setProxyURL: function( s ){ chat_proxy = s; },
		setHelpdeskURL: function( s ){ helpdesk_url = s; },
		setCategory: function( s ){ chat_category = s; },
		
	
		// check to see if any admins are online
		checkAvailable: function(){
			if( firstCheck ){
				cdiv = Ext.get( chat_div_name );
				cdiv.update( "<img src='" + image_wait + "'>" );
				firstCheck = false;
			}
			
			portalCheck();		
		}
	};
	
}();
