/***********************************************************************************/
/* Project:				Popper Version 2 (or "Pooper" for Olivier)
/* Alpha Date:			December 19 2007
/* Beta Launch:			March 18 2008
/* Beta Client Launch:	April 21 2008
/* Live:				May ?? 2008
/* Technical Contact:	Nick
/* File:				popper.js Version 2, used with popper.mv,logfile.mv
/* Description:			This js is used to make the popper appear in he user's nvbar.
/***********************************************************************************/
// DB variables
var PP_db;					// Platform code
var PP_acc;					// The account name of the current user
var PP_refreshRate;			// In milliseconds
var PP_lang;				// Langauge of platform (or user)
var PP_fromtime;			// Last time Popper checked for new events (is actually a recno ultimately)

// JS variables
var PP_timer;				// Timer that will make the Ajax call every n seconds
var PP_request;				// The Ajax request variable holder
var PP_alertItems = [];		// Holds the raw data returned from popper.mv
var PP_alertItemsText = [];	// Holds the text that will appear in the popper
var PP_alertItemsTimes = [];// Holds the time at which the pop came in
var PP_alertItemsHeight = [];// Holds the height of the div of the alert
var PP_alertCounter = 0;
var PP_displayTimer = [];	// Keeps track of how long each alert has been displayed for
var PP_clearDisplayRate = 8000;	// Defines the number of milliseconds to wait before removing a display alert
var PP_globalAlert = '';
var PP_hasFocus = true;		// Flag to determine if user is actively on website or somewhere else
var PP_debug_mode = 0;				// Debug mode switch
var PP_debug_acc = 'nicolas.jouannem';	// Debug account access

// Not used for now. Could be used to add a blinking effect
var PP_quiteBGcolor;
var PP_alertBGcolor;

// Display variabels
var PP_alertItem_height = '75px';
var PP_alertItem_width = '135px';
var PP_lineLen = 26;

var PP_timerlen = 5;
var PP_slideAniLen = 250;
var PP_timerID = new Array();
var PP_startTime = new Array();
var PP_obj = new Array();
var PP_endHeight = new Array();
var PP_moving = new Array();
var PP_dir = new Array();

// Browser detection variables
var app_agent = navigator.userAgent.toLowerCase();
var isSafari = app_agent.indexOf('safari')>=0;
var isOpera = false;
var isFF = app_agent.indexOf('firefox')>=0;
var isIE = false;

// Emergency & Error handling variables
var PP_offline = false;
var PP_retryInterval = 120;				// Number of seconds to wait before trying to reconnect
var PP_popup_suspected = false;
var PP_responseTime = 0;
var PP_responseTimer;
var PP_requestOut = false;
var PP_popperOffline = false;

var PP_defaultTotalRecapNumberToDisplay = 5;	// Default number of alerts to show when activating a recap

