

//	DoChatter.js: Javascript included on guest's browser
//	Jerrata DoChatter (c)2008-2009 Johnnie Rose, Jr. (johnnie@jerrata.com)
//	Revision 20090210
//	http://jerrata.com/?product=DoChatter

//	This Javascript file is included by the guest and enables the guest to force
//	a chat with the administrator (if the admin is online) and accept or decline
//	an invitation from the administrator to start a chat.

//==============================================================================
//==============================================================================
//==============================================================================
// WEBSITE-SPECIFIC VARIABLES
// Change the following settings to customize DoChatter to your website.

// Set DOCHATTER_LOCATION to the place where you put DoChatter.php
// and DoChatter.js, ensuring that there is a slash at the end.
var DOCHATTER_LOCATION = "http://weseekit.com/dochatter/";

// Enter your email address, below, to receive a notification when a guest
// leaves a message for you when you aren't online or choose to appear offline.
var ADMINISTRATOR_EMAIL = "weseekit@weseekit.com";

// This is the message displayed to guests when you invite a guest to start a
// chat from the DoChatter administrative interface.  You can edit this message
// as you see fit.
var MESSAGE_INVITE_GUEST_TO_CONVO = "One of our Seekers would like to start helping you. Do you accept this invitation?";

// Set this variable to true if you'd like visitors to send email to
// ADMINISTRATOR_EMAIL (above) when they click on the offline image.  Set this
// variable to false if, instead, you'd like a popup message (below) to appear.
var SEND_EMAIL_IF_ADMIN_OFFLINE = true;

// This is the popup message displayed to guests who click on the offline image
// if you've set SEND_EMAIL_IF_ADMIN_OFFLINE (above) to false.
var MESSAGE_ADMIN_OFFLINE = "We are deeply sorry, but this operator seems to be offline. Try visiting his or her profile and leave a message! Just click on \"View Profile\" next to his or her name.";

//==============================================================================
//==============================================================================
//==============================================================================
// PROGRAM CODE BEGINS HERE

var ACTION_UPDATE_GUEST				= "update_guest";
var ACTION_DECLINE_INVITATION		= "decline_invitation";
var ACTION_ACCEPT_INVITATION		= "accept_invitation";
var ACTION_SYNC_CONVO				= "sync_convo";
var ACTION_SHOW_CHAT				= "show_chat";
var ACTION_FORCE_CHAT				= "force_chat";
var AJAX_CMD_OK						= "ok";
var AJAX_CMD_ERROR					= "no";
var AJAX_CMD_NEW_GUEST				= "ng";
var AJAX_CMD_INVITE_GUEST_TO_CONVO	= "ci";
var AJAX_CMD_START_NEW_CONVO		= "nc";
var DOCHATTER_COOKIE_GUEST_ID		= "dochatter_guest_id";
var DOCHATTER_COOKIE_REFERRER		= "dochatter_referrer";
var CHAT_WINDOW_HEIGHT				= 550;
var CHAT_WINDOW_WIDTH				= 800;
var chat_window						= null;
var INCOMING_CHAT_REQUEST_POPUP_WIDTH	= 600;
var INCOMING_CHAT_REQUEST_POPUP_HEIGHT	= 210;
var incoming_chat_request_popup_active	= false;
var REFRESH_INTERVAL;
var guest_id = null;
var convo_id = null;
var request = null;

// if admin has not specified department(s), specify a default department
if ( typeof departments == "undefined" )
	var departments = "Default";

InitiateGuest ();

//==============================================================================
// HANDLER FUNCTIONS
//==============================================================================

function WriteCookie ( name, value )
{
	document.cookie = name + "=" + escape ( value ) + "; expires=Sat, 1 Jan 2050 12:00:00 UTC; path=/";
}

//==============================================================================
function ReadCookie ( name )
{
	if ( document.cookie.indexOf ( ";" ) == -1 )	// only 1 cookie -> return substring to length of document.cookie
		return unescape ( document.cookie.substring ( document.cookie.indexOf ( name ) + name.length + 1 ) );
		
	// multiple cookies -> return substring from name to the next semicolon after name or to length of document.cookie
	var end_index = document.cookie.indexOf ( ";", document.cookie.indexOf ( name ) );
	
	if ( end_index == -1 )
		end_index = document.cookie.length;
	
	return unescape ( document.cookie.substring ( document.cookie.indexOf ( name ) + name.length + 1, end_index ) );
}

//==============================================================================
function CookieExists ( name )
{
	if ( document.cookie.indexOf ( name ) == -1 )
		return false;
		
	return true;
}

