try { // Mozilla doesn't like firing click() on A elements; define it as a method for A elements
	document.createElement('a');
	HTMLElement.prototype.click = function () {
		if (typeof this.onclick == 'function') {
			if (this.onclick({type: 'click'}) && this.href) 
				window.open(this.href, this.target ? this.target : '_self');
		} else if (this.href)
			window.open(this.href, this.target ? this.target : '_self');
	};
}
catch (e) {}

var communityRules = {
	'a.popHelp' : function (el) {
		el.onclick = function () {
			var w = window.open(this.href,this.target,'width=320,height=300,resizable=1,scrollbars=1');
			w.focus();
			return false;
		}
	},
	'.squareBox' : function (el) {
		var hd = el.getElementsByTagName("THEAD")[0].getElementsByTagName("A")[0];
		var _dom = document.all ? 3 : document.getElementById ? 1 : document.layers ? 2 : 0;
		el.onclick = function (e) {
			if (document.all) e = window.event;
			var sourceElement = (_dom==3) ? e.srcElement : e.target;
			if (hd) { // because we don't want a child link to also cause a page navigate
				 if (sourceElement.nodeName) {
					if (!((sourceElement.nodeName=="A") || (sourceElement.parentNode.nodeName=="A"))) {
						hd.click();
					}
				}
			}
		};
		el.onmouseover = function () {
			if (hd) el.style.cursor = 'pointer';
		};
		el.onmouseout = function () {
			if (hd) el.style.cursor = 'default';
		}
	},
	'#starlink a' : function (el) {
		el.onclick = function () {
			var APB = new ajaxPostback();
			APB.data = [['page',document.location.href],['random',Math.random() * 10000]]; // prevent caching
			APB.handler = "/jcommunity/doStarPage.asp";
			APB.postData(setPageStar,ajaxDebug);
			return false; // don't go to #
		}
	},
	'.popHelp' : function (el) {
		var myTitle = el.getAttribute("title");
		if (myTitle) el.setAttribute("title", "");
		el.onmouseover = function() {
 			if (myTitle) tb_balloonHelp(el,myTitle,"#F90","#FFE");
			return true;
		};
		el.onmouseout = function() {
			if (myTitle) tb_balloonHelp(el);
			return true;
		};
	},
	'.searchtext' : function (el) {
		el.onfocus = function () {
			if (el.value == "Search...") {
				el.value = "";
				el.style.color = "#000";
			}
		};
		el.onblur = function () {
			if (el.value.replace(/^\s*|\s*$/g, "") == "") {
				el.value = "Search...";
				el.style.color = "#ccc";
			}
		};
	},
	'.groupadmin td' : function (el) {
		el.onmouseover = function () {
			el.className = 'adminCellOver';
		};
		el.onmouseout = function () {
			el.className = '';
		}
	},
	'input.shortcut' : function (el) {
		el.onkeypress = function (e) { // Allow uppercase A-Z and 0-9 only
			var keycode;
			if (window.event) keycode = window.event.keyCode;
			else if (e) keycode = e.which;
			if ( ((keycode > 64) && (keycode < 91)) || ((keycode > 47) && (keycode < 58)) || ((keycode > 96) && (keycode < 123)) ) {
				// A-Za-z0-9
				return true;
			} else {
				return false;
			}
		};
		el.onchange = function () { // onblur doesn't seem to fire; use onchange instead.
			el.value = el.value.toUpperCase();
		};
	},
	'.expandOptionalDetails' : function (link) {
		link.onclick = function () {
			var img = link.getElementsByTagName("IMG")[0];
			var display = "none";
			if (img.src.indexOf("expand") > -1) {
				img.src = "images/contract.gif?" + Math.random();
				display = "block";
			} else {
				img.src = "images/expand.gif?" + Math.random();
				display = "none";
			}
			var trs = document.getElementsByTagName("TR");
			for (var i=0; i<trs.length; i++) {
				if (trs[i].className == "normallyHidden") {
					trs[i].style.display = display;
				}
			}
		}
	},
	'.expando_handle' : function (link) {
		link.onclick = function () {
			el = "target_" + link.getAttribute("id").replace(/handle_/i,"");
			div = $(el);
			if (parseInt(div.offsetHeight) == 0) {
				new Effect.BlindDown(el);
			} else {
				new Effect.BlindUp(el);
			}
			return false;
		}
	}
}
Behaviour.register(communityRules);