// Called onLoad of "Body" tag
function PP_F_init(account,shortname,refreshrate,language,fromtime)
{
	/* Detect IE browser */
	app_agent = navigator.appName.toLowerCase();
	if (app_agent.indexOf('microsoft')>=0 && isSafari == false && isFF == false){
		isIE = true;
	}

	/* Set global vars */
	PP_db = shortname;
	PP_acc = account;
	PP_refreshRate = refreshrate;
	PP_refreshRate = 10000;
	PP_lang = language;
	PP_fromtime = 'new_' + fromtime;
	
	if (isIE) PP_alertItem_height = '120px';
	
	/* Set display */
	//$('PP_popper').innerHTML = $('PP_popper').innerHTML + '<div style=\"margin-left: 3px; width: 145px; background-image: url(\'/scripts/images/PP_corners.gif\'); background-width: 100%;\"> <div class=\"alert_header\"><span class=title><a href=\"javascript: PP_F_showLastAlerts(\'\')\">' + 'NV Live Notification' + ' <span id=\"totalalerts\" class=\"alert_counter\"></span></a></span></div> </div>';	
	//$('PP_popper').innerHTML = $('PP_popper').innerHTML + '<div style=\"margin-left: 3px; width: 145px;\"><div class=\"top-left\"></div><div class=\"top-right\"></div><div class=\"alert_header\"><span class=title><a href=\"javascript: PP_F_showLastAlerts(\'\')\">' + 'NV Live Notification' + ' <span id=\"totalalerts\" class=\"alert_counter\"></span></a></span></div>'; // <div style=\"border-bottom: 2px solid #808080;\"></div></div>
	//$('PP_popper').innerHTML = $('PP_popper').innerHTML + '<div style=\"margin-left: 3px; width: 135px;\"><div class=\"top-left\"></div><div class=\"top-right\"></div><div class=\"inside\"><div class=\"alert_header\" style=\"\"><span class=title>' + 'NV Live Notifier ' + '<B><a href=\"javascript: PP_F_showLastAlerts(\'\')\"><span id=\"totalalerts\" class=\"alert_counter\"></span></a></B></span></div><p class=\"notopgap\"><span id=\"status_image_standby\"><img width=\"19\" height=\"19\" align=\"absmiddle\" src=\"/scripts/images/PP_online.gif\" border=\"0\"> Online</span><span id=\"status_image_updating\"><img align=\"absmiddle\" height=\"19\" src=\"/lib/osx/spinning.gif\" border=\"0\"> Updating</span><span id=\"status_image_offline\"><img align=\"absmiddle\" src=\"/scripts/images/PP_stop.gif\" height=\"19\" border=\"0\"> Offline</span></p><p class=\"nobottomgap\"></p></div><div class=\"bottom-left\"></div><div class=\"bottom-right\"></div></div>';
	//$('PP_popper').innerHTML = $('PP_popper').innerHTML + '<div style=\"margin-left: 3px; width: 135px; border-bottom: 2px solid #808080; background-color: #E6E6E6;\"><div class=\"top-left\"></div><div class=\"top-right\"></div><div class=\"inside\"><div class=\"alert_header\" style=\"\"><span class=title>' + 'NV Live Notifier ' + '<B><a href=\"javascript: PP_F_showLastAlerts(\'\')\"><span id=\"totalalerts\" class=\"alert_counter\"></span></a></B></span></div>test</div>';
	$('PP_popper').innerHTML = $('PP_popper').innerHTML + '<div class=\"title_header\"><span class=\"title\">' + '&nbsp;NV Live Notifier ' + '<B><a href=\"javascript: PP_F_showLastAlerts(\'\')\"><span id=\"totalalerts\" class=\"alert_counter\"></span></a></B></span></div>';
	showStatus(1);	// Display stand-by status
	PP_F_timer();
}

// This function turns off Popper
function PP_F_goOffline()
{
	try {
		clearTimeout(PP_timer);
		PP_requestOut = false;
		PP_popperOffline = true;
		showStatus(0);
		//if (PP_popup_suspected == false)
		//{
			// Shut-off was not due to popup-blocker but to server
			PP_timer = setTimeout("PP_F_timer()",(PP_retryInterval*1000));
		//}
	} catch(e) {
		alert('In PP_F_goOffline() - ' + e.number + ' ' + e.description);
	}
}

function PP_F_goOfflinePERM()
{
	try {
		clearTimeout(PP_timer);
		PP_requestOut = false;
		PP_popperOffline = true;
		showStatus(0);
		//if (PP_popup_suspected == false)
		//{
			// Shut-off was not due to popup-blocker but to server
			//PP_timer = setTimeout("PP_F_timer()",(PP_retryInterval*1000));
		//}
	} catch(e) {
		alert('In PP_F_goOfflinePERM() - ' + e.number + ' ' + e.description);
	}
}

// This function increase the response time
function PP_F_responseTime()
{
	PP_responseTime++;
	PP_responseTimer = setTimeout("PP_F_responseTime()",1);
}

// This function starts the timer and makes the request
function PP_F_timer()
{
	if (PP_popperOffline == true)
	{
		showStatus(2);
		PP_popperOffline = false;
	} else {
		showStatus(1);
	}
	
	if (PP_requestOut == true)
	{
		PP_F_goOffline();
		return;
	}
	var url 	= '/' + PP_db + '/popper.mv';
	var params 	= 'fromtime=' + PP_fromtime + '&action=fetch';
	//showStatus(2);
	
	
	// Start timer
	//clearInterval(PP_responseTimer);
	PP_responseTime = 0;
	PP_F_responseTime();
	
	PP_request = new Ajax.Request(url,{method: 'post', asynchronous: true, parameters: params, onSuccess: PP_F_processFetch, onFailure: PP_F_processError});
	PP_requestOut = true;
}

function PP_F_updateCounter()
{
	document.getElementById('totalalerts').innerHTML = "(" + PP_alertCounter + ")";
}

