/******************************************************************************
* Author:   Andrew Connick
* Date:     09/08/06
******************************************************************************/


var tickerI = 0;
var tickerJ = 0;
var tickerFadein = true;

var selectedPicture="";

var chatCookie = "chatState";		// values: 0=no action, 1=open, 2=closed
var onlineUserTimeout = 30000;	// 30 seconds
var instantMsgTimeout = 5000;		// 5 seconds
var maxTimeout = 60000 * 30;		// 30 mins
var instantMsgTimer = null;

function dspTicker() {

	if (tickerJ == 0) {

		var html = "<p>"
		if (tickerLink[tickerI].length > 1) {
			html += "<a href='" + tickerLink[tickerI] + "'>";
			html += tickerTxt[tickerI] + "<img src='images/arrow.gif' /></a>";
		}
		else html += tickerTxt[tickerI];
		html += "<p>";
		setHtml("ticker", html);

		tickerI++;
		if (tickerI == tickerTxt.length) tickerI = 0;
		tickerFadein = true;
		setTimeout("dspTicker()", 100);
	}
	else if (tickerJ == 100) {
		tickerFadein = false;
		setTimeout("dspTicker()", 6000);
	}
	else setTimeout("dspTicker()", 50);

	if (tickerFadein) tickerJ = tickerJ + 5;
	else tickerJ = tickerJ - 10;
	setOpacity(document.getElementById("ticker"), tickerJ);
}

function showElm(id) { try { document.getElementById(id).style.display = ""; } catch(e) { } }
function showElm2(id) { try { document.getElementById(id).style.display = "block"; } catch(e) { } }
function showElm3(id) { try { document.getElementById(id).style.display = "inline"; } catch(e) { } }
function hideElm(id) { try { document.getElementById(id).style.display = "none"; } catch(e) { } }

function setHtml(id, html) { try { document.getElementById(id).innerHTML = html; } catch(e) { } }
function appendHtml(id, html) { try { document.getElementById(id).innerHTML += html; } catch(e) { } }

function dspPopup(target) {
	popup = window.open(baseUrl + target, "popUp", "width=850,height=580,top=200,status=yes,resizable=yes");
	popup.focus();
}

function isBlank(fld) {
	if (fld==null) return false;
	else if (fld.value == "") return true;
	else if (fld.value == " ") return true;
	else if (fld.value == "0") return true;
	else return false;
}

function vldEmail(e) {
	// define a regular expression to validate the email address
	var r = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
	if (r.test(e.value)) return true;                        // quit if the email is valid.
	// otherwise set an error.
	e.select();
	alert("Please enter a valid email address.");
	e.focus();
	return false;                                            // return false to halt processing.
}

function vldNumber(nbr) {
	// define a regular expression to validate number
	var r = /^\d*.?\d*$/;
	if (r.test(nbr.value)) return true;                      // quit if valid.
	// otherwise set an error.
	alert("This item must be numeric.");
	nbr.focus();
	nbr.select();
	return false;
}

// Validate the basic format of a date 
function vldDate(dte) {
	// define a regular expression to validate date
	if (dte.value=="") return true;                          // quit if blank.
	r = /^\d*\/\d*\/\d*$/;
	if (r.test(dte.value)) return true;                      // quit if valid.
	// otherwise set an error.
	alert("Please enter a valid date (format dd/mm/yy).");
	dte.focus();
	dte.select();
	return false;
}

// Validate text for special characters
function vldText(txt) {
	if (txt.value.indexOf('>')>=0 || 
			txt.value.indexOf('<')>=0 ||
			txt.value.indexOf('"')>=0 ||
			txt.value.indexOf('\'')>=0 ||
			txt.value.indexOf('\n')>=0 ||
			txt.value.indexOf('\r')>=0 ||
			txt.value.indexOf('\r\n')>=0 ||
			txt.value.indexOf('&')>=0) {
		txt.select();
		alert("Text contains an invalid character \n < >  quotes and newline \n are not allowed.");
		txt.focus();
		return false;
	}
	return true;
}

// Validate text for special characters (allow single quote & line feed)
function vldText2(txt) {
	if (txt.value.indexOf('>')>=0 || 
			txt.value.indexOf('<')>=0 ||
			txt.value.indexOf('"')>=0 ||
			txt.value.indexOf('&')>=0) {
		txt.select();
		alert("Text contains an invalid character \n < >  double quotes and newline \n are not allowed.");
		txt.focus();
		return false;
	}
	return true;
}

// Validate text for html codes
function vldText3(txt) {
	if (txt.value.indexOf('>')>=0 || 
			txt.value.indexOf('<')>=0) {
		txt.select();
		alert("Text contains an invalid character \n < and > are not allowed.");
		txt.focus();
		return false;
	}
	return true;
}

