/**
*	(c) www.fijiwebdesign.com
*/

// simple debug
function _debug(txt) {
	var el = document.getElementById('ajc_debug');
	if (!el) return false;
	
	el.value += txt+"\r\n";
}

function privateChat(recipient, roomid) {

	var windowName = "pm_" + recipient;
	var settings=
	"toolbar=no,location=no,directories=no,"+
	"status=no,menubar=no,scrollbars=no,"+
	"resizable=yes,width=" + pm_width + ",height=" + pm_height;
	var url = serverUrl + "index2.php?option=com_ajaxchat&task=pm&recipient=" + recipient;


	if (!pm_window[windowName]) {
		//_debug('new window:' + url);
		pm_window[windowName] = window.open(url, windowName, settings);
		pmwinTimer[windowName] = focusWin(windowName);
		return;
	}

	if (pm_window[windowName].location && !pm_window[windowName].closed) {
		//_debug('window exists:' + url);

		  if (roomid != pm_window[windowName].roomid) {
			//_debug('new session.')
			pm_window[windowName] = window.open(url, windowName, settings);
		  }
		  focusWin(windowName);

		} else {

		//_debug('old window reopen:' + url);
		pm_window[windowName] = window.open(url, windowName, settings);
		focusWin(windowName);
	}

}

var pmwin_interval = 1000; // wait before focusing window
var pmwinTimer = new Array();
var winErrors = 0;

// focus the pm window
function focusWin(name) {

	try {
		if (!pm_window[name].timer) pm_window[name].timer = 0;
		if (pm_window[name].timer > 3) {
				//alert("You may have a popup blocker, \r\n that is preventing you from viewing private chat messages... grrr!");
				return false;
			}
		pm_window[name].timer++;
	} catch(e) {
		// window has no properties yet?
		if (winErrors > 3) {
			//alert("You may have a popup blocker, \r\n that is preventing you from viewing private chat messages... grrr!");
			winErrors = 0; // rewind error counter
				return false;
		}
		winErrors++;
	}

	try {
		pm_window[name].focus();
	} catch (e) {
		
		setTimeout(function() { focusWin(name); }, pmwin_interval);
	}
}

// onload handlers
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
	window.onload = func;
  } else {
	window.onload = function() {
	  oldonload();
	  func();
	}
  }
}

// check the conneciton to the chat room
function checkConnection() {
	_debug('checking connection...');
	return new AJAXRequest("post", serverUrl + "index2.php", "option=" + encode('com_ajaxchat') + "&no_html=" + encode(1) + "&task=" + encode('status') , validateNewConnection);
}

no_polling = false; // polling flag
var no_connect = false; // global connection toggle
// create a new connection to chatroom
function newConnection() {

	connectCount++;

	_debug('new connection req');
	if (no_connect) return false; // currently negotiating connection
	else no_connect = true; // set flag for currently connecting

	// stop msgs polling
	no_polling = true;

	return new AJAXRequest("post", serverUrl + "index2.php", "option=" + encode('com_ajaxchat') + "&no_html=" + encode(1) + "&task=" + encode('connect') , validateNewConnection);
}

var connectCount = 0;
var newConnectionTimer; // setTimeout var
function validateNewConnection(myAJAX) {

	if (myAJAX.readyState == 4) {

	connectCount++;
	no_connect = false; // allow new connections

	if (myAJAX.status == 200) {
		var xml = myAJAX.responseXML;
		var text = myAJAX.responseText;
		_debug('Connection Response:'+text);

		// parse the xml
		if (xml) {
		  if (xml.documentElement) {

	var conn = xml.documentElement.getElementsByTagName('connection');
	var status = conn[0].getAttributeNode("status").nodeValue;


	if (status == 1) { // we have a connection, start checking for notifications
		no_polling = false;   // restart polling
		no_connect = false; // restart new connections
		showNotifications();
		return true;
	} else if (status == -9) { // User has been banned
		return false; // for now
	} else {
		negotiateConnection();
	}
			  }
			}
		}
	} 
}

function negotiateConnection() {
	_debug('Negotiating new connection...');
	if (connectCount > 3) { 
		_debug('Connection refused...');
		return false; // todo: we tried twice, so die.
	} else {
		_debug('Connection retry...');
		newConnection(); // retry connection
	}
}