/* AJAX manipulations */
// Handles successful results from Ajax call
var PP_F_processFetch = function PP_F_get(t)
{
	// Stop timer
	clearTimeout(PP_responseTimer);
	PP_requestOut = false;
	//$('PP_popper').innerHTML = PP_responseTime;
	

	// For debug purposes (to be removed)
	//$('PP_popper').innerHTML = t.responseText;
	var items = t.responseText.split("");	// NOTE: There is an invisible character between the quotes
	var temp_raw_text = '';	// To group alerts together when they come in packs
	var number_of_new_alerts = 0;
	//$('PP_popper').innerHTML = t.responseText;
	
	if (t.responseText.indexOf("<HTML>") > 0)
	{
		showStatus(0);
		//alert('Warning! We have detected that you have logged in somewhere else. Your connection will be terminated.');
		//parent.frames[2].location.reload();
		//window.parent.top.location.href = 'http://www.etheryl.net/' + PP_db;
		PP_F_goOffline();
		return false;
	}

	if (trim(items[0]) == 'GOOFFLINENOW')
	{
		// Server is in a critical situation and someone has pulled the plug (perhaps)
		PP_F_goOfflinePERM();
		return;
	}

	
	if (trim(items[0]) == 'ERROR')
	{
		// PP_fromtime = trim(items[1]); --> Not needed because it was already set from previous call.
		PP_goOffline();
		return;
	}
	
	if (trim(items[0]) != 'NONEWEVENTS')
	{
		try {
			for (var i=0; i < items.length-1; i=i+2)
			{
				//$('PP_popper').innerHTML = items[0];
				//alert('AC = ' + PP_alertCounter + ' i = ' + trim(items[i]) + ' (i+1)= ' + trim(items[i+1]));
				
				temp_raw_text = trim(items[i]);
				PP_alertItems[PP_alertCounter] = trim(items[i+1]) + '#' + trim(items[i]);
				PP_alertItemsText[PP_alertCounter] = temp_raw_text;
				//PP_F_showAlert(PP_alertCounter);
				PP_F_createAlertV2(PP_alertCounter);
				PP_alertCounter++;
				number_of_new_alerts++;
			}
			PP_fromtime = trim(items[i]);
			PP_F_updateCounter();
			PP_F_showLastAlerts(number_of_new_alerts);
		} catch(e) {
			//alert('here Error ' + e.name + ' -- ' + e.message);
			// Something went wrong, turn off popper
			PP_F_goOffline();
		}
	} else {
		PP_fromtime = trim(items[1]);
	}
	
	// Check if server took too long to respond.
	if (PP_responseTime > 70)
	{
		PP_F_goOffline();
		return;
	}
	
	if (PP_popperOffline == false)
	{
		// Set timer for next call
		PP_timer = setTimeout("PP_F_timer()",PP_refreshRate);
		showStatus(1);	// Change status
	}
	
}

// Handles errors in Ajax call
var PP_F_processError = function PP_F_error(t)
{
	clearTimeout(PP_responseTimer);
	PP_F_goOffline();
	// alert('AJAX Error ' + t.status + ' -- ' + t.statusText);
}

/* Display function for Popper */
// Show new item in alert box by creating a new span element
function PP_F_showAlert(num)
{
	var newDiv = '<div id=item' + num + ' style=\" border-bottom: 1px solid #ccc; padding:5px; overflow:hidden; height:50px; display:none; margin:auto; width: ' + PP_alertItem_width +'\">' + PP_alertItemsText[num] + '</div>';
	$('PP_popper').innerHTML = $('PP_popper').innerHTML + newDiv;
	slidedown('item'+num);
	PP_displayTimer[num] = setTimeout("PP_F_clearAlert("+num+")",PP_clearDisplayRate);
	
}