// Make sure the right hand column is shorter than centre 
function setRhColHeight() {
	var lh = document.getElementById("leftContent").offsetHeight;
	var rh = document.getElementById("rightContent").offsetHeight;
	lh += 100; 	// apply adjustment (added 19/5/9)
	var i = 10;
	while (rh > lh && i > 2) {
		hideElm("rh" + i);
		rh = document.getElementById("rightContent").offsetHeight;
		i--;
	}
}

/******************************************************************************
* function to create an ajax request object
* based on http://www.tizag.com/ajaxTutorial/ajaxbrowsersupport.php
*	revised, based on 
* http://stackoverflow.com/questions/415160/best-method-of-instantiating-an-xmlhttprequest-object
******************************************************************************/
function getAjaxRequest(){
	try { return new XMLHttpRequest();                    } catch(e) { }
	try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) { }
	try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) { }
	try { return new ActiveXObject('Msxml2.XMLHTTP');     } catch(e) { }
	try { return new ActiveXObject('Microsoft.XMLHTTP');  } catch(e) { }
	return null;
}

/******************************************************************************
* function to get data for a given url and insert the response into
* the document at the given id.
* It checks that the response contains the verification text.
******************************************************************************/
function addAjaxData(url, elementId, verify) {
	var ajaxRequest = getAjaxRequest();
	if (ajaxRequest!=null) {
		ajaxRequest.onreadystatechange = function() {
			if(ajaxRequest.readyState == 4) {
				var res = ajaxRequest.responseText;
				if (res.indexOf(verify) >= 0) setHtml(elementId, res);
			}
		}
		try {
			ajaxRequest.open("GET", url);
			ajaxRequest.send(null);
		} catch(e) { }
	}
}

/******************************************************************************
* function to validate the search form prior to submission.
******************************************************************************/
function vldSearchForm(frm) {
	if (frm.term.value=="Search") return false;
	else if (isBlank(frm.term)) return false;
	else return true;
}

/******************************************************************************
* function to check that something has been entered in 
* the comment form prior to submission.
******************************************************************************/
function prsAddComment(frm) {
	if (isBlank(frm.comment)) return false; // do not process form if no comment
	else return true;
}

/******************************************************************************
* function to show or hide an element
******************************************************************************/
function showOrHideElement(id) {
	var elm = document.getElementById(id);
	if (elm.style.display=="block") elm.style.display = "none";
	else elm.style.display = "block";
	return false;
}

/******************************************************************************
* function to validate an amount
******************************************************************************/
function vldAmount(a) {
	// define a regular expression to validate an amount
	var r = /^\d*[\.-]?\d{0,2}$/;
	if (r.test(a.value)) return true;                        // quit if the email is valid.
	// otherwise set an error.
	a.select();
	alert("Please enter a valid amount.");
	a.focus();
	return false;                                            // return false to halt processing.
}

/******************************************************************************
* function to get online users information
******************************************************************************/
function getOnlineInf(repeat) {
	var userListAjaxObj = getAjaxRequest();
	if (userListAjaxObj!=null) {
		userListAjaxObj.onreadystatechange = function() {
			try {
				if(userListAjaxObj.readyState == 4) {
					var res = userListAjaxObj.responseText;
					var txt = getXmlContent("userlist", res);
					if (txt != null) setHtml("onlineUserList", txt);
					txt = getXmlContent("usercount", res);
					if (txt != null) setHtml("onlineUserCount", txt);
					if (repeat && onlineUserTimeout<maxTimeout) setTimeout("getOnlineInf(true)", onlineUserTimeout *= 1.2);
				}
			} catch(e) { }
		}
		var url = 'onlineusers.jsp';
		try {
			userListAjaxObj.open("GET", url);
			userListAjaxObj.send(null); 
		} catch(e) { }
	}
}

/******************************************************************************
* function to get instant message information
******************************************************************************/
function getInstantMsgInf(txt) {

	// Clear any outstanding request
	if (instantMsgTimer!=null) {
		clearTimeout(instantMsgTimer);
		instantMsgTimer = null;
	}

	// Define ajax 
	var instantMsgAjaxObj = getAjaxRequest();
	if (instantMsgAjaxObj!=null) {
		instantMsgAjaxObj.onreadystatechange = function() {
			try {
				if(instantMsgAjaxObj.readyState == 4) {

					// Process the response
					var res = instantMsgAjaxObj.responseText;
					var msg = getXmlContent("messages", res);
					if (msg != null) {
						setHtml("instantMsgTxt", msg);
						document.getElementById("instantMsgWin").scrollTop = 2000;
						if (res.indexOf("<currentmessage>") > 0 && !chatWasClosed()) dspInstantMsg(true); 		// open chat window if loading a new page and new message exists
						if (document.getElementById("instantMsg").style.display=="block" && instantMsgTimeout<maxTimeout)
							instantMsgTimer = setTimeout("getInstantMsgInf(null)", instantMsgTimeout *= 1.2);
					}
				}
			} catch(e) { }
		}
		var url = "instantmessage.jsp"
		if (txt!=null) url = url + "?text=" + encodeURIComponent(txt);
		try {
			instantMsgAjaxObj.open("GET", url);
			instantMsgAjaxObj.send(null); 
		} catch(e) { }
	}
}