//==============================================================================
function AJAXRequest ( action, params )
{
	// branch based on browser
	if ( window.XMLHttpRequest )
		request = new XMLHttpRequest ();
	else
		request = new ActiveXObject ( "Microsoft.XMLHTTP" );

	request.onreadystatechange = AJAXResponse;
    request.open ( "POST", DOCHATTER_LOCATION + "DoChatter.php?action=" + action, true );
	request.setRequestHeader ( 'Content-Type', 'application/x-www-form-urlencoded' );
	request.send ( params );
}

//==============================================================================
function AJAXResponse ()
{
	if ( request.readyState == 4 )
    {
        if ( request.status == 200 )
        {
        	var ajax_cmd	  = request.responseText.substring ( 0, 2 );
        	var ajax_response = request.responseText.substring ( 2 );
        	
        	switch ( ajax_cmd )
        	{
        		case AJAX_CMD_OK:	// parse the returned string of the form w/o spaces: ops_online_dept_grp_1 , ops_online_dept_grp_2, ... | refresh_interval
		
        			// apply "divjuggle" algorithm to successively get handles to all divs on webpage w/ id = "is_admin_online"
					var i = 0;
					var div, max, content, dept_groups;
					var divs = new Array ();
				
					while ( ( div = document.getElementById ( "is_admin_online" ) ) != null )
					{
						div.id = div.id + i++;
						divs.push ( div );
					}
					
					content = ( ajax_response.substring ( 0, ajax_response.indexOf ( "|" ) ) ).split ( "," );
					dept_groups = departments.split ( ";" );
				
					if ( divs.length < content.length )
						max = divs.length;
					else
						max = content.length;
				
					for ( i = 0; i < max; i++ )
					{
						if ( content [ i ] == "1" )	// admin online for this department group
						{
							divs [ i ].innerHTML = '<a href="javascript:ForceChat ( \'' + dept_groups [ i ] + '\' );"><img border="0" src="' + DOCHATTER_LOCATION + 'images/admin_online.gif"></a>';
						}
						else
						{
							if ( SEND_EMAIL_IF_ADMIN_OFFLINE )
								divs [ i ].innerHTML = '<a href="mailto:' + ADMINISTRATOR_EMAIL + '"><img border="0" src="' + DOCHATTER_LOCATION + 'images/admin_offline.gif"></a>';
							else
								divs [ i ].innerHTML = '<img border="0" onclick="javascript:window.alert ( MESSAGE_ADMIN_OFFLINE );" src="' + DOCHATTER_LOCATION + 'images/admin_offline.gif" style="cursor:pointer;cursor:hand;">';
						}
					}
				
					for ( i = 0; i < divs.length; i++ )
						divs [ i ].id = "is_admin_online";
        			
        			REFRESH_INTERVAL = parseInt ( ajax_response.substring ( ajax_response.indexOf( "|" ) + 1 ) ) * 1000;
					
					setTimeout ( "UpdateGuest ()", REFRESH_INTERVAL );
        			
					break;
        		
				case AJAX_CMD_ERROR:

					window.alert ( ajax_response );
        			
					break;
        		
				case AJAX_CMD_NEW_GUEST:
        			
					guest_id = ajax_response.substring ( 0, ajax_response.indexOf ( "|" ) );
					
					WriteCookie ( DOCHATTER_COOKIE_GUEST_ID, guest_id );
					
        			REFRESH_INTERVAL = parseInt ( ajax_response.substring ( ajax_response.indexOf ( "|" ) ) ) * 1000;
        			
        			setTimeout ( "UpdateGuest ()", REFRESH_INTERVAL );
        			
        			break;
        		
        		case AJAX_CMD_INVITE_GUEST_TO_CONVO:
        		
        			convo_id = ajax_response;
        			
					LaunchIncomingChatRequestPopup ();
        			
        			break;
        	}
		}
    }
}

