//-- CopyRight 2009 Paul Davis ---------------------------------------------------------------------------

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

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.replace(/\(/, "") == responsefunction) { // then id or template, not function
					if (responsefunction.replace(/[\.]/, "") == responsefunction) // template
						fill(responsefunction, ajax.responseText);
					else // id 
						window.location = responsefunction;
				} else {
					try {
						eval(responsefunction);
					} catch (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 calendarDraw (day, month, year, fieldid) {
	monthnames = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
	var html = '\n\t<table class="cal" cellspacing="0">';
	// year
	html += '\
		<tr>\
			<td colspan="2" class="cal year"><a class="cal year" href="javascript:void(0)" onMouseDown="calendarDraw(' + day + ', ' + month + ', ' + (year - 1) + ', \'' + fieldid + '\');">&laquo;</a></td>\
			<td colspan="3" class="cal year">' + year + '</td>\
			<td colspan="2" class="cal year"><a class="cal year" href="javascript:void(0)" onMouseDown="calendarDraw(' + day + ', ' + month + ', ' + (year + 1) + ', \'' + fieldid + '\');">&raquo;</a></td>\
		</tr>';
	// month
	html += '\
		<tr>\
			<td colspan="2" class="cal month"><a class="cal month" href="javascript:void(0)" onMouseDown="calendarDraw(' + day + ', ' + ((month == 1) ? 12 : (month - 1)) + ', ' + ((month == 1) ? (year - 1) : year) + ', \'' + fieldid + '\');">&laquo;</a></td>\
			<td colspan="3" class="cal month">' + monthnames[month - 1] + '</td>\
			<td colspan="2" class="cal month"><a class="cal month" href="javascript:void(0)" onMouseDown="calendarDraw(' + day + ', ' + ((month == 12) ? 1 : (month + 1)) + ', ' + ((month == 12) ? (year + 1) : year) + ', \'' + fieldid + '\');">&raquo;</a></td>\
		</tr>';
	// day names
	var daynames = new Array('S', 'M', 'T', 'W', 'T', 'F', 'S');
	html += '\n\t\t<tr>';
	for (var i = 0; i < daynames.length; i++)
		html += '<td class="cal dayname">' + daynames[i] + '</td>';
	html += '</tr>';
	// days
	// previous month days
	var first = new Date(year, month - 1, 1);
	html += '<tr>';
	var weekstart = first.getDay();
	for(var i = weekstart; i > 0; i--)
		html += '<td class="cal day">&nbsp;</td>';
	// current month days
	var thismonth = new Date(year, month - 1, 1);
	var nextmonth = new Date(year, month, 1);
	var monthdays = Math.round((nextmonth.getTime() - thismonth.getTime()) / 86400000);
	var today = new Date();
	for(var i = 1; i <= monthdays; i++) {
		var todayclass = ((i == today.getDate()) && (month == (today.getMonth() + 1)) && (year == today.getFullYear())) ? ' today' : '';
		html += '<td class="cal day' + todayclass + '"><a href="javascript:void(0)" class="cal' + todayclass + '" onclick="calendarSet(\'' + i + '/' + month + '/' + year + '\', \'' + fieldid + '\')">' + i + '</a></td>';
		if ((i + weekstart - 1) % 7 == 6)
			html += '</tr><tr>';
	}
	// next month days
	var last = new Date(year, month - 1, monthdays);
	var weekfinish = last.getDay();
	for(var i = 6; i > weekfinish; i--)
		html += '<td class="cal day">&nbsp;</td>';
	html += '</tr>';
	// finish
	html += '</table>';
	document.getElementById('calendarpopup').innerHTML = html;
}

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

function calendarMakePopUp (fieldid, whereid, aclass) { 
	aclass = (aclass) ? aclass : '';
	var where = document.getElementById(whereid);
	var field = document.getElementById(fieldid);
	if (field && where) {
		calendarfieldid = fieldid;
		var caldiv = document.createElement('div');
		caldiv.id = 'calendarpopup';
		caldiv.className = aclass;
		document.body.appendChild(caldiv);
		caldiv.style.position = 'absolute';
		caldiv.style.left = findPos(where, 'x');
		caldiv.style.top  = findPos(where, 'y') + Math.max(where.clientHeight, where.offsetHeight);
		var today = new Date();
		calendarDraw(today.getDate(), today.getMonth() + 1, today.getFullYear(), fieldid);
	} 
}

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

function calendarPopUp (fieldid, whereid, aclass) {
	if (document.getElementById('calendarpopup'))
		destroy('calendarpopup');
	else
		setTimeout('calendarMakePopUp(\'' + fieldid + '\', \'' + aclass + '\', \'' + whereid + '\')', 100);
}

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

function calendarSet (datestring, fieldid) {
	var field = document.getElementById(fieldid);
	if (field)
		field.value = dateConform(datestring);
	destroy('calendarpopup');
}

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

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 dateConform (datestring) { 
	var future = (arguments.length > 1) ? arguments[1] : true; // automically adjust future dates to last century if 2 digit
	monthnames = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
	var now  = new Date();
	// sort out the datestring and get a date to work with
	datestring = datestring.replace(/[\.\/\-]/g, " ");
	var day   = getNumber(datestring, 1);
	var month = getNumber(datestring, 2);
	var year  = getNumber(datestring, 3);
	if (day == 0) {// no datestring
		day   = now.getDate();
		month = now.getMonth() + 1;
		year  = now.getFullYear();
	} else {
		// check month supplied as text
		var monthtext = datestring.match(/[a-zA-z]+/g);
		if (monthtext) {
			if (monthtext.length == 1) { 
				monthtext = monthtext[0];
				for (var i = 0; i < monthnames.length; i++) {
					var reg = new RegExp(monthnames[i], "i")
					if (monthtext.match(reg))
						month = i + 1;
				}
				year  = getNumber(datestring, 2);
			}
		} 
		if (month == 0)
			month = now.getMonth() + 1;
		if ((year < 1) || isNaN(year))
			year = now.getFullYear();
		while (month < 0){
			month += 12;
			year--;
		}
		while (month > 12){
			month -= 12;
			year++;
		}
	}
	if (year < 1)
		year = now.getFullYear();
	year = (year < 1000) ? (2000 + getNumber(year)) : year;
	while ((year > now.getFullYear()) && (!future)) 
		year -= 100;
	return day + '/' + month + '/' + year;
}

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

function destroy (id) {
	var el = document.getElementById(id);
	if (el) {
		var parent = el.parentNode;
		var a = parent.removeChild(el);
		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 el = document.getElementById(parentid);
	if (el) {
		while (el.firstChild) {
			if (el.firstChild.firstChild)
				empty(el.firstcChild);
			var temp = el.removeChild(el.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 menuClose(tomenu, alevel) {
	var a;
	var m;
	for (var i = menuBranches.length - 1; i >= alevel; i--) {
		if ((menuBranches[i] != tomenu) && (menuBranches[i] != '0') && (menuBranches[i] != 'none')) {
			m = document.getElementById(menuBranches[i]);
			m.style.visibilty = 'hidden';
			m.style.top = "-20000px";
			m.style.left = "-20000px";
			a = document.getElementById("link" + menuBranches[i].slice(4));
			if (a)
				a.className = a.className.replace(/ trail/g, "");
			menuBranches[i] = 'none';
		}
	}
}

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

function menuGo (frommenu, tomenu, alevel, horizontal, xoff, yoff) {
	if (alevel > 0)
		menuStartTimeOut = setTimeout('menuShow(\'' + frommenu + '\', \'' + tomenu + '\', ' + alevel + ', ' + horizontal + ', ' + xoff + ', ' + yoff + ')', 100);
	else
		menuStartTimeOut = setTimeout('menuShow(\'' + frommenu + '\', \'' + tomenu + '\', ' + alevel + ', ' + horizontal + ', ' + xoff + ', ' + yoff + ')', 200);
}

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

function menuStop () {
	clearTimeout(menuStartTimeOut);
}

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

function menuShow (frommenu, tomenu, alevel, horizontal, xoff, yoff) {
	menuClose(tomenu, alevel);
	clearTimeout(menuTimeOut);
	menuTimeOut = setTimeout('menuClose(\'0\', 0)', 60000);
	menuBranches[alevel] = tomenu;
	if (document.getElementById(tomenu)) {
		var a = document.getElementById(frommenu);
		a.className = a.className.replace(/ trail/g, "") + " trail";
		var b = document.getElementById(tomenu);
		var x = findPos(a, 'x');
		var y = findPos(a, 'y');
		var w = Math.max(a.clientWidth, a.offsetWidth);
		var h = Math.max(a.clientHeight, a.offsetHeight);
		var bw = b.offsetWidth;
		var bh = b.offsetHeight;
		var sx = window.innerWidth;
		var sy = window.innerHeight;
		var dx = 0;
		if (horizontal) {
			if (x + 2 + bw > sx)
				dx = -(x + 2 + bw - sx);						
		} else {
			if (x + w + 2 + bw > sx)
				dx = -(w + bw + (2 * xoff));
		}
		var dy = y;
		if (y + bh > sy)
			dy = sy - bh - 1;
		b.style.zIndex = 400;
		if (horizontal) {
			b.style.top = (y + h) + 'px';
			b.style.left = (x + dx) + 'px';
		} else {
			b.style.top = (dy + yoff) + 'px';
			b.style.left = (x + w + xoff + dx) + 'px';
		}
		if (bh > sy) {
			b.style.top = '1px';
			b.style.height = (sy - 2) + 'px';
		}	
		b.style.visibility = 'visible';
	}
}

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

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;
}

//--------------------------------------------------------------------------------------------------------
// globals -----------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------

var mousex = 0;
var mousey = 0;

var menuBranches = new Array();
menuBranches[0] = '0';
menuStartTimeOut = 0;
menuTimeOut = 0;

document.onclick = function() { 
	menuClose('0', 0); 
	if (document.getElementById('calendarpopup'))
		destroy('calendarpopup');
};
	