/******************************************************************************
* helper function to display instant message
* return true if already open
******************************************************************************/
function dspInstantMsg(showWelcome) {
	var elm = document.getElementById("instantMsg");
	if (elm!=null) {
		if (elm.style.display=="block") return true;
		elm.style.display = "block";
		if (showWelcome) showElm2("instantMsgWelcome");
		showElm2("footerPopup");
		document.getElementById("instantMsgInp").focus();
	}
	return false;
}

/******************************************************************************
* function to open instant message
******************************************************************************/
function openInstantMsg() {
	if (dspInstantMsg(true)) closeFooterPopup();		// close if already open
	else {
		// getOnlineInf(false);     removed 25/11/11
		onlineUserTimeout = 30000;	// 30 seconds
		instantMsgTimeout = 5000;		// 5 seconds
		getInstantMsgInf(null);
		document.cookie = chatCookie + "=1; path=/;";
	}
	return false;
}

/******************************************************************************
* function to close footer popup (instant message & user list)
******************************************************************************/
function closeFooterPopup() {
	hideElm('instantMsg');
	hideElm('footerPopup');
	document.cookie = chatCookie + "=2; path=/;";
	return false;
}

/******************************************************************************
* function to send an instant message
******************************************************************************/
function sendInstantMsg(elm, e) {
	if (enterPressed(e) && !isBlank(elm)) {
		hideElm("instantMsgWelcome");
		instantMsgTimeout = 5000;		// 5 seconds
		getInstantMsgInf(elm.value);
		var dte = new Date();
		var msg = "<p class='me'>" + dte.getHours() + ":" + dte.getMinutes();
		msg = msg + " <a>" + currentUserId + ":</a> " + elm.value + "</p>";
		appendHtml("instantMsgTxt", msg);
	}
}

/******************************************************************************
* function to clear text after enter
******************************************************************************/
function clearText(elm, e) {
	if (enterPressed(e)) elm.value = "";
}

/******************************************************************************
* function to determine if enter was pressed (for the given event)
******************************************************************************/
function enterPressed(e) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return false;
	if (keycode==13) return true;
	else return false;
}

/******************************************************************************
* function to determine if ipad/iphone/ipod
******************************************************************************/
function isIpad() {
	if(navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod') return true;
	else return false;
}

/******************************************************************************
* Drop down menu functions (see http://www.alistapart.com/articles/dropdowns )
******************************************************************************/
function setDropDown() {
	if (document.all && document.getElementById) {    // identifies IE
		var div = document.getElementById("menuUl");
		for (i=0; i<div.childNodes.length; i++) {
			var n = div.childNodes[i];
			if (n.nodeName == "LI") {
				n.onmouseover = function() { this.className = "over"; }
  			n.onmouseout = function() { this.className = ""; }
			}
		}
	}
}

/******************************************************************************
* function to set the opacity (0=transparent, 100=opaque)
******************************************************************************/
function setOpacity(obj, opacity) {
	if (opacity > 100) opacity = 100;	
	obj.style.filter = "alpha(opacity:" + opacity + ")";           // IE/Win
	obj.style.KHTMLOpacity = opacity/100;                          // Safari < 1.2, Konqueror
	obj.style.opacity = opacity/100;                               // modern browsers
}

/******************************************************************************
* function to get xml content for a given element name
* eg txt:  <something><p>this and that</p></something><other>zzz</other>
*    name: something
* returns: <p>this and that</p>
* if tags not found, it returns null
******************************************************************************/
function getXmlContent(name, txt) {
	var res = null;
	var strTag = "<" + name + ">";
	var str = txt.indexOf(strTag) + strTag.length;
	if (str >= 0) {
		var endTag = "</" + name + ">";
		var end = txt.indexOf(endTag);
		if (end > str) res = txt.slice(str, end);
	}
	return res;
}

/******************************************************************************
* function to determine if chat was open (on previous page)
******************************************************************************/
function chatWasOpen() {
	var pos = document.cookie.indexOf(chatCookie);
	if (pos != -1 && document.cookie.charAt(pos+10)=='1') return true;
	else return false;
}

/******************************************************************************
* function to determine if chat has been closed by user during this session
******************************************************************************/
function chatWasClosed() {
	var pos = document.cookie.indexOf(chatCookie);
	if (pos != -1 && document.cookie.charAt(pos+10)=='2') return true;
	else return false;
}

