/* COPYRIGHT (C) Paul Davis 2009. All rights reserved. */
 
//--------------------------------------------------------------------------------------------------------

function addCSS (arule) {
	if (!document.styleSheets[0])
		return false;
	var lastcss = document.styleSheets[document.styleSheets.length - 1];
	var cssrules = (lastcss["cssRules"]) ? lastcss["cssRules"].length : lastcss["rules"].length;
	lastcss.insertRule(arule, cssrules);
	return true;
}

//--------------------------------------------------------------------------------------------------------

function addOnLoad (func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload)
				oldonload(); 
			func();
		}
	}
}

//--------------------------------------------------------------------------------------------------------

function ajax (url, responsefunction) { // response function can be js code, template file name, or id
	var ajax = null;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		ajax = new XMLHttpRequest();
		if (ajax.overrideMimeType)
			ajax.overrideMimeType("text/xml");
	} else if (window.ActiveXObject) { // IE 
		try {
			ajax = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				ajax = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!ajax) {
		alert("Giving up :( Cannot create an XMLHTTP instance");
		return false;
	}
	var busy = document.getElementById("busy");
	ajax.onreadystatechange = function() { 
		if (ajax.readyState == 4) {
			if (ajax.status == 200) {
				if (responsefunction) {
					if (responsefunction.replace(/\(/, "") == responsefunction) { // then id or template, not function
						if (responsefunction.replace(/[\.]/, "") == responsefunction) // not template
							fill(responsefunction, ajax.responseText);
						else // id 
							window.location = responsefunction;
					} else {
						try {
							eval(responsefunction);
						} catch (e) {
							//console.log(e);
							alert("Error: ajax function called failed: " + responsefunction);
						}
					}
				}
			} else
				alert("Sorry. An error has occurred: " + ajax.status);
			if (busy)
				busy.style.display = "none";
			return true;
		}
	};
	var address = window.location.href;
	address = address.replace(/\/[^\/]*(\?|$).*/, "");
	var page = url.replace(/\?.*/, "");
	ajax.open("POST", address + "/" + page, true);
	ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	if (busy)
		busy.style.display = "block";
	var query = url.replace(/.*?\?/, "");
	ajax.send(query);			
}

//-------------------------------------------------------------------------------------------------------

function base64 (input) {
	var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var output = "";
	var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
	var i = 0;

	input = utf8(input);

	while (i < input.length) {

		chr1 = input.charCodeAt(i++);
		chr2 = input.charCodeAt(i++);
		chr3 = input.charCodeAt(i++);

		enc1 = chr1 >> 2;
		enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
		enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
		enc4 = chr3 & 63;

		if (isNaN(chr2)) {
			enc3 = enc4 = 64;
		} else if (isNaN(chr3)) {
			enc4 = 64;
		}

		output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);

	}

	return output;
}

//--------------------------------------------------------------------------------------------------------

function blank (parentid) { // blanks all input elements inside a particular element
	var elm = document.getElementById(parentid);
	if (elm) {
		var descendants = elm.getElementsByTagName('input');
		for (var i = 0; i < descendants.length; i++)
			controlSet (descendants[i].id, false, '', false);
		descendants = elm.getElementsByTagName('select');
		for (var i = 0; i < descendants.length; i++)
			controlSet (descendants[i].id, false, '', false);
		descendants = elm.getElementsByTagName('textarea');
		for (var i = 0; i < descendants.length; i++)
			controlSet (descendants[i].id, false, '', false);
	}
}

//--------------------------------------------------------------------------------------------------------

function cboxval (cb, cbhidden) {
	var re = new RegExp('(^|\,)' + cb.value + '($|\,)', "g"); 
	var cbval = document.getElementById(cbhidden); 
	cbval.value = cbval.value.replace(re, ''); 
	if (cb.checked)
		cbval.value = (cbval.value) ? cbval.value + "," + cb.value : cb.value;
}

