/* Global functions of awesomness custom element lookup and create: adds .listen() for consistent cross browser event handling may wrapp in jbAnimate the elements at a later date. Jason Grima - jackbox.au@gmail.com */
if(!document.jbFunctions) {
	if(!document.jb$) { document.jb$ = function(e) { if(typeof e == 'object') { document.jbExtendElement(e); return e; } if(typeof e == 'string') { var el = document.getElementById(e); document.jbExtendElement(el); return el; } }; jb$ = document.jb$; };
	if(!document.unixTimeStamp) { 
		document.unixTimeStamp = function() { return new Date().getTime(); }; 
		unixTimeStamp = document.unixTimeStamp;
	}
	if(!document.jbAjax) {
		document.jbAjax = { version:"v1.3", sessionTimer: 90, 
			timeout: null,
			sessionTimeout: function() { if(Widgets.notify && jbAjax.sessionTimer == 90) { Widgets.notify_update("Your session will expire in "+jbAjax.sessionTimer+" seconds."); jbAjax.sessionTimer--; jbAjax.timeout = setTimeout(jbAjax.sessionTimeout, 1000); } else if(Widgets.notify_update) {  if(jbAjax.sessionTimer > 0)  { Widgets.notify_update("Your session will expire in "+jbAjax.sessionTimer+" seconds."); jbAjax.sessionTimer--; jbAjax.timeout = setTimeout(jbAjax.sessionTimeout, 1000); } else { if(Widgets.logout) { Widgets.notify_update("Your session has expired, logging out."); Widgets.logout("Your session has expired"); } } } },
			sessionPing: function() { return; if(jbAjax.timeout != null) { clearTimeout(jbAjax.timeout); } if(jbAjax.sessionTimer < 90) { jbAjax.sessionTimer = 90; if(Widgets.notify) { Widgets.notify(null,1); } } clearTimeout(jbAjax.timeout); /*jbAjax.timeout = setTimeout(jbAjax.sessionTimeout, 900000); jbAjax.timeout = setTimeout(jbAjax.sessionTimeout, 6000);*/ },
			x: 			function(){var idList = Array("Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP");var bFound = false;for (var i=0; i < idList.length && !bFound; i++) {try { var oDoc = new ActiveXObject(idList[i]);o2Store = idList[i];bFound = true; } catch (e) { } } if (!bFound){ try{ var oDoc = new XMLHttpRequest(); } catch (e) { alert("Failed to create XMLHttpRequest Object \n Original Exception: " + e.description); } } return oDoc; },
			serialize:	function(f){var g=function(n){return f.getElementsByTagName(n)};var nv=function(e){if(e.name)return encodeURIComponent(e.name)+'='+encodeURIComponent(e.getValue?e.getValue():e.value);else return ''};var i=collect(g('input'),function(i){if((i.type!='radio'&&i.type!='checkbox')||i.checked)return nv(i)});var s=collect(g('select'),nv);var t=collect(g('textarea'),nv);return i.concat(s).concat(t).join('&');},
			send:		function(u,f,m,a){if (u.indexOf("?") < 1){ u+="?"; } else { u+="&"; } u += ('ajax.timestamp=' + new Date().getTime()); var x=jbAjax.x(); x.open(m,u,true); x.onreadystatechange=function(){ if(x.readyState==4)f(x)}; if(m=='POST')x.setRequestHeader('Content-type','application/x-www-form-urlencoded'); x.send(a); jbAjax.sessionPing();},
			get:		function(url,func){jbAjax.send(url,func,'GET')},
			gets:		function(url){ var x=jbAjax.x();x.open('GET',url,false);x.send(null); jbAjax.sessionPing(); return x.responseText},
			getd:		function(url){ var x=jbAjax.x();x.open('GET',url,false);x.send(null); jbAjax.sessionPing(); return x.responseXML.documentElement},
			posts:		function(url,args){ var x=jbAjax.x();x.open('POST',url,false);x.setRequestHeader('Content-type','application/x-www-form-urlencoded');x.send(args); jbAjax.sessionPing(); return x.responseText},
			post:		function(url,func,args){jbAjax.send(url,func,'POST',args)},
			update:		function(url,elm){var e=jb$(elm);var f=function(r){e.innerHTML=r.responseText};jbAjax.get(url,f)},
			submit:		function(url,elm,frm){var e=jb$(elm);var f=function(r){e.innerHTML=r.responseText};jbAjax.post(url,f,jbAjax.serialize(frm))},
			xslt:		function(xml,xsl){ if(window.XSLTProcessor){ var processor = new XSLTProcessor(); processor.importStylesheet(xsl); try { var newFragment = processor.transformToFragment(xml, document); var html = new XMLSerializer().serializeToString(newFragment); } catch (e){ try { var html =  xml.transformNode(xsl); } catch  (e){ alert("Error performing XSL transformation \n"+e+""); } } return html; }else{ return xml.transformNode(xsl); } }
		}
		/*window.listen("load", function() {
			jbAjax.sessionPing();
		});*/
		jbAjax = document.jbAjax;
	}	
	if(!document.jbExtendElement) { 
		document.jbExtendElement = function(el) { 
			if(el == null) return null;
			el.listen = function(e, f) { if(this.addEventListener) { return this.addEventListener(e, f, false); } else if (this.attachEvent) {
				/* IE event handler for parity with other browsers */ 
				if(!this._eH) { this._eH = []; } if(!this._eH[e]) { this._eH[e] = []; } this._eH[e][this._eH[e].length+1] = f; 
				switch(e) { 
					case 'click': this.onclick = function() { for(var f in this._eH['click']) { this._eH['click'][f].call(this); } }; break; 
					case 'change': this.onchange = function() { for(var f in this._eH['change']) { this._eH['change'][f].call(this); } }; break; 
					case 'mouseover': this.onmouseover = function() { for(var f in this._eH['mouseover']) { this._eH['mouseover'][f].call(this); } }; break; 
					case 'mouseout': this.onmouseout = function() { for(var f in this._eH['mouseout']) { this._eH['mouseout'][f].call(this); } }; break; 
					case 'mousedown': this.onmousedown = function() { for(var f in this._eH['mousedown']) { this._eH['mousedown'][f].call(this); } }; break; 
					case 'mouseup': this.onmouseup = function() { for(var f in this._eH['mouseup']) { this._eH['mouseup'][f].call(this); } }; break; 
					case 'dblclick': this.ondblclick = function() { for(var f in this._eH['dblclick']) { this._eH['dblclick'][f].call(this); } }; break; 
					case 'keydown': this.onkeydown = function() { for(var f in this._eH['keydown']) { this._eH['keydown'][f].call(this); } }; break; 
					case 'keyup': this.onkeyup = function() { for(var f in this._eH['keyup']) { this._eH['keyup'][f].call(this); } }; break; 
					case 'keypress': this.onkeypress = function() { for(var f in this._eH['keypress']) { this._eH['keypress'][f].call(this); } }; break;
					case 'load': this.onload= function() { for(var f in this._eH['load']) { this._eH['load'][f].call(this); } }; break; 
					case 'unload': this.onunload = function() { for(var f in this._eH['unload']) { this._eH['unload'][f].call(this); } }; break; 
					case 'blur': this.onblur = function() { for(var f in this._eH['blur']) { this._eH['blur'][f].call(this); } }; break; 
					case 'focus': this.onfocus = function() { for(var f in this._eH['focus']) { this._eH['focus'][f].call(this); } }; break; 
				} } }; 
			el.unlisten = function(e, f) {
				if(this.removeEventListener) { return this.removeEventListener(e, f, false); } else if (this.detachEvent) {
					/* IE event handler for parity with other browsers */
					if(!this._eH) { return; } if(!this._eH[e]) { return } 
					for(var func in this._eH[e]) {
						if(this._eH[e][func] == f) {
							this._eH[e][func] = null;
							delete this._eH[e][func];
						}
					}
				}
			};
			el.cloneme = function() { var src = this; var dst = this.cloneNode(true); dst.onclick = src.onclick; dst.onmouseover = src.onmouseover; dst.onmouseout = src.onmouseout; dst.onmousedown = src.onmousedown; dst.onmouseup = src.onmouseup; };
			el.clearContent = function() { if(this.innerHTML) { this.innerHTML = ''; } };
			el.setContent = function(t) { this.innerHTML = t; };
			el.setRadius = function(r) { this.style.borderRadius = r; this.style.MozBorderRadius = r; this.style.WebKitBorderRadius = r; };
			el.setVisible = function(v) { this.style.opacity = v == 1 ? 1 : 0; this.style.filter = v == 1 ? "alpha(opacity = 100)" : "alpha(opacity = 0)"; this.style.display = v == 1 ? 'block' : 'none'; };
			el.setMargin = function(l,t,r,b) { if(l != null) this.style.marginLeft = l; if(t != null) this.style.marginTop = t; if(r != null) this.style.marginRight = r; if(b != null) this.style.marginBottom = b; };
			el.setSize = function(w,h) { if(w != null) this.style.width = w; if(h != null) this.style.height = h; };
			el.setPosition = function(x,y,w,h) { this.setPositionSize(x,y,w,h); };
			el.setPositionFixed = function(l,t,r,b) { this.style.position = 'fixed'; if(l != null) this.style.left = l; if(t != null) this.style.top = t; if(r != null) this.style.right = r; if(b != null) this.style.bottom = b; };
			el.setPositionAbsolute = function(l,t,r,b) { this.style.position = 'absolute'; if(l != null) this.style.left = l; if(t != null) this.style.top = t; if(r != null) this.style.right = r; if(b != null) this.style.bottom = b; };
			el.setPositionSize = function(x,y,w,h) { if(x != null) this.style.left = x; if(y != null) this.style.top = y; if(w != null) this.style.width = w; if(h != null) this.style.height = h; };
			el.fade = function(o,t,f) { Animate.fade(this, o, t, f); };	
			el.addClass = function(className) { if(this.className.indexOf(className) == -1) { this.className += ' ' + className; } };
			el.removeClass = function(className){ while(this.className.indexOf(className) != -1) { this.className = this.className.replace(" "+className,  ""); this.className = this.className.replace(className,  ""); } };
			el.hasClass = function(className) { if(this.className.indexOf(className) != -1) { return true; } else { return false; } };
			el.getOpacity = function() { if(!this.style) return 1; if(this.filters) { var opac = parseFloat(this.filters['alpha'].opacity / 100); } else { var opac = parseFloat(this.style.opacity); } if(isNaN(opac)) { return 0; } else { return opac; } },
			el.setOpacity = function(opac) { if(isNaN(opac)) { opac = 0; } if(!this.style) return 1; if(this.filters) { this.filters['alpha'].opacity = parseInt(opac *100); } else { this.style.opacity = opac; } }
			el.getParent = function() { if(this.parentNode) { return this.parentNode; } }
			el.setDefaultValue = function(val) { document.jbSetDefaultValue(this, val); }
			return el; 
		};
		jbExtendElement = document.jbExtendElement;
		jbExtend = document.jbExtendElement;
	}
	if(!window.listen) window.listen = function(e, f) { if(window.addEventListener) { window.addEventListener(e,f, false); } else if (window.attachEvent) { window.attachEvent('on'+e, f);  }  };
	if(!document.listen) document.listen = function(e, f) { if(document.addEventListener) { document.addEventListener(e,f, false); } else if (document.attachEvent) { document.attachEvent('on'+e, f); } };
	if(!window.unlisten) window.unlisten = function(e, f) { if(window.removeEventListener) { window.removeEventListener(e,f, false); } else if (window.detachEvent) { window.detachEvent('on'+e, f);  }  };
	if(!document.unlisten) document.unlisten = function(e, f) { if(document.removeEventListener) { document.removeEventListener(e,f, false); } else if (document.detachEvent) { document.detachEvent('on'+e, f); } };
	if(!document.UserSetting) { document.UserSetting = function(setting, value) { if(value != undefined) { return jbAjax.gets('/?userSettings='+setting+'&value='+value); } else { return jbAjax.gets('/?userSettings='+setting);  } }; userSetting = document.UserSetting; }
	if(!document.jbKSort) { document.jbKSort = function(in_array) { var keys = new Array(); var new_array = new Array(); var msg; for(k in in_array) { keys.push(k); } keys.sort(function (a, b){return (a > b) - (a < b);}); for (var i = 0; i < keys.length; i++) { new_array[keys[i]] = in_array[keys[i]]; msg += keys[i]; } return new_array; }; jbKSort = document.jbKSort; }
	if(!document.jbBind) { document.jbBind = function(f) { window.listen('load', f) }; jbBind = document.jbBind; }
	if(!document.jbTarget) { document.jbTarget = function(e) { if(e == null) e = window.event; return (e.srcElement) ? e.srcElement: e.target; }; jbTarget = document.jbTarget; };
	if(!document.jbCreate) { document.jbCreate = function(e) { var el = document.createElement(e); el = document.jbExtendElement(el); return el;}; jbCreate = document.jbCreate; };
	if(!document.jbToggleBlock) { document.jbToggleBlock = function(e) { jb$(e).style.display = jb$(e).style.display == 'none' ? 'block': 'none'; }; jbToggleBlock = document.jbToggleBlock; }
	if(!document.jbAlert) { document.jbAlert = function(msg) { if(Widgets.notify) { Widgets.notify(msg, 5000); } else { alert(msg); } }; jbAlert = document.jbAlert; }
	if(!document.jbCancel) { document.jbCancel = function(e) { if(!e) { e = window.event; e.returnValue = false; } else { e.preventDefault(); } }; jbCancel = document.jbCancel; jbCancelEvent = document.jbCancel; }
	if(!document.jbSetDefaultValue) { document.jbSetDefaultValue = function(el, val) { 
		el.defaultValue = val; 
		if(el.value == el.defaultValue) { el.addClass('default'); } 
			el.listen('focus', function() { if(el.value == el.defaultValue) { el.value = ''; el.removeClass('default'); } }); 
			el.listen('blur', function() { if(el.value == '') { el.addClass('default'); el.value = el.defaultValue; } }); 
			el.listen('change', function() { if(el.value == '') { el.addClass('default'); el.value = el.defaultValue; } }); }; 
		jbSetDefaultValue = document.jbSetDefaultValue; }

	var Animate = {
		fade: function(e, o, t, c) { /* fade opacity of an element from it's current to artbitrary new value */
			if(t < 50) { Animate.setOpac(e, o); c.call(e); } 
			e.animStyle = 'nonlinear'; 
			e.animCallBack = c; e.startOpac = Animate.getOpac(e); e.endOpac = o; e.deltaOpac = (e.startOpac - e.endOpac) / (t/50); Animate.fadeInterval(e);
			e.animSpeed = t;
		},
		fadeInterval: function (e) {
			if(e == null) return null;
			if(e.startOpac > e.endOpac) {
				Animate.setOpac(e, Animate.getOpac(e) - e.deltaOpac);
				if(e.animStyle == 'nonlinear') e.deltaOpac = (((Animate.getOpac(e) - e.endOpac) * 0.5) / e.animSpeed) * 500; 
				if((Animate.getOpac(e) - e.endOpac) < 0.01) {
					Animate.setOpac(e.endOpac);
					if(e.animCallBack) e.animCallBack();
				} else {
					setTimeout('Animate.fadeInterval(jb$("'+e.id+'"))', 90);
				}
			} else {
				Animate.setOpac(e, Animate.getOpac(e) + e.deltaOpac);
				if(e.animStyle == 'nonlinear') e.deltaOpac = Math.abs((((e.endOpac - Animate.getOpac(e)) * 0.5)  / e.animSpeed) * 500); 
				if((e.endOpac - Animate.getOpac(e)) < 0.01) {
					Animate.setOpac(e.endOpac);
					if(e.animCallBack) e.animCallBack();
				} else {
					setTimeout('Animate.fadeInterval(jb$("'+e.id+'"))', 90);
				}		
			}
		},
		getOpac: function(e) { if(!e.style) return 1; if(e.filters) { var opac = parseFloat(e.filters['alpha'].opacity / 100); } else { var opac = parseFloat(e.style.opacity); } if(isNaN(opac)) { return 0; } else { return opac; } },
		setOpac: function(e, opac) { if(isNaN(opac)) { opac = 0; } if(!e.style) return 1; if(e.filters) { e.filters['alpha'].opacity = parseInt(opac *100); } else { e.style.opacity = parseFloat(opac); } }
	}
	var jbJSONParse = (function () { var at, ch,  escapee = { '"':  '"', '\\': '\\', '/':  '/', b:    '\b', f:    '\f', n:    '\n', r:    '\r', t:    '\t' },  text, error = function (m) {throw { name: 'SyntaxError', message: m, at: at, text: text }; }, next = function (c) { if (c && c !== ch) { error("Expected '" + c + "' instead of '" + ch + "'"); } ch = text.charAt(at); at += 1; return ch; }, number = function () { var number, string = ''; if (ch === '-') { string = '-'; next('-'); } while (ch >= '0' && ch <= '9') { string += ch; next(); } if (ch === '.') { string += '.'; while (next() && ch >= '0' && ch <= '9') { string += ch; } } if (ch === 'e' || ch === 'E') { string += ch;next(); if (ch === '-' || ch === '+') { string += ch; next(); } while (ch >= '0' && ch <= '9') { string += ch; next(); } } number = +string; if (isNaN(number)) { error("Bad number"); } else { return number; } }, string = function () { var hex, i, string = '', uffff; if (ch === '"') { while (next()) { if (ch === '"') { next(); return string; } else if (ch === '\\') { next(); if (ch === 'u') { uffff = 0; for (i = 0; i < 4; i += 1) { hex = parseInt(next(), 16); if (!isFinite(hex)) { break; } uffff = uffff * 16 + hex; } string += String.fromCharCode(uffff); } else if (typeof escapee[ch] === 'string') { string += escapee[ch]; } else { break; } } else { string += ch; } } } error("Bad string"); }, white = function () { while (ch && ch <= ' ') { next(); } }, word = function () { switch (ch) { case 't': next('t');  next('r'); next('u'); next('e'); return true; case 'f': next('f'); next('a'); next('l'); next('s'); next('e'); return false; case 'n': next('n'); next('u'); next('l'); next('l'); return null; } error("Unexpected '" + ch + "'"); }, value,   array = function () { var array = []; if (ch === '[') { next('['); white(); if (ch === ']') { next(']'); return array;   } while (ch) { array.push(value()); white(); if (ch === ']') { next(']'); return array; } next(','); white(); } } error("Bad array"); }, object = function () { var key, object = {}; if (ch === '{') { next('{'); white(); if (ch === '}') { next('}'); return object;   } while (ch) { key = string(); white(); next(':'); if (Object.hasOwnProperty.call(object, key)) { error('Duplicate key "' + key + '"'); } object[key] = value(); white();if (ch === '}') { next('}'); return object; } next(','); white(); } } error("Bad object"); }; value = function () { white(); switch (ch) { case '{': return object(); case '[': return array(); case '"': return string(); case '-': return number(); default: return ch >= '0' && ch <= '9' ? number() : word(); } }; return function (source, reviver) { var result; text = source; at = 0; ch = ' '; result = value();  white();if (ch) { error("Syntax error"); } return typeof reviver === 'function' ? (function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); }({'': result}, '')) : result; }; }());
	document.jbFunctions = true;
}



// Fix scollable areas for touchscreen devices: Thanks http://chris-barr.com
function isTouchDevice(){ try{ document.createEvent("TouchEvent"); return true; }catch(e){ return false; } }
function touchScroll(id){
	if(isTouchDevice()){ //if touch events exist...
		var el=document.getElementById(id);
		var scrollStartPos=0;
		document.getElementById(id).addEventListener("touchstart", function(event) {
			scrollStartPos=this.scrollTop+event.touches[0].pageY;
			event.preventDefault();
		},false);
		document.getElementById(id).addEventListener("touchmove", function(event) {
			this.scrollTop=scrollStartPos-event.touches[0].pageY;
			event.preventDefault();
		},false);
	}
}