// Slight modification to the above function. This one doesn't display the new item.
function PP_F_createAlertV2(num)
{
	try {
		var h = PP_F_getHeight(PP_alertItemsText[num]);
		var tempstr = PP_alertItemsText[num];
		if (PP_debug_mode && PP_acc == PP_debug_acc) alert('h = ' + h);
		PP_alertItemsHeight[num] = h;
		if (PP_debug_mode && PP_acc == PP_debug_acc) alert('PP_alertItemsHeight['+num+'] = ' + PP_alertItemsHeight[num]);
		var newDiv = '<div id=item' + num + ' style=\"overflow:hidden; height: ' + h + 'px; display:none; margin-left: 3px; width: ' + PP_alertItem_width +'\"><div class=\"top-left\"></div><div class=\"top-right\"></div><div class=\"inside\"><div class=\"alert_header\" style=\"\">' + getTime() + '</div><p class=\"notopgap\">' + PP_alertItemsText[num] + '</p><p class=\"nobottomgap\"></p></div><div class=\"bottom-left\"></div><div class=\"bottom-right\"></div></div>';
		/*
		if (tempstr.indexOf('said:') > 0 || tempstr.indexOf('dit:') > 0)
		{
			PP_globalAlert = PP_alertItemsText[num];
			PP_globalAlert = PP_globalAlert.replace(/(<([^>]+)>)/ig,""); 
		}
		*/
		// If this is a chatroom invitation, launch invitation popup
		if (tempstr.indexOf('chatroom') > 0)
		{
			PP_showChatInvitation(num);
		}
		if (tempstr.indexOf('dit:') > 0 || tempstr.indexOf('said:') > 0)
		{
			PP_showIM(num);
		}
		//var newDiv = '<div id=item' + num + ' style=\"overflow:hidden; height: ' + PP_alertItem_height + '; display:none; margin-left: 3px; width: ' + PP_alertItem_width +'\"><div class=\"top-left\"></div><div class=\"top-right\"></div><div class=\"inside\"><p class=\"notopgap\">' + getTime() + '</p><p class=\"nobottomgap\">' + PP_alertItemsText[num] + '</p></div><div class=\"bottom-left\"></div><div class=\"bottom-right\"></div></div>';
		//alert(newDiv);
		$('PP_popper').innerHTML = $('PP_popper').innerHTML + newDiv;
	} catch(e) {
		PP_popup_suspected = true;
		PP_F_goOffline();
		//if (e.number == -2146823281)
		if (PP_lang == 'en')
		{
			alert('It appears that you have a popup-blocker which is blocking notifications from NV Live. Please allow your browser to display pop-ups coming from:\n\nhttp://www.etheryl.net/\n\nYou will not receive notifications until you change this setting. NV Live will try reconnecting in a few minutes.');
		}
		if (PP_lang == 'fr')
		{
			alert('Il semble que vous avez un anti-popups qui g\350ne le bon fonctionnement de NV Live.\n\nPour recevoir des notifications instantan\351es, veuillez authoriser le site www.etheryl.net a vous montrer des pop-ups.\n\nVous ne pouvez pas recevoir de notifications tant que ce syst\352me est en place. NV Live tantera de se reconnecter dans quelques minutes.');
		}
		//alert('createAlertV2 ' + e.name + ' ' + e.description + ' ' + e.number);		
	}
}

// Parse URL string for values
function PP_getParam(param,str)
{
	// Use window.location.href instead of url to parse current URL
	param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+param+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( str );
	if( results == null )
		return "";
	else
		return results[1];
}