var validationRegister = {
	'.validateform input' : function (el) {
		var typ = el.getAttribute("type");
		var req = el.getAttribute("required");
		if (req) {
			var doc = document.createElement("SPAN");
			doc.className = "required";
			doc.innerHTML = "*";
			el.parentElement.appendChild(doc);
		}
		el.onblur = function() {
			if (req) {
				if (typ == "text") {
					// this is a bit of a hack; if there's a browse icon (etc) next to the field
					// then we need to skip that and put the text after it. When there is
					// no second sibling we need to just position it right after the field
					var ns1 = getNextSibling(el);
					var ns2 = getNextSibling(ns1);
					var ns = ns2 ? ns2 : ns1;
					if (el.value.replace(/^\s*|\s*$/g, "")=="") {
						el.style.backgroundColor = "#FFF5CF";
						if (ns) ns.innerHTML = "* Oops, you missed a required field";
					} else {
						el.style.backgroundColor = "#fff";
						if (ns) ns.innerHTML = "*";
					}
				}
			}
		};
		// aha, tricky. If the onclick event is already loaded with something (as the cancel button will be)
		// then don't overwrite the onclick event with this function; leave it as is.
		if (typeof el.onclick != 'function') el.onclick = function () {
			if (el.getAttribute("type")=="submit") {
				// could be better; should check only "this" form
				var l = document.getElementsByTagName("input");
				for (var i=0;i<l.length;i++) {
					if ((l[i].getAttribute("required")) && (l[i].getAttribute("type")=="text")) {
						if (l[i].value.replace(/^\s*|\s*$/g, "")=="") {
							alert("Oops, you missed a required field.\rYou need to fix it before you can continue.");
							return false;
						}
					}
				}
				var l = document.getElementsByTagName("textarea");
				for (var i=0;i<l.length;i++) {
					if (l[i].getAttribute("required")) {
						if (l[i].value.replace(/^\s*|\s*$/g, "")=="") {
							alert("Oops, you missed a required field.\rYou need to fix it before you can continue.");
							return false;
						}
					}
				}
				var l = document.getElementsByTagName("select");
				for (var i=0;i<l.length;i++) {
					if (l[i].getAttribute("required")) {
						if (l[i].value.replace(/^\s*|\s*$/g, "")=="") {
							alert("Oops, you missed a required field.\rYou need to fix it before you can continue.");
							return false;
						}
					}
				}
			}
		}
	},
	'.validateform textarea' : function (el) {
		var req = el.getAttribute("required");
		if (req) {
			var doc = document.createElement("SPAN");
			doc.className = "required";
			doc.innerHTML = "*";
			el.parentElement.appendChild(doc);
		}
		el.onblur = function() {
			if (req) {
				var ns = getNextSibling(el);
				if (el.value.replace(/^\s*|\s*$/g, "")=="") {
					el.style.backgroundColor = "#FFF5CF";
					if (ns) ns.innerHTML = "* Oops, you missed a required field";
				} else {
					el.style.backgroundColor = "#fff";
					if (ns) ns.innerHTML = "*";
				}
			}
		};
	},
	'.validateform select' : function (el) {
		var req = el.getAttribute("required");
		if (req) {
			var doc = document.createElement("SPAN");
			doc.className = "required";
			doc.innerHTML = "*";
			el.parentElement.appendChild(doc);
		}
		el.onblur = function() {
			if (req) {
				var ns = getNextSibling(el);
				if (el.value.replace(/^\s*|\s*$/g, "")=="") {
					el.style.backgroundColor = "#FFF5CF";
					if (ns) ns.innerHTML = "* Oops, you missed a required field";
				} else {
					el.style.backgroundColor = "#fff";
					if (ns) ns.innerHTML = "*";
				}
			}
		};
	},
	'.registerform .changeorg' : function (el) {
		el.onchange = function () {
			if (el[el.selectedIndex].value.replace(/^\s*|\s*$/g, "")!="") {
				document.forms['form1'].elements['txtOrganisationName'].value = el[el.selectedIndex].text;
			}
		}
	},
	'.validateform .changeorg' : function (el) {
		el.onchange = function () {
			if (el[el.selectedIndex].value.replace(/^\s*|\s*$/g, "")!="") {
				document.forms['form1'].elements['txtOrganisationName'].value = el[el.selectedIndex].text;
			}
		}
	}
}
Behaviour.register(validationRegister);