// new notifications
var period_notify = 30000;
function showNotifications() { // get new notifications
_debug('new notes req');
if (no_polling) {
	return false;
}

return new AJAXRequest("post", serverUrl + "index2.php", "option=" + encode('com_ajaxchat') + "&no_html=" + encode(1) + "&task=" + encode('notify'),
							   displayNotifications);

}

var _setTimeout_notes = true;
var notesTimer; // global setTimeout for notes

// display notifications
function displayNotifications(myAJAX) {

		if (myAJAX.readyState == 4) {
		if (myAJAX.status == 200) {
			var xml = myAJAX.responseXML;
			var text = myAJAX.responseText;
			_debug('Notes Response:'+text);

			// parse the xml
			if (xml) {
			  if (xml.documentElement) {
				var notifications = xml.documentElement.getElementsByTagName("note");


				if (notifications.length > 0) {

					for (var i = 0; i < notifications.length; i++) {

						var roomid = notifications[i].getAttributeNode("roomid").nodeValue;
						var creator = notifications[i].getAttributeNode("creator").nodeValue;
						alertNotification(creator, roomid);

					}

				} else {
				  //validateResponse(xml); // validate connection
				}
			  }
			}
		} else {
			negotiateConnection();
			return false;
		}
		requestMode = false;
		if (_setTimeout_notes) {
			notesTimer = setTimeout('showNotifications()', period_notify);
		} else _setTimeout_notes = true;

	}

} // display notifications

var period_alert = 1000;
var alertsTimer = new Array();
function alertNotification(creator, roomid) {

	if (ajc_ignored[creator] == true) return false;
	
	// check to see if win exists
	var windowName = "pm_" + creator;
	try {
		if (pm_window[windowName].location && !pm_window[windowName].closed) {
		focusWin(windowName); // focus window
		return true;
	}
	} catch(e) { _debug(e) }

	var fn = function(creator, roomid) {
		var html = '<div style="border: 1px solid red;background: orange; font-size: 16px; padding: 8px; height: 50px;">'+creator+' sent you a chat message.<br /> <a href="'+serverUrl+'/index2.php?option=com_ajaxchat&task=pm&recipient='+creator+'" target="_blank" onclick="privateChat(\''+creator+'\', '+roomid+');closeAlert(\''+creator+'\');return false;">Chat</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" onclick="closeAlert(\''+creator+'\', true);return false;">Ignore</a></div>';
		showTip(document.body, 'alertNotification', html, 0, document.body.clientWidth-251, 250, false, 'pointer');
		document.getElementById('alertNotification').style.top = winScrollTop()+'px'; // move to top

		document.onscroll = function() {
			try {
			//alert(parseInt(document.body.scrollTop)+'px')
			document.getElementById('alertNotification').style.top = winScrollTop()+'px';
			//objDiv.scrollHeight;
			} catch(e) { _debug(e) }
		}
	}
	

	if (ajc_note_open == 1) {
		if (!tip_status) {
			tip_status = true;
			fn(creator, roomid);
			tip_status = false;
		} else {
			fn(creator, roomid);
		}
	} else {
		privateChat(creator, roomid);
	}
}

var ajc_ignored = new Array();
// close alert: add a cookie to track ignored users/save to db
function closeAlert(user, ignore) {
	if (ignore) {
		// confirm
		if (!confirm('Stop viewing messages from '+user+'?')) return false;
		else {
			// ignore the user for this session
			document.getElementById('alertNotification').style.display = 'none';
			ajc_ignored[user] = true;
			
		}
	} else {
		document.getElementById('alertNotification').style.display = 'none';
	}
}

// get client win scroll
function winScrollTop() {
	var pos = 0;
	if (document.documentElement && document.documentElement.scrollTop) {
		pos = document.documentElement.scrollTop; 
	} else if (document.body) {
		  pos = document.body.scrollTop; 
	} else if (window.innerHeight) {
		  pos = window.pageYOffset; 
	}
	return pos;
}

// start up our application
addLoadEvent(function() { 
	period_notify = 30000;
	// check to see if we have an existing connection
	checkConnection(); 
});

window.onunload = function() {

	for (win in pm_window) {
		try {
			//pm_window[win].close();
		} catch(e) { /* trap error */ }
	}
}

