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

var tickerMax = 30;
var tickerI = 0;
var tickerJ = tickerMax;
var tickerK = 0;
var tickerL = 0;
var selectedPicture="";
var textSize = 70;
var onlineUserTimeout = 30000;	// 30 seconds
var instantMsgTimeout = 5000;		// 5 seconds
var maxTimeout = 60000 * 30			// 30 mins

function dspTicker() {

	if (tickerJ==tickerMax) {
		var html = "<p id='tickerStrap'>" + tickerStrap[tickerK] + "</p>";
		html += "<a id='ticker' href='" + tickerLink[tickerI] + "'>";
		html += tickerTxt[tickerI] + "<img src='images/arrow.gif' /></a>"
		setHtml("tickerIn", html);
	}

	tickerJ--;
	document.getElementById("ticker").style.paddingTop = tickerJ + "px";
	if (tickerL==0) document.getElementById("tickerStrap").style.paddingTop = tickerJ + "px";

	if (tickerJ==0) {
		tickerI++;
		if (tickerI==tickerTxt.length) tickerI=0;
		tickerL++;
		if (tickerL==5) {
			tickerK++;
			if (tickerK==tickerStrap.length) tickerK=0;
			tickerL = 0;
		}
		tickerJ = tickerMax;
		setTimeout("dspTicker()", 5000);
	}
	else setTimeout("dspTicker()", 50);
}

function showDd(elm) { 
	for (i=0; i<elm.childNodes.length; i++) {
		n = elm.childNodes[i];
		if (n.className=="ddMenu") n.style.display = "block";
	}
}

function hideDd(elm) { 
	for (i=0; i<elm.childNodes.length; i++) {
		n = elm.childNodes[i];
		if (n.className=="ddMenu") n.style.display = "none";
	}
}

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--;
	}

	// Also set col height (removed 2/3/9)
//	var h = lh - rh + 20;
//	var h = lh - rh - 40;
//	if (h > 0) document.write("<div style='height: " + h + "px; '></div>");
}

// set the text size, using a value stored in cookie
function setTextSize() {
	var pos = document.cookie.indexOf("textSize=");
	if (pos != -1) {
		var start = pos + 9;
		var end = document.cookie.indexOf(";", start);
		if (end == -1) end = document.cookie.length;
		// convert the cookie value to a number, then use the global variable for textsize
		textSize = Number(document.cookie.substring(start, end));
	}
	document.body.style.fontSize = textSize + "%";                 // set the font size.
	// set side nav font size 
	if (document.getElementById("sideNav")!=null) {
		var textSize2 = .16 * textSize;            // set side nav to 11px
		if (textSize2 > 13.5) textSize2 = 13.5;		 // do not overflow box
//		alert("text size: " + textSize2 + "px");
		document.getElementById("sideNav").style.fontSize = textSize2 + "px";
	}
}

// process a user request to change the text size
function changeTextSize(direction) {
	if (direction=="0") textSize = 70;
	else if (direction=="+") textSize = textSize + 5;
	else { if (textSize > 20) textSize = textSize - 5; }
	expiryDate = new Date();
	expiryDate.setFullYear(2020);
	document.cookie = "textSize=" + textSize + "; path=/; expires=" + expiryDate.toGMTString();
	setTextSize();
	return false;
}

/******************************************************************************
* 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 url = 'onlineusers.jsp?mode=S';
	var elm = document.getElementById('onlineList'); 
	if (elm!=null && elm.style.display!="none") url = 'onlineusers.jsp';
	userListAjaxObj = addAjaxData(url, 'onlineInf', 'Online Users');
	if (repeat && onlineUserTimeout<maxTimeout) setTimeout("getOnlineInf(true)", onlineUserTimeout *= 1.2);
}

/******************************************************************************
* function to get instant message information
******************************************************************************/
function getInstantMsgInf(repeat, txt) {
	instantMsgAjaxObj = getAjaxRequest();
	if (instantMsgAjaxObj!=null) {
		instantMsgAjaxObj.onreadystatechange = function() {
			try {
				if(instantMsgAjaxObj.readyState == 4) {
					var res = instantMsgAjaxObj.responseText;
					var str = res.indexOf("<messages>") + 10;
					if (str >= 0) {																							// verifies response
						var end = res.indexOf("</messages>");
						if (end > str) setHtml("instantMsgTxt", res.slice(str, end));
						document.getElementById("instantMsgWin").scrollTop = 2000;
						if (res.indexOf("<currentmessage>") > 0 && !repeat) showElm3("instantMsgBlink");
						else hideElm("instantMsgBlink");
					}
				}
			} catch(e) { }
		}
		var url = "instantmessage.jsp"
		if (txt!=null) url = url + "?text=" + encodeURIComponent(txt);
		try {
			instantMsgAjaxObj.open("GET", url);
			instantMsgAjaxObj.send(null); 
		} catch(e) { }
	}

	if (repeat && document.getElementById("instantMsg").style.display=="block" && instantMsgTimeout<maxTimeout)
		setTimeout("getInstantMsgInf(true, null)", instantMsgTimeout *= 1.2);
}

/******************************************************************************
* function to open instant message
******************************************************************************/
function openInstantMsg() {
	var elm = document.getElementById("instantMsg");
	if (elm!=null) {
		if (elm.style.display=="block") return closeInstantMsg();		// close if already open
		elm.style.display = "block";
		showElm("onlineList");
		showElm("instantMsgWelcome");
		getOnlineInf(false);
		onlineUserTimeout = 30000;	// 30 seconds
		instantMsgTimeout = 5000;		// 5 seconds
		getInstantMsgInf(true, null);
		document.getElementById("instantMsgInp").focus();
	}
	return false;
}

/******************************************************************************
* function to close instant message
******************************************************************************/
function closeInstantMsg() {
	hideElm('instantMsg');
	hideElm('onlineList');
	return false;
}

/******************************************************************************
* function to send an instant message
******************************************************************************/
function sendInstantMsg(elm, e) {
	if (enterPressed(e) && !isBlank(elm)) {
		hideElm("instantMsgWelcome");
		getInstantMsgInf(false, elm.value);
		var dta = document.getElementById("instantMsgTxt").lastChild;
		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;
}