var generalBehaviours = {
	'.adv_search' : function(el) {
		var d = document.getElementById("adv_search");
		el.onclick = function() {
			if (d) {
				if (d.style.display == "block") {
					el.innerHTML = "Advanced";
					d.style.display = "none";
					addCookie("jcom", "adv_search", "n");
				} else {
					el.innerHTML = "Hide advanced";
					d.style.display = "block";
					addCookie("jcom", "adv_search", "y");
				}
			}
			return false;
		}
	},
	'.admintable th' : function (el) {
		el.onclick = function () {
			if (el.innerHTML=="Approve") {
				var d = document.getElementsByTagName("INPUT");
				for (var i=0;i<d.length;i++) if (d[i].getAttribute("name")=="approval") {
					d[i].checked=!d[i].checked;
					if (d[i].checked) {
						d[i].parentNode.parentNode.className  += ' selrow';
					} else {
						d[i].parentNode.parentNode.className = d[i].parentNode.parentNode.className.replace(/ selrow/,"");
					}
				}
			} else if (el.innerHTML=="Remove") {
				var d = document.getElementsByTagName("INPUT");
				for (var i=0;i<d.length;i++) if (d[i].getAttribute("name")=="reproval") {
					d[i].checked=!d[i].checked;
					if (d[i].checked) {
						d[i].parentNode.parentNode.className  += ' selrow';
					} else {
						d[i].parentNode.parentNode.className = d[i].parentNode.parentNode.className.replace(/ selrow/,"");
					}
				}
			}
		}
	},
	'.admintable input' : function (el) {
		el.onclick = function () {
			if (el.getAttribute("type") == "checkbox") {
				if (el.parentNode.parentNode.tagName=="TR") {
					if (el.checked) {
						el.parentNode.parentNode.className  += ' selrow';
					} else {
						el.parentNode.parentNode.className = el.parentNode.parentNode.className.replace(/ selrow/,"");
					}
				}
			}
		}
	},
	'.admincell td' : function (el) {
		el.title = "This item is visible to Toolbox Administrators only";
	},
	'.membership_type td' : function (el) {
		el.onclick = function () {
			var N = el.parentElement.getElementsByTagName("TD");
			for (var i=0;i<N.length;i++) N[i].className="";
			el.className = 'selected';
			document.forms['a'].Membership.value = el.getElementsByTagName("A")[0].href.split("#")[1];
		}
	}
}
Behaviour.register(generalBehaviours);

addLoadEvent(checkIncomingIM);

var m_boolDebug = false;
var imTimer, iTimeoutValue = 10;

var forevery = 5; // no. online users before adding addseconds to heartbeat wait
var addseconds = 10; // how many seconds of wait time to add per bracket
var limitat = 90; // maximum time between heatbeats (seconds)
var currentamount = 0; // the current refresh rate

function checkIncomingIM() {
	if (document.getElementById("imLink")) {
		var IM = new ajaxPostback();
		IM.data = [['operation','incoming'],['Limit','Y'],['random',Math.random() * 10000]]; // prevent caching
		IM.handler = "/toolbox/ajaxTIM.asp";
		IM.getData(setIncoming, ajaxDebug);
		clearTimeout(imTimer);
		if (iTimeoutValue > 0) imTimer = setTimeout("checkIncomingIM()", iTimeoutValue * 1000);
		IM = null;
	}
}