//==============================================================================
function LaunchIncomingChatRequestPopup ()
{
	var window_width;
	var window_height;
	var vertical_scroll_pos;
	var horizontal_scroll_pos;
		
	if ( document.layers || ( document.getElementById && !document.all ) )
	{
	   window_width = window.innerWidth;
	   window_height = window.innerHeight;
	   vertical_scroll_pos = window.pageYOffset;
	   horizontal_scroll_pos = window.pageXOffset;
	}
	if ( document.all )
	{
	   window_width = document.body.clientWidth;
	   window_height = document.body.clientHeight;
	   vertical_scroll_pos = document.body.scrollTop;
	   horizontal_scroll_pos = document.body.scrollLeft;
	}
		
	document.getElementById ( "incoming_chat_request_popup" ).style.top = vertical_scroll_pos + ( window_height - INCOMING_CHAT_REQUEST_POPUP_HEIGHT ) / 2;
	document.getElementById ( "incoming_chat_request_popup" ).style.left = horizontal_scroll_pos + ( window_width - INCOMING_CHAT_REQUEST_POPUP_WIDTH ) / 2;
	document.getElementById ( "incoming_chat_request_popup" ).style.width = INCOMING_CHAT_REQUEST_POPUP_WIDTH;
	document.getElementById ( "incoming_chat_request_popup" ).style.height = INCOMING_CHAT_REQUEST_POPUP_HEIGHT;
	document.getElementById ( "incoming_chat_request_popup" ).style.visibility = "visible";
		
	document.getElementById ( "veil" ).style.top = vertical_scroll_pos;
	document.getElementById ( "veil" ).style.left = horizontal_scroll_pos;
		
	var alpha = 75;
		
	document.getElementById ( "veil" ).style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=0,opacity:" + alpha + ")";	// MSIE
	document.getElementById ( "veil" ).style.KHTMLOpacity = alpha / 100;	// Safari < 1.2, Konqueror
	document.getElementById ( "veil" ).style.MozOpacity = alpha / 100;	// Older Mozilla & Firefox
	document.getElementById ( "veil" ).style.opacity = alpha / 100;	// Safari 1.2+, newer Mozilla & Firefox, CSS3
		
	document.getElementById ( "veil" ).style.visibility = "visible";
	
	incoming_chat_request_popup_active = true;
}

//==============================================================================
window.onresize = function ()
{
	if ( incoming_chat_request_popup_active )
		LaunchIncomingChatRequestPopup ();
}

//==============================================================================
function DismissPopup ()
{
	document.getElementById ( "incoming_chat_request_popup" ).style.visibility = "hidden";
	document.getElementById ( "veil" ).style.visibility = "hidden";
	
	incoming_chat_request_popup_active = false;
}

//==============================================================================
// lets the client invite the admin to start a chat
function ForceChat ( from_dept_group )
{
	var force_chat_request;
	
	// branch based on browser
	if ( window.XMLHttpRequest )
		force_chat_request = new XMLHttpRequest ();
	else
		force_chat_request = new ActiveXObject ( "Microsoft.XMLHTTP" );

    force_chat_request.open ( "POST", DOCHATTER_LOCATION + "DoChatter.php?action=" + ACTION_FORCE_CHAT, false );
	force_chat_request.setRequestHeader ( 'Content-Type', 'application/x-www-form-urlencoded' );
	force_chat_request.send ( "guest_id=" + guest_id + "&departments=" + escape ( from_dept_group ) );
	
	switch ( force_chat_request.responseText.substring ( 0, 2 ) )
	{
		case AJAX_CMD_ERROR:
		
			window.alert ( force_chat_request.responseText.substring ( 2 ) );
			
			break;
			
		case AJAX_CMD_START_NEW_CONVO:
			
			var chat_window_params = new Array ();
		        			
		    chat_window_params.push ( "width=" + CHAT_WINDOW_WIDTH );
		    chat_window_params.push ( "height=" + CHAT_WINDOW_HEIGHT );
		    chat_window_params.push ( "left=" + ( screen.width - CHAT_WINDOW_WIDTH ) / 2 );
			chat_window_params.push ( "top=" + ( screen.height - CHAT_WINDOW_HEIGHT ) / 2 );
			chat_window_params.push ( "location=no" );
			chat_window_params.push ( "resizable=no" );
			chat_window_params.push ( "scrollbars=no" );
			chat_window_params.push ( "status=no" );
			chat_window_params.push ( "toolbar=no" );
			chat_window_params.push ( "menubar=no" );
			chat_window_params.push ( "directories=no" );
		
			chat_window = window.open ( DOCHATTER_LOCATION + "DoChatter.php?action=" + ACTION_SHOW_CHAT + "&convo_id=" + force_chat_request.responseText.substring ( 2 ), "DoChatterChatWindow", chat_window_params.join ( ", " ) );
			
			if ( !chat_window )
			{
				window.alert ( "DoChatter was unable to launch a 1-on-1 chat window." );
			}
			else
			{
				if ( window.focus )
					chat_window.focus ();
			}
			
			break;
	}
}