//--------------------------------------------------------------------------------------------------------

function changeColour (value) {
	if (!document.styleSheets[0])
		return false;
	value = (value) ? value : "#0b3b6f";
	var result = 0;
	var cssrules = (document.styleSheets[0]["cssRules"]) ? "cssRules" : "rules";
	for (var sheet = 0; sheet < document.styleSheets.length; sheet++) {
		var css = document.styleSheets[sheet][cssrules];
		for (var rule = 0; rule < css.length; rule++) {
			if (css[rule].selectorText == ".colour") {
				document.styleSheets[sheet].deleteRule(rule);
				document.styleSheets[sheet].insertRule('.colour { background-color: ' + value + ' !important; }', 0);
				result++;
			} else if (css[rule].selectorText == ".textcolour") {
				document.styleSheets[sheet].deleteRule(rule);
				document.styleSheets[sheet].insertRule('.textcolour { color: ' + value + ' !important; }', 0);
				result++;
			}
			if (result >= 2)
				return true;
		}
	}
	return false;
}

//------------------------------------------------------------------------------------------------------

function copy  (container, template, index) { // copies innerHTML of div (not the div itself to a container)
	var c = el(container);
	var t = el(template);
	if (c && t) {
		if (!index) {
			index = 0;
			for (var j = 0; j < c.childNodes.length; j++) {
				if (c.childNodes[j].id) {
					var i = getInteger(c.childNodes[j].id.match(/[0-9]+$/));
					index = Math.max(index, i);
				}
			}
			index++;
		}
		// this doesn't work properly: c.innerHTML += html; ... so a lot more mucking about is needed ...
		var wrapper = null; // first div inside template is the "wrapper"
		for (var j = 0; j < t.childNodes.length; j++) {
			if (t.childNodes[j].nodeType == 1) {
				wrapper = t.childNodes[j];
				break;
			}
		}
		var n = document.createElement(wrapper.tagName);
		n.id = wrapper.id.replace(/\[\[INDEX\]\]/g, index);
		n.className = wrapper.className;
		n.innerHTML = wrapper.innerHTML.replace(/\[\[INDEX\]\]/g, index);
		c.appendChild(n);
		return index;
	}
	return -1;
}

//------------------------------------------------------------------------------------------------------

function destroy (id) {
	var elm = document.getElementById(id);
	if (elm) {
		var parent = elm.parentNode;
		var a = parent.removeChild(elm);
		delete a;
	}
}
	
//--------------------------------------------------------------------------------------------------------

function e (astring) {
	//if (console)
	//	console.log(astring);
}

//--------------------------------------------------------------------------------------------------------

function el (id) {
	if (document.getElementById(id))
		return document.getElementById(id);
	/*
	if (arguments.length == 1)
		e("ERROR - failed to find element " + id);
	*/
	return false;
}

//--------------------------------------------------------------------------------------------------------

function empty (parentid) { // empties an element of all other elements
	var elm = document.getElementById(parentid);
	if (elm) {
		while (elm.firstChild) {
			if (elm.firstChild.firstChild)
				empty(elm.firstChild);
			var temp = elm.removeChild(elm.firstChild);
			delete temp;
		}
	}
}

//--------------------------------------------------------------------------------------------------------

function fill (id, html) {
	var elm = document.getElementById(id);
	if (elm)
		elm.innerHTML = html;
}

//-------------------------------------------------------------------------------------------------------

function findPos (obj, xory) {
	var result = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			if (xory == 'x') result += obj.offsetLeft;
			else result += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if ((xory == 'x') && (obj.x)) result += obj.x;
	else if (obj.y) result += obj.y;
	return result;
}

//-------------------------------------------------------------------------------------------------------