function setIncoming(obj) {
	if (obj) {
		if (typeof obj != 'object') obj = new Function("return "+obj)()
		var d = document.getElementById("imLink");
		if (obj.messages > 0) {
			d.innerHTML = d.innerHTML.replace(/pop_window\.png/,"incoming_message.gif").replace(/Show messenger/,"You\'ve got mail!");
		} else {
			d.innerHTML = d.innerHTML.replace(/incoming_message\.gif/,"pop_window.png").replace(/You\'ve got mail!/,"Show messenger");
		}
		amount = (addseconds * Math.round((obj.users / forevery) + 0.5));
		iTimeoutValue = ((amount > limitat) ? limitat : amount);
		if (m_boolDebug) {
			var dbgObj = document.getElementById("imDebug");
			if (!dbgObj) {
				var d = document.getElementById("imLink");
				dbgObj = document.createElement("DIV");
				dbgObj.setAttribute("id","imDebug");
				d.parentNode.appendChild(dbgObj);
			}
			dbgObj.innerHTML = "Messages: " + obj.messages + "<br/>Users: " + obj.users + "<br/>Delay: " + (iTimeoutValue * 1000);
		}
	}
}

function setPageStar(obj) {
	var d = document.getElementById("starlink");
	if (d && obj) {
		var h = d.innerHTML;
		if ((obj == "set") && (/star_grey.png/.test(h))) d.innerHTML = h.replace(/star_grey.png/,"star_yellow.png").replace(/Star /,"Unstar ");
		if ((obj == "unset") && (/star_yellow.png/.test(h))) d.innerHTML = h.replace(/star_yellow.png/,"star_grey.png").replace(/Unstar /,"Star ");
		Behaviour.apply(); // because innerHTML has updated the DOM
	}
}

function ajaxDebug(obj) {
	// throw the error in a new window so it's easy to read
	var errorWin = window.open();
	errorWin.document.clear();
	errorWin.document.write(obj);
	errorWin.document.close();
	errorWin.focus();
}

// Javascript cookie suck. In ASP you can assign a key/pair against a name.
// In javascript it's just name/value. So we have to set it like this.
function addCookie( sName, sKey, sValue ) {
    if ( sName.length < 1 ) return;
	var sCookieValue;
    if (document.cookie) {
		var i = document.cookie.indexOf(sName + "=");
		var j = document.cookie.indexOf(";", i);
        sCookieValue = document.cookie.substring(i + sName.length + 1, (j < 0) ? document.cookie.length : j);
		if (sCookieValue) {
			arCookie = sCookieValue.split("&");
			for (var l=0;l<arCookie.length;l++) {
				brCookie = arCookie[l].split("=");
				if (brCookie[0].toLowerCase==sName.toLowerCase()) arCookie[l] = "";
			}
			sCookieValue = arCookie.join("&");
		}
	}
	if (sCookieValue) {
		sCookieValue += "&";
		sCookieValue = sCookieValue.replace(/\&{2,}/g,"");
	}
	sCookieValue += sKey + "=" + escape(sValue);
    if ( 0 < sValue.length ) {
        var expDate = new Date();
        expDate.setTime( expDate.getTime() + 365*24*60*60*1000 ); // don't expire cookie; preserve it for ever. The room clears it.
        document.cookie = "" + sName + "=" + sCookieValue + "; expires=" + expDate.toGMTString() + "; path=/";
    } else {
        document.cookie = sName + "=";
    }
}

function community_presence(uid) {
	var pw = window.open("/toolbox/utlPresence.asp?Context=application&GroupKey=0","presWin_"+uid,"width=400,height=400,resizable=yes");
	pw.focus();
}

function togglePMForm() {
	el = $("utPMForm");
	if (el.style.display == "none") {
		el.style.display = "block";
		$("upPMLink").style.display = "none";
	} else {
		el.style.display = "none";
		$("upPMLink").style.display = "block";
	}
}