//==============================================================================
function AcceptInvitation ()
{
	// boil departments variable down to comma-delimited list of distinct departments
	var from_dept_group_prime = ( departments.replace ( /;/g, "," ) ).split ( "," );
	var from_dept_group = new Array ();
	
	for ( var i = 0; i < from_dept_group_prime.length; i++ )
	{
		for ( var f = 0; f < from_dept_group.length; f++ )
		{
			if ( from_dept_group [ f ] == from_dept_group_prime [ i ] )
				break;
		}
		
		if ( f == from_dept_group.length )	// didn't find group_prime [ i ] in group
			from_dept_group.push ( from_dept_group_prime [ i ] );
	}
	
	from_dept_group = from_dept_group.join ( "," );
	
	// branch based on browser
	var accepted_chat_request;
	
	if ( window.XMLHttpRequest )
		accepted_chat_request = new XMLHttpRequest ();
	else
		accepted_chat_request = new ActiveXObject ( "Microsoft.XMLHTTP" );

    accepted_chat_request.open ( "POST", DOCHATTER_LOCATION + "DoChatter.php?action=" + ACTION_ACCEPT_INVITATION, false );
	accepted_chat_request.setRequestHeader ( 'Content-Type', 'application/x-www-form-urlencoded' );
	accepted_chat_request.send ( "guest_id=" + guest_id + "&convo_id=" + convo_id + "&departments=" + escape ( from_dept_group ) );
	
	switch ( accepted_chat_request.responseText.substring ( 0, 2 ) )
	{
		case AJAX_CMD_ERROR:
		
			window.alert ( accepted_chat_request.responseText.substring ( 2 ) );
			
			break;
			
		case AJAX_CMD_START_NEW_CONVO:
			
			var chat_window_params = new Array ();
		        			
		    chat_window_params.push ( "width=" + CHAT_WINDOW_WIDTH );
		    chat_window_params.push ( "height=" + CHAT_WINDOW_HEIGHT );
		    chat_window_params.push ( "left=" + ( screen.width - CHAT_WINDOW_WIDTH ) / 2 );
			chat_window_params.push ( "top=" + ( screen.height - CHAT_WINDOW_HEIGHT ) / 2 );
			chat_window_params.push ( "location=no" );
			chat_window_params.push ( "resizable=no" );
			chat_window_params.push ( "scrollbars=no" );
			chat_window_params.push ( "status=no" );
			chat_window_params.push ( "toolbar=no" );
			chat_window_params.push ( "menubar=no" );
			chat_window_params.push ( "directories=no" );
		
			chat_window = window.open ( DOCHATTER_LOCATION + "DoChatter.php?action=" + ACTION_SHOW_CHAT + "&convo_id=" + accepted_chat_request.responseText.substring ( 2 ), "DoChatterChatWindow", chat_window_params.join ( ", " ) );
			
			if ( !chat_window )
			{
				window.alert ( "DoChatter was unable to launch a 1-on-1 chat window." );
			}
			else
			{
				if ( window.focus )
					chat_window.focus ();
			}
			
			break;
	}
	
	setTimeout ( "UpdateGuest ()", REFRESH_INTERVAL );
}

//==============================================================================
function DeclineInvitation ()
{
	AJAXRequest ( ACTION_DECLINE_INVITATION, "convo_id=" + convo_id + "&departments=" + escape ( departments ) );
}

//==============================================================================
function UpdateGuest ()
{
	AJAXRequest ( ACTION_UPDATE_GUEST, "guest_id=" + guest_id + "&departments=" + escape ( departments ) + "&page=" + window.location + "&referrer=" + ReadCookie ( DOCHATTER_COOKIE_REFERRER ) );
}

//==============================================================================
function InitiateGuest ()
{
	var referrer;
	
	if ( CookieExists ( DOCHATTER_COOKIE_GUEST_ID ) )
	{
		guest_id = ReadCookie ( DOCHATTER_COOKIE_GUEST_ID );
		referrer = ReadCookie ( DOCHATTER_COOKIE_REFERRER );
		
		AJAXRequest ( ACTION_UPDATE_GUEST, "guest_id=" + guest_id + "&departments=" + escape ( departments ) + "&page=" + window.location + "&referrer=" + referrer + "&new=page" );
	}
	else
	{
		referrer = "None provided";
		
		if ( document.referrer && ( document.referrer != "" ) )
			referrer = document.referrer;

		WriteCookie ( DOCHATTER_COOKIE_REFERRER, referrer );
		
		AJAXRequest ( ACTION_UPDATE_GUEST, "departments=" + escape ( departments ) + "&page=" + window.location + "&referrer=" + referrer + "&new=page" );
	}
}

//==============================================================================
function GetRefreshInterval ()
{
	return REFRESH_INTERVAL;
}