// Display a popup window for chat invitation with 3 possible options
function PP_showChatInvitation(alertid)
{
	var w = window.screen.width;
	w = (w/2) - 200;
	var h = window.screen.height;
	h = (h/2) - 140;
	var text = PP_alertItemsText[alertid];
	var filterid = PP_getParam('r',text);
	text = escape(text);
	var URL = '/' + PP_db + '/popper.mv?showInvitation=1&text=' + text + '&room=' + filterid + '&db=' + PP_db;
	day = new Date();
	id = day.getTime();
	var newid = 'p' + id;
	eval("page" + id + " = window.open(URL, '" + newid + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=280,left=" + w +",top=" + h + "');");
	//var newWin = window.open(URL, 'chat'+id, 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=280,left=' + w +',top=' + h + '\'');
	if (window.focus) {
		eval("page"+id+".focus();");
	}
	//newWin.focus()}	// Set focus on new window
	//return true;
}

// Display a popup window for chat invitation with 3 possible options
function PP_showIM(alertid)
{
	var w = window.screen.width;
	w = (w/2) - 200;
	var h = window.screen.height;
	h = (h/2) - 140;
	var text = PP_alertItemsText[alertid];
	text = escape(text);
	
	var temp = PP_alertItems[PP_alertCounter];
	var temp2 = temp.split("#");
	imsender = temp2[0];	
	
	var URL = '/' + PP_db + '/popper.mv?showIM=1&text=' + text + '&db=' + PP_db + '&imsender=' + imsender;
	day = new Date();
	id = day.getTime();
	var newid = 'p' + id;
	eval("page" + id + " = window.open(URL, '" + newid + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=300,left=" + w +",top=" + h + "');");
	//var newWin = window.open(URL, 'chat'+id, 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=280,left=' + w +',top=' + h + '\'');
	if (window.focus) {
		eval("page"+id+".focus();");
	}
	//newWin.focus()}	// Set focus on new window
	//return true;
}

// Determine type of event to estimate height of div being created. Ideally, we would like it to NOT have to specify the height in the style of the div but we must
// Guess is done based on text received
function PP_F_getHeight(text)
{
	var ret = PP_alertItem_height;
	if (text.indexOf('chatroom') > 0)
	{
		if (PP_debug_mode && PP_acc == PP_debug_acc) alert('chat detected');
		if (isIE) { return '145'; } else { return '95'; }
	}
	if (text.indexOf('said:') > 0 || text.indexOf('dit:') > 0)
	{
		if (PP_debug_mode && PP_acc == PP_debug_acc) alert('im detected');
		if (isIE) { return '145'; } else { return '105'; }
	}
	if (text.indexOf('online') > 0 || text.indexOf('offline') > 0 || text.indexOf('en ligne') || text.indexOf('d&eacute;connect&eacute;') > 0)
	{
		if (PP_debug_mode && PP_acc == PP_debug_acc) alert('online presence detected');
		if (isIE) { return '130'; } else { return '84'; }
	}
	return ret;
}

function PP_F_createAlertV1(num)
{
	var newDiv = '<div id=item' + num + ' style=\" border-bottom: 1px solid #ccc; padding:5px; overflow:hidden; height:50px; display:none; margin:auto; width: ' + PP_alertItem_width +'\">' + PP_alertItemsText[num] + '</div>';
	$('PP_popper').innerHTML = $('PP_popper').innerHTML + newDiv;	
}
// Remove item from display box by hiding span
function PP_F_clearAlert(n)
{
	//$('item'+n).style.display = 'none';
	slideup('item'+n);
}

// Makes last x alerts visible where x is either defined or default is used.
function PP_F_showLastAlerts(x)
{
	var num;
	var j = 0;		// Temporary counter to count how many alerts have been made visible again
	
	if (x == '')
	{
		num = PP_defaultTotalRecapNumberToDisplay;
	} else {
		num = x;
	}
	
	for (var i = PP_alertCounter-1; i >= 0 && j <= (num-1); i--)
	{
		slidedown('item'+i);
		PP_displayTimer[i] = setTimeout("PP_F_clearAlert("+i+")",PP_clearDisplayRate);
		j++;
	}
	// If user receives a direct message, then force an alert
	if (PP_globalAlert != '')
	{
		//alert(PP_globalAlert);
		window.focus();
		PP_globalAlert = '';	// Empty alert so that it doesn't show the next one.
	}
}

// Show the last x alerts in the Popper (doesn't work now)
function PP_F_showLast(x)
{
	var j = 0;
	for (var i = (PP_alertCounter-1); i >= 0; i--)
	{
		PP_F_showAlert(i);
		j++;
	}
}

// Animation functions
function slidedown(objname){
  if(PP_moving[objname])
    return;
 
  if(document.getElementById(objname).style.display != "none")
    return; // cannot slide down something that is already visible
 
  PP_moving[objname] = true;
  PP_dir[objname] = "down";
  startslide(objname);
}
 
function slideup(objname){
  if(PP_moving[objname])
    return;
 
  if(document.getElementById(objname).style.display == "none")
    return; // cannot slide up something that is already hidden
 
  PP_moving[objname] = true;
  PP_dir[objname] = "up";
  startslide(objname);
}

function startslide(objname)
{
  PP_obj[objname] = document.getElementById(objname);
  //PP_endHeight[objname] = parseInt(PP_obj[objname].style.height);
  var temp = objname;
  var r = temp.match(/[\d\.]+/g);
  temp = +r[0];
  if (PP_debug_mode && PP_acc == PP_debug_acc) alert('temp = ' + temp);
  PP_endHeight[objname] = PP_alertItemsHeight[temp];
  if (PP_debug_mode && PP_acc == PP_debug_acc) alert('using ' + PP_endHeight[objname]);
  PP_startTime[objname] = (new Date()).getTime();
 
  if(PP_dir[objname] == "down"){
    PP_obj[objname].style.height = "1px";
  }
 
  PP_obj[objname].style.display = "block";
 
  PP_timerID[objname] = setInterval('slidetick(\'' + objname + '\');',PP_timerlen);
}

function slidetick(objname){
  var elapsed = (new Date()).getTime() - PP_startTime[objname];
 
  if (elapsed > PP_slideAniLen)
    endSlide(objname)
  else {
    var d =Math.round(elapsed / PP_slideAniLen * PP_endHeight[objname]);
    if(PP_dir[objname] == "up")
      d = PP_endHeight[objname] - d;
 
    PP_obj[objname].style.height = d + "px";
  }
 
  return;
}

function endSlide(objname){
  clearInterval(PP_timerID[objname]);
 
  if(PP_dir[objname] == "up")
    PP_obj[objname].style.display = "none";
 
  PP_obj[objname].style.height = PP_endHeight[objname] + "px";
 
  delete(PP_moving[objname]);
  delete(PP_timerID[objname]);
  delete(PP_startTime[objname]);
  delete(PP_endHeight[objname]);
  delete(PP_obj[objname]);
  delete(PP_dir[objname]);
 
  return;
}

/* Text manipulation functions */
function ltrim(str) { 
	for(var k = 0; k < str.length && isWhitespace(str.charAt(k)); k++);
	return str.substring(k, str.length);
}
function rtrim(str) {
	for(var j=str.length-1; j>=0 && isWhitespace(str.charAt(j)) ; j--) ;
	return str.substring(0,j+1);
}
function trim(str) {
	return ltrim(rtrim(str));
}
function isWhitespace(charToCheck) {
	var whitespaceChars = " \t\n\r\f";
	return (whitespaceChars.indexOf(charToCheck) != -1);
}

/* Time manipulation functions */
// Returns a string which represents the user's current time as per his computer display
function getTime() {
	var now = new Date;
	var time_stamp = now.getHours() + ":" + showZeroFilled(now.getMinutes()) // + ":" + showZeroFilled(now.getSeconds());
	return time_stamp;
}

function showZeroFilled(inValue) {
	if (inValue > 9)
	{
		return "" + inValue;
	}
	return "0" + inValue;
}

/* Status display functions */
function hideAllStatuses()
{
	$('status_image_updating').style.display = 'none';
	$('status_image_offline').style.display = 'none';
	$('status_image_standby').style.display = 'none';
}

function showStatus(statusCode)
{
	return;
	hideAllStatuses();
	if (statusCode == 0) $('status_image_offline').style.display = 'block';
	if (statusCode == 1) $('status_image_standby').style.display = 'block';
	if (statusCode == 2) $('status_image_updating').style.display = 'block';
}

function manageFocus(status)
{
	if (status == 0)
	{
		PP_hasFocus = false;
		document.getElementById('PP_focus_status').innerHTML = "FOCUS: FALSE";
	} else {
		document.getElementById('PP_focus_status').innerHTML = "FOCUS: TRUE";
		PP_hasFocus = true;
	}
}

/* THIS CODE IS USED IN THE POPUP WINDOW THAT IS VIEWED WHEN A CHAT INVITATION OCCURS */
function sendChatResponse(resp,room,db)
{
	var ele_opt = document.getElementById('options');
	var ele_spin = document.getElementById('sending');
	var chat_url = '/' + db + '/popper.mv?room=' + room;
	var params = 'action=chat_resp&resp=' + resp;
	
	ele_opt.style.display = 'none';
	ele_spin.style.display = 'block';
	
	var chatresponse = new Ajax.Request(chat_url, { asynchronous: true, method: 'post', parameters: params, onFailure: function(t) { 
		// alert('Error ' + t.status + ' -- ' + t.statusText);
		try {
			ele_spin.innerHTML = "Sorry, we were unable to process your response. Please try again later.<BR><BR>You may close this window.";
		} catch (e) {
			alert('Sorry, we were unable to process your response. Please try again later.You may close this window.');	
		}
	},
	onSuccess: function(t) {
		window.close();
	}
	});
}



/* END OF FILE */


/*
PeriodicalUpdater did not work because the parameters that are declared once are not reset on new requests.
Lots of modifications would have to be made on the server-side in order for this to work. 

PP_timer = new Ajax.PeriodicalUpdater('PP_temp','/' + PP_db + '/popper.mv?action=fetch', {
	method: 'get', parameters: '&fromtime='+PP_fromtime, frequency: (PP_refreshRate/1000), decay: 1, evalScripts: false, asynchronous: true,
	onFailure: function(PP_sendFailure){ alert('Popper has failed.'); },
	onSuccess: PP_processFetch
	
});
*/