/* COPYRIGHT (C) Paul Davis 2009. All rights reserved. */
 
//--- Drag and drop vars  -----------------------------------------------------------------------------------------------

var mousex = null;
var mousey = null;

var dragelm = null;
var dragghost = null;
var dragcontainerid = null;
var dragdropclass = null;
var dragcommand = null;
var dragconstrain = "y";

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

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 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 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 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 destroy (id) {
	var elm = document.getElementById(id);
	if (elm) {
		var parent = elm.parentNode;
		var a = parent.removeChild(elm);
		delete a;
	}
}

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

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 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');
				last = c.childNodes[j];
			}
		}
	}
}

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

function copy  (container, template) {
	var c = el(container);
	var t = el(template);
	if (c && t) {
		var index = 0;
		for (var j = 0; j < c.childNodes.length; j++) {
			if (c.childNodes[j].id) {
				var i = getInteger(c.childNodes[j].id);
				index = Math.max(index, i);
				last = c.childNodes[j];
			}
		}
		index++;
		// this doesn't work properly: c.innerHTML += html; ... so a lot more mucking about is needed ...
		var wrapper = null; // first div inside template
		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 drag (event) {
	if (dragghost) {
		getMouseXY(event);
		if (dragconstrain == "y")
			dragghost.style.top  = (mousey - 10 - document.body.scrollTop) + 'px';
		else if (dragconstrain == "x")
			dragghost.style.left = (mousex - 10 - document.body.scrollLeft) + 'px';
		else {
			dragghost.style.top  = (mousey - 10 - document.body.scrollTop) + 'px';
			dragghost.style.left = (mousex - 10 - document.body.scrollLeft) + 'px';
		}
	}
	return false; // in IE this prevents cascading of events, thus text selection is disabled
}

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

function drop (event) {
	if (dragghost) {
		document.onmousemove = null;
		document.onmouseup = null;
		document.onmousedown = null;
		document.body.removeChild(dragghost);
		dragghost = null;
		getMouseXY(e);
		var container = document.getElementById(dragcontainerid);
		var descendants = container.getElementsByTagName('div');
		for(var i = 0; i < descendants.length; i++) {
			var target  = descendants[i];
			if (target.className == dragdropclass) {
				var ok = 0;
				if (dragconstrain == "y") {
					var targety = findPos(target, 'y');
					var targetheight = Math.max(target.clientHeight, target.offsetHeight);
					ok = ((mousey > targety) && (mousey < (targety + (targetheight / 2))));
				} else if (dragconstrain == "x") {
					var targetx = findPos(target, 'x');
					var targetwidth = Math.max(target.clientWidth, target.offsetWidth);
					if ((mousex > targetx) && (mousex < (targetx + (targetwidth / 2))))
						ok = 1;
					else if ((mousex >= (targetx + (targetwidth / 2))) && (mousex < (targetx + targetwidth)))
						ok = 2;
				} else {
					var targety = findPos(target, 'y');
					var targetheight = Math.max(target.clientHeight, target.offsetHeight);
					var targetx = findPos(target, 'x');
					var targetwidth = Math.max(target.clientWidth, target.offsetWidth);
					ok = ((mousey > targety) && (mousey < (targety + targetheight)));
					ok = ok && ((mousex > targetx) && (mousex < (targetx + targetwidth)));
				}
				if (ok) {
					var id = target.id;
					if (!isInId(id, dragelm.id)) {
						if (dragcommand == 'drop') {
							if (ok == 2)
								document.getElementById(dragcontainerid).insertBefore(dragelm, target.nextSibling);
							else
								document.getElementById(dragcontainerid).insertBefore(dragelm, target);
						} else
							cmd(dragcommand, id);
					}
					break;
				}
			}
		}
	}			
}
		
//-----------------------------------------------------------------------------------------------------------------------

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.firstcChild);
			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 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 grab (elm, containerid, classname, command, constrain) {
	if (typeof(elm) == 'string')
		elm = document.getElementById(elm);
	if (!elm)
		return false;
	// NOTE : page tree is default to save on render time
	dragcontainerid = containerid;
	var container = document.getElementById(dragcontainerid);
	if (!container)
		return false;
	dragconstrain = constrain;
	dragdropclass = classname;
	dragcommand = (command) ? command : 'dragCtree';
	dragelm = elm;
	dragghost = elm.cloneNode(true);
	dragghost.id = 'ghost' + dragcontainerid;
	dragghost.style.position = "absolute";
	dragghost.style.float = "none";
	dragghost.onmousedown = null;
	dragghost.onmouseover = null;
	dragghost.style.top  = findPos(elm, "y") + 'px';
	dragghost.style.left = findPos(elm, "x") + 'px';
	dragghost.style.opacity = 0.5;
	document.body.appendChild(dragghost);
	document.onmousedown = function () { return false; }; // prevents cascading of events, disabling text selection
	document.onmousemove = drag;
	document.onmouseup = drop;
}

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

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 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 quote (text) {
	return text.replace(/"/g, '&quot;');
}

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

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 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 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 submitFake (containerid, template, destinationid) {
	var f = document.getElementById(containerid);
	if (f) {
		var url = "";
		var err = "";
		var nodes = f.getElementsByTagName("*");	
		for (var i = 0; i < nodes.length; i++) {
			var nodetype = nodes[i].tagName.toLowerCase();
			if (nodetype == "input")
				nodetype = nodes[i].getAttribute("type");
			switch (nodetype.toLowerCase()) {
				case "text": case "hidden": case "textarea": case "password":
					err = validateInput(nodes[i]);
					var name = (nodes[i].name) ? nodes[i].name : nodes[i].id;
					url += "&" + name + "=" + escape(nodes[i].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
				ajax(url, template); 
			return true;
		}
	}
	return false;
}

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

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

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

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) {
					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_-]*$");
					if (!re.test(elm.value))
						err = "You have supplied an invalid email adress - please check your information";
				}
				if (req.indexOf("Required") > -1) {
					if (elm.value == "")
						err = "Some required fields are empty - please fill them.";
				}
				break;
		}
	}
	return err;
}

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