function formType (id_elm) {
	if (typeof(id_elm) == "string") {
		f = el(id_elm);
		if (!f) {
			f = document.getElementsByName(id_elm);
			if (!f.length)
				f = document.getElementsByName("bit" + id_elm);
				if (!f.length)
					return false;
			f = f.item(0);
		}
	} else
		f = id_elm;
	switch (f.nodeName) {
		case "SELECT":		return "select-one";	break;
		case "TEXTAREA":	return "textarea";		break;
		case "SPAN":		return "fixed";			break;
		case "INPUT":
			switch (f.getAttribute("type")) {
				case "text":		return "input";		break;
				case "password":	return "password";	break;
				case "file":		return "file";		break;
				case "button":		return "submit";	break;
				case "checkbox":	return "checkbox";	break;
				case "radio":		return "radio";		break;
				case "hidden":		return (el(id_elm + "_select")) ? "selector" : "hidden"; break;
			}
			break;
	}
}

//--------------------------------------------------------------------------------------------------------

function getInteger (astring) {
	astring = String(astring);
	var count = (arguments.length > 1) ? arguments[1] - 1 : 0;
	var matches = astring.match(/[\-0-9]+/g);
	if (!matches || (count > matches.length))
		return 0;
	return Number(matches[count]);
}

//--------------------------------------------------------------------------------------------------------

function getMouseXY(event) { 
	if (!event) 
		event = window.event; // works on IE, but not NS (we rely on NS passing us the event)
	if (event) { 
		if (event.pageX || event.pageY) { // this doesn't work on IE6!! (works on FF,Moz,Opera7)
			mousex = event.pageX - document.body.scrollLeft;
			mousey = event.pageY;// - document.body.scrollTop;
		} else if (event.clientX || event.clientY) { // works on IE6,FF,Moz,Opera7
			mousex = event.clientX + document.body.scrollLeft;
			mousey = event.clientY; // + document.body.scrollTop;
		}  
	}
}

//--------------------------------------------------------------------------------------------------------

function getNumber (astring) {
	astring = String(astring);
	var count = (arguments.length > 1) ? arguments[1] - 1 : 0;
	var matches = astring.match(/[\-0-9\.]+/g);
	if (!matches || (count > matches.length))
		return 0;
	return Number(matches[count]);
}

//-------------------------------------------------------------------------------------------------------

function gtlt (astring) {
	astring = astring.replace(/\</g, "&lt;");
	return astring.replace(/\>/g, "&gt;");
}

//-------------------------------------------------------------------------------------------------------

function isInId (objid, containerid) {
	var obj = document.getElementById(objid);
	while (obj) {
		if (obj.id == containerid)
			return true;
		obj = obj.parentNode;
	}
	return false;
}

//-------------------------------------------------------------------------------------------------------

