// $Id: common.js,v 1.9 2008/11/22 16:24:53 cmanley Exp $


// xGetElementById, Copyright 2001-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
function xGetElementById(e) {
	if(typeof(e)=='string') {
		if(document.getElementById) e=document.getElementById(e);
		else if(document.all) e=document.all[e];
		else e=null;
	}
	return e;
}


// xAddEventListener, Copyright 2001-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
// http://cross-browser.com/x/lib/view.php?sym=xAddEventListener
function xAddEventListener(e,eT,eL,cap) {
	if(!(e=xGetElementById(e)))return;
	eT=eT.toLowerCase();
	if(e.addEventListener)e.addEventListener(eT,eL,cap||false);
	else if(e.attachEvent)e.attachEvent('on'+eT,eL);
	else e['on'+eT]=eL;
}



// xDef r1, Copyright 2001-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
function xDef() {
	for(var i=0; i<arguments.length; ++i){if(typeof(arguments[i])=='undefined') return false;}
	return true;
}


// xClientWidth r5, Copyright 2001-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
function xClientWidth() {
	var v=0,d=document,w=window;
	if((!d.compatMode || d.compatMode == 'CSS1Compat') && !w.opera && d.documentElement && d.documentElement.clientWidth)
		{v=d.documentElement.clientWidth;}
	else if(d.body && d.body.clientWidth)
		{v=d.body.clientWidth;}
	else if(xDef(w.innerWidth,w.innerHeight,d.height)) {
		v=w.innerWidth;
		if(d.height>w.innerHeight) v-=16;
	}
	return v;
}



function isScriptLoaded(src) {
	var scripts = document.getElementsByTagName('script');
	for (var i = 0; i < scripts.length; i++) {
		if (scripts[i].getAttribute('src') == src) {
			return true;
		}
	}
	return false;
}


function loadScript(src) {
	if (isScriptLoaded(src)) {
		return true;
	}
	if (document.createElement && document.childNodes) {
		var e = document.createElement('script');
		e.setAttribute('src', src);
		e.setAttribute('type', 'text/javascript');
		//e.setAttribute('defer', 'defer');
		var head = document.getElementsByTagName('head')[0];
		var scripts = document.getElementsByTagName('script');
		if (scripts.length) {
			head.insertBefore(e, scripts[0]);
		}
		else {
			document.getElementsByTagName('head')[0].appendChild(e);
		}
		return true;
	}
	return false;
}


function sprintf() { // From http://jan.moesen.nu/
	if (!arguments || arguments.length < 1 || !RegExp) {
		return;
	}
	var str = arguments[0];
	var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
	var a = b = [], numSubstitutions = 0, numMatches = 0;
	while (a = re.exec(str)) {
		var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
		var pPrecision = a[5], pType = a[6], rightPart = a[7];
		//alert(a + '\n' + [a[0], leftpart, pPad, pJustify, pMinLength, pPrecision);
		numMatches++;
		if (pType == '%') {
			subst = '%';
		}
		else {
			numSubstitutions++;
			if (numSubstitutions >= arguments.length) {
				alert('Error! Not enough function arguments (' + (arguments.length - 1) + ', excluding the string)\nfor the number of substitution parameters in string (' + numSubstitutions + ' so far).');
			}
			var param = arguments[numSubstitutions];
			var pad = '';
			if (pPad && pPad.substr(0,1) == "'") pad = leftpart.substr(1,1);
			else if (pPad) pad = pPad;
			var justifyRight = true;
			if (pJustify && pJustify === "-") justifyRight = false;
			var minLength = -1;
			if (pMinLength) minLength = parseInt(pMinLength);
			var precision = -1;
			if (pPrecision && pType == 'f') precision = parseInt(pPrecision.substring(1));
			var subst = param;
			if (pType == 'b') subst = parseInt(param).toString(2);
			else if (pType == 'c') subst = String.fromCharCode(parseInt(param));
			else if (pType == 'd') subst = parseInt(param) ? parseInt(param) : 0;
			else if (pType == 'u') subst = Math.abs(param);
			else if (pType == 'f') subst = (precision > -1) ? Math.round(parseFloat(param) * Math.pow(10, precision)) / Math.pow(10, precision): parseFloat(param);
			else if (pType == 'o') subst = parseInt(param).toString(8);
			else if (pType == 's') subst = param;
			else if (pType == 'x') subst = ('' + parseInt(param).toString(16)).toLowerCase();
			else if (pType == 'X') subst = ('' + parseInt(param).toString(16)).toUpperCase();
		}
		str = leftpart + subst + rightPart;
	}
	return str;
}


// Extend some classes.
if (!String.prototype.toHtml) {
	String.prototype.toHtml = function() {
		return this.replace(/[&<>]/g, function(c) { if (c == '&') return '&amp;'; if (c == '<') return '&lt;'; if (c == '>') return '&gt;'; });
	}
}
if (!String.prototype.trim) {
	String.prototype.trim = function() {
		return this.replace(/(^\s+|\s$)/g, '');
	}
}
if (!String.prototype.nl2br) {
	String.prototype.nl2br = function() {
		return this.replace(/\r?\n/g, '<br/>');
	}
}
if (!Date.prototype.getUnixTime) {
	Date.prototype.getUnixTime = function() {
		return Math.floor(this.valueOf() / 1000);
	}
}

// See http://www.crockford.com/javascript/inheritance.html
Function.prototype.addMethod = function (name, func) {
	this.prototype[name] = func;
	return this;
}
Function.addMethod('extend', function (parent) {
	var d = {}, p = (this.prototype = new parent());
	this.addMethod('callSuper', function (name) {
		if (!(name in d)) {
			d[name] = 0;
		}
		var f, r, t = d[name], v = parent.prototype;
		if (t) {
			while (t) {
				v = v.constructor.prototype;
				t -= 1;
			}
			f = v[name];
		} else {
			f = p[name];
			if (f == this[name]) {
				f = v[name];
			}
		}
		d[name] += 1;
		r = f.apply(this, Array.prototype.slice.apply(arguments, [1]));
		d[name] -= 1;
		return r;
	});
	return this;
});



function cookieCheck() {
	document.cookie = "cookiecheck=1";
	var enabled = (document.cookie.indexOf("cookiecheck") != -1);
	// Check if session cookie is present, if not then page was loaded from browser or google cache and is probably invalid.
	if (enabled) {
		if ((document.cookie.indexOf("PHPSESSID") == -1) && (window.location.hostname.toLowerCase().indexOf('bioreform.') >= 0)) {
			document.location.reload(true);
			return;
		}
	}
	else {
		var e = document.getElementById('cookies_disabled');
		if (e) {
			e.style.display = 'block';
		}
	}
}



/**
 * Returns the text value of an element.
 */
function domNodeTextValue(n) {
	if (n.nodeType == 3) { // text node
		return n.nodeValue;
	}
	var result = '';
	if (n.hasChildNodes()) {
		var nodes = n.childNodes;
		for (var i = 0; i < nodes.length; i++) {
			result += domNodeTextValue(nodes[i]);
		}
	}
	return result;
}


function setDocumentTitle() {
	var e = document.getElementById('pageTitle');
	if (e) {
		document.title += ' - ' + domNodeTextValue(e);
	}
}


// Things to call after document has loaded.
xAddEventListener(
	this,
	'load',
	function() {
		cookieCheck();
		setDocumentTitle();
	},
	false
);
