

//	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://jerrata.com/software/bin/DoChatter200902109/";

// 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 = "johnnie@jerrata.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 = "A guest, not affiliated with Jerrata Solutions, has invited you to chat from the online demo of DoChatter.  Do you accept this invitation?";

//==============================================================================
//==============================================================================
//==============================================================================
// 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				= 500;
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";

var html = '';

html += '<div id="veil" style="background-color:#000000;height:100%;position:absolute;visibility:hidden;width:100%;z-index:5;"></div>';
html += '<div id="incoming_chat_request_popup" style="background-color:#464646;position:absolute;visibility:hidden;z-index:6;">';
html += '	<div style="background-color:#464646;border:1px solid #303030;height:160px;left:25px;position:absolute;top:25px;width:550px;">';
html += '		<div style="color:#ffffff;left:25px;position:absolute;top:25px;width:500px;">';
html += '			<table cellpadding="0" cellspacing="0" style="color:#a3a3a3;font-family:Helvetica;font-size:11px;line-height:150%;width:500px;">';
html += '				<tr>';
html += '					<td>';
html += '						<center>';
html += '							<img alt="Please select a chat request to answer, below." src="' + DOCHATTER_LOCATION + 'images/client_incoming_chat_req.gif" height="33" width="350">';
html += '						</center>';
html += '					</td>';
html += '				</tr>';
html += '				<tr>';
html += '					<td style="height:15px;"></td>';
html += '				</tr>';
html += '				<tr>';
html += '					<td style="color:#ffffff;font-family:Georgia;font-size:16px;">'
html += '						' + MESSAGE_INVITE_GUEST_TO_CONVO;
html += '					</td>';
html += '				</tr>';
html += '				<tr>';
html += '					<td style="height:15px;"></td>';
html += '				</tr>';
html += '				<tr>';
html += '					<td>';
html += '						<table style="width:100%;">';
html += '							<tr>';
html += '								<td style="cursor:pointer;cursor:hand;font-family:Georgia;font-size:16px;" onclick="window.open ( \'http://jerrata.com/?product=DoChatter&from=dochatter_installation_invite\', \'DoChatterPromoWindow\' );">';
html += '									<font style="color:#ffffff;font-weight:bold;">:-) ! (-:</font> &nbsp; <font style="color:gray;">Jerrata DoChatter</font>';
html += '								</td>';
html += '								<td style="color:#a3a3a3;font-family:Georgia;font-size:16px;text-align:right;">';
html += '									<input onclick="javascript:DeclineInvitation (); DismissPopup ();" type="button" value="Decline">';
html += '									&nbsp;or&nbsp;';
html += '									<input onclick="javascript:AcceptInvitation (); DismissPopup ();" type="button" value="Accept">';
html += '								</td>';
html += '							</tr>';
html += '						</table>';
html += '					</td>';
html += '				</tr>';
html += '			</table>';
html += '		</div>';
html += '	</div>';
html += '</div>';

document.write ( html );

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: current_admin_visibilityrefresh_interval
        			if ( ajax_response.substring ( 0, 1 ) == "1" )
        			{
        				if ( document.getElementById ( "is_admin_online" ) )
        					document.getElementById ( "is_admin_online" ).innerHTML = '<a href="javascript:ForceChat ();"><img border="0" src="' + DOCHATTER_LOCATION + 'images/admin_online.gif"></a>';
        			}
        			else
        			{
        				if ( document.getElementById ( "is_admin_online" ) )
        					document.getElementById ( "is_admin_online" ).innerHTML = '<a href="mailto:' + ADMINISTRATOR_EMAIL + '"><img border="0" src="' + DOCHATTER_LOCATION + 'images/admin_offline.gif"></a>';
        			}
        			
        			REFRESH_INTERVAL = parseInt ( ajax_response.substring ( 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 ()
{
	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 ( departments ) );
	
	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 ()
{
	var accepted_chat_request;
	
	// branch based on browser
	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 ( departments ) );
	
	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;
}