function json (value) { // makes string into json safe format
	if (!value)
		return "";
	value = value.replace(/[\\]/g, "\\\\");
	value = value.replace(/[\b]/g, "\\b");
	value = value.replace(/[\f]/g, "\\f");
	value = value.replace(/[\n]/g, "\\n");
	value = value.replace(/[\r]/g, "\\r");
	value = value.replace(/[\t]/g, "\\t");
	value = value.replace(/[\"]/g, "\\\"");
	return value;
}

//-------------------------------------------------------------------------------------------------------

function legalise (text) { // cleans up text for use as a HTML element id or name
	if (text) {
		var illegal = /[\`\s\~\!\@\#\$\%\^\&\*\)\(\-\=\+\.\,\<\>\?\/\|\\\[\]\{\}\"\']/g;
		return text.replace(illegal, '_');
	}
	return '';
}

//-------------------------------------------------------------------------------------------------------

function movables  (container) {
	var c = el(container);
	if (c) {
		for (var j = 0; j < c.childNodes.length; j++) {
			if (c.childNodes[j].nodeType == 1) {
				c.childNodes[j].innerHTML = c.childNodes[j].innerHTML.replace(/class\=\"move hide/, 'class="move');
			}
		}
	}
}

//--------------------------------------------------------------------------------------------------------

function numberFormat (value, decimals, precision) {
	var digits = "0000000000";
	if (value == 0) // logs won't work
		return "0" + ((decimals) ? "." + digits.slice(0, decimals) : "");
	var power = Math.floor(Math.log(value * 1.00000000001) / Math.log(10));
	digits = String(Math.round(value / Math.pow(10, (power - (precision - 1))))) + "0000000000";
	if (power < 0)
		return "0" + ((decimals) ? "." + digits.slice(0, decimals) : "");
	else if (power == 0)
		return digits.slice(0, 1) + ((decimals) ? "." + digits.slice(1, (decimals + 1)) : "");
	else {
		var wholepart = digits.slice(0, (power + 1));
		var whole = "";
		while (wholepart.length > 3) {
			whole = "," + wholepart.slice(-3) + whole;
			wholepart = wholepart.slice(0, -3);
		}
		whole = wholepart + whole;
		return whole + ((decimals) ? "." + digits.slice(power + 1, (decimals + power + 1)) : "");
	}
}

//-------------------------------------------------------------------------------------------------------

function passify (text) { // cleans up text for passing in html javascript calls built as strings, pass second argument true to convert to HTML
	text = text.replace(/\\/g, '\\\\');
	text = text.replace(/'/g, '\\\'');
	if ((arguments.length > 1) && arguments[1])
		text = quote(text);
	else
		text = text.replace(/"/g, '\\"');
	return text;
}

//-------------------------------------------------------------------------------------------------------

function preload (imagepaths) {
	if (imagepaths) {
		if (typeof(imagepaths) == "string")
			imagepaths = imagepaths.split(",");
		var imgs = new Array();
		for (var i = 0; i < imagepaths.length; i++) {
			imgs[i] = new Image();
			imgs[i].src = trim(imagepaths[i]);
		}
	}
}

//-------------------------------------------------------------------------------------------------------

function quote (text) {
	return text.replace(/"/g, '&quot;');
}

//-------------------------------------------------------------------------------------------------------

function replaceCSS (arule) {
	if (!document.styleSheets[0])
		return false;
	var bits = arule.split("{");
	var style = trim(bits[0], "\\s");
	var cssrules = (document.styleSheets[0]["cssRules"]) ? "cssRules" : "rules";
	for (var sheet = 0; sheet < document.styleSheets.length; sheet++) {
		var css = document.styleSheets[sheet][cssrules];
		for (var rule = 0; rule < css.length; rule++) {
			if (css[rule].selectorText == style) {
				document.styleSheets[sheet].deleteRule(rule);
				document.styleSheets[sheet].insertRule(arule, rule);
				return true;
			} 
		}
	}
	return addCSS(arule);
}

//-------------------------------------------------------------------------------------------------------

function showDiv (show, hide) {
	var elm = null;
	if (arguments.length > 1) { // hide
		for (var i = 1; i < arguments.length; i++) {
			var divs = arguments[i].split(",");
			for (var j = 0; j < divs.length; j++) {
				elm = document.getElementById(divs[j]);
				if (elm)
					elm.style.display = "none";
			}
		}
	}
	elm = document.getElementById(show);
	if (elm)
		elm.style.display = "block";
}

//--------------------------------------------------------------------------------------------------------

function submitFake (containerid, template, destinationid) {
	var f = document.getElementById(containerid);
	if (f) {
		var fields = ",";
		var url = "";
		var err = "";
		var nodes = f.getElementsByTagName("*");	
		for (var i = 0; ((i < nodes.length) && !err); i++) {
			var type = formType(nodes[i]);
			var name = nodes[i].getAttribute("name");
			if (name && type &&(fields.indexOf("," + name + ",") == -1)) {
				fields += name + ",";
				var value = "";
				err = validateInput(nodes[i]);
				switch (type.toLowerCase()) {
					case "input": case "textarea": case "hidden": case "textarea": case "password": case "select-one":
						value = nodes[i].value;
						break;
					case "radio": 
						var f = document.getElementsByName(name);
						for (var j = 0; j < f.length; j++) {
							if (f[j].checked)
								value = f[j].value;
						}
						break;
				}
				url += "&" + name + "=" + escape(value);
			}
		}
		if (err) {
			alert(err);
			return false;
		} else {
			url = ((template) ? template : "index.php") + "?" + url.slice(1);
			if (destinationid) // ajax fill
				ajax(url, destinationid);
			else // ajax reload
				window.location = url;
			return true;
		}
	}
	return false;
}

//--------------------------------------------------------------------------------------------------------

function submitForm (formname) {
	var f = document[formname];
	if (f) {
		regexsupport = false;
		if (window.RegExp) {
			var testre = new RegExp('a');
			if (testre.test('a'))
				regexsupport = true;
		}
		if (regexsupport) {
			var err = '';
			var re = new RegExp('^[a-zA-Z0-9][a-z\.A-Z0-9_-]*@[a-zA-Z0-9][a-z\.A-Z0-9_-]+[\.][a-z\.A-Z0-9_-]*$');
			for (var loop=0; loop < f.elements.length; loop++) {
				var el = f.elements[loop];
				var req = String(el.getAttribute('alt'));
				if (req.indexOf('Email') > -1) {
					if (!re.test(el.value))
						err = 'You have supplied an invalid email adress - please check your information';
				}
				if (req.indexOf('Required') > -1) {
					if (el.getAttribute('type') == 'checkbox') {
						var cbs = document.getElementsByName(el.name);
						var cberr = 'Some checkbox choices are required - please check them to proceed.';
						for (var i = 0; i < cbs.length; i++)
							cberr = (cbs[i].checked) ? '' : cberr;
						if (cberr)
							err = cberr;
					} else {
						if (el.value == '')
							err = 'Some required fields are empty - please fill them.';
					}
				}
			}
			if (err == '')
				f.submit();
			else
				alert(err);
		} else {
			f.submit();
		}
	}
	return false;
}

//--------------------------------------------------------------------------------------------------------

function trim(str, chars) {
    chars = chars || "\\s";
	str = str.replace(new RegExp("^[" + chars + "]+", "g"), "");
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

//--------------------------------------------------------------------------------------------------------

function utf8 (string) {
	string = string.replace(/\r\n/g,"\n");
	var utftext = "";

	for (var n = 0; n < string.length; n++) {

		var c = string.charCodeAt(n);

		if (c < 128) {
			utftext += String.fromCharCode(c);
		}
		else if((c > 127) && (c < 2048)) {
			utftext += String.fromCharCode((c >> 6) | 192);
			utftext += String.fromCharCode((c & 63) | 128);
		}
		else {
			utftext += String.fromCharCode((c >> 12) | 224);
			utftext += String.fromCharCode(((c >> 6) & 63) | 128);
			utftext += String.fromCharCode((c & 63) | 128);
		}

	}

	return utftext;
}

//--------------------------------------------------------------------------------------------------------

function validateInput (elm) {
	var err = "";
	if (elm) {
		var type = elm.tagName.toLowerCase();
		if (type == "input")
			type = elm.getAttribute("type");
		switch (type.toLowerCase()) {
			case "text": case "hidden": case "textarea": case "password":
				var req = String(elm.getAttribute("alt"));
				if (req.indexOf("Ignore") > -1)
					return "";
				if (req.indexOf("Email") > -1) {					
					if (elm.value.match(/^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$/) == null) { //'
						err = "You have supplied an invalid email adress - please check your information";
						console.log(err);
					}
						
				}
				if (req.indexOf("Required") > -1) {
					if (elm.value == "")
						err = "Some required fields are empty - please fill them.";
				}
				break;
		}
	}
	return err;
}

//--------------------------------------------------------------------------------------------------------


