// Support for deleting records with Ajax

function v2(a) {
	var thermoff = true;
	if (a instanceof Array) { 
		try {
		while (flag = a.shift()) {
			switch (flag) {
			case 'J': 
				eval(a.shift()); 
				break;
			case 'JX': 
				if (eval(a.shift())) 
					eval(a.shift());
				else
					dumb = a.shift(); 
				break;
			case 'C': 
				var divname = a.shift();
				var elem = document.getElementById(divname);
				if (!elem) {
					dumb = a.shift();
					alert('Location not found on screen: ' + divname + " = " + dumb);
				} else {
					if (elem.id == "bar") thermoff = false;
					elem.innerHTML = a.shift();
				}
				break;
			case 'CX': 
				var divname = a.shift();
				var elem = document.getElementById(divname);
				if (!elem) {
					dumb = a.shift();
				} else {
					if (elem.id == "bar") thermoff = false;
					elem.innerHTML = a.shift();
				}
				break;
			}
		}
		} catch (err) {
			var txt = "The response from the server is invalid (" + err + ")\n";
			txt += a;
			alert(txt);
		}
	} else {
		alert("Problem in v2: " + a);
	}
	if (thermoff)
		document.getElementById('delay').innerHTML = "";
}

// Loading
function popdelay() {
	var mb = document.getElementById('delay');
	if (mb) 
		mb.innerHTML = "<div style='position: absolute; bottom: 50%; left: 50%;'>" +
						"<img src='" + iurl + "images/loading_loading.gif' border='0'/></div>";
	var msg = document.getElementById('message');
	if (msg)
		msg.innerHTML = ""; 
}
// Loading
function poptab0() {
	popdelay();
}
function poptab0off() {
	var mb = document.getElementById('delay');
	if (mb) 
		mb.innerHTML = "";
}
function ifpopdelay() {
	var mb = document.getElementById('delay');
	if (mb) 
		if (mb.innerHTML.length > 10) 
			return true;
	return false;
}
		
	


// Booking stuff
function makebooking(obj, e) {
	var targ
	if (!e) var e = window.event
	if (e.target) targ = e.target
	else if (e.srcElement) targ = e.srcElement
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode
	if (targ.tagName != "A" && targ.tagName != "IMG") {
		var divs = obj.getElementsByTagName('div');
		var catid = 0;
		var resid = 0;
		if (document.rc_form) {
			var rcform = document.rc_form;
			catix = rcform.rc_categories.selectedIndex;
			catid = rcform.rc_categories.options[catix].value;
			resid = rcform.rc_resources.value;
		}
		agent.call(surl + 'ajax_functions.php','makebooking3','v2',divs[0].id, catid, resid);
	}
}
function besave() {
	poptab0();
	var can = eval("document.be_form.save_cancel.value");
	if (can == "cancel") return bookingtable();
	var frm = document.be_form;
	if (frm.be_timestart.selectedIndex < 0 || frm.be_timeend.selectedIndex < 0) {
		alert("Booking not completed - no valid period selected");
		revalidateSave(document.be_form.save,"Save");
		poptab0off();
		return;
	}
	if (!frm.be_resourceid || frm.be_resourceid.value == "") {
		alert("Booking not completed - no resource selected");
		revalidateSave(document.be_form.save,"Save");
		poptab0off();
		return;
	}
	var parms = form_to_array("be_form");
	agent.call(surl + 'ajax_functions.php', 'besave', 'v2', parms);
}
function adddesc(divid,desc) {
	var obj = document.getElementById(divid);
	if (obj) {
		var txt = obj.innerHTML;
		obj.innerHTML = txt + desc;
	}
}
// To display the booking popup (at least)
function popupdesc(event,bookcnt) {
	if (bookcnt > 0 && popupenabled) {
		var x=event.clientX - 180;
		var y=event.clientY + 5;
		// Scroll in IE, check documentElement first
		var iescrollx = (document.documentElement)?document.documentElement.scrollLeft:document.body.scrollLeft;
		var iescrolly = (document.documentElement)?document.documentElement.scrollTop:document.body.scrollTop;
		var scrollx = (document.all)?iescrollx:window.pageXOffset;
		var scrolly = (document.all)?iescrolly:window.pageYOffset;
		// screenx = (document.all)?document.body.offsetWidth:window.innerWidth;
		// screeny = (document.all)?document.body.offsetHeight:window.innerHeight;
		// alert("x=" + x + " y=" + y + " scrollx=" + scrollx + " scrolly=" + scrolly + " screenx=" + screenx + " screeny=" + screeny);
		var mb = document.getElementById("bookcnt" + bookcnt);
		if (mb) {
			var adjustleft = scrollx + event.clientX - 180;
			var adjusttop = scrolly + event.clientY + 5;
			mb.style.left = adjustleft + "px";
			mb.style.top = adjusttop + "px";
			mb.style.position = "absolute";
			mb.style.visibility = "visible";
			mb.style.display = "block";
			mb.style.zIndex = 9999;
		} else {
			alert("Error: Not found bookcnt" + bookcnt);
		}
	}
}
function popuphide(bookcnt) {
	if (bookcnt > 0) {
		var mb = document.getElementById("bookcnt" + bookcnt);
		if (mb) {
			mb.style.visibility = "hidden";
			mb.style.display = "none";
		}
	}
}

var popupenabled = true;

// To display the booking popup (at least)
function popupgen(divid) {
	var elem = document.getElementById(divid);
	if (elem) {
		/***
		x=event.clientX - 180;
		y=event.clientY + 5;
		iescrollx = (document.documentElement)?document.documentElement.scrollLeft:document.body.scrollLeft;
		iescrolly = (document.documentElement)?document.documentElement.scrollTop:document.body.scrollTop;
		scrollx = (document.all)?iescrollx:window.pageXOffset;
		scrolly = (document.all)?iescrolly:window.pageYOffset;
		adjustleft = scrollx + event.clientX - 180;
		adjusttop = scrolly + event.clientY + 5;
		elem.style.left = adjustleft + "px";
		elem.style.top = adjusttop + "px";
		elem.style.position = "absolute";
		***/
		popupenabled = false;
		elem.style.visibility = "visible";
		elem.style.display = "block";
		elem.style.zIndex = 9999;
	} else {
		alert("Error: Screen location " + divid + " not found");
	}
}
function popdowngen(divid) {
	var elem = document.getElementById(divid);
	if (elem) {
		elem.style.visibility = "hidden";
		elem.style.display = "none";
		popupenabled = true;
	}
}

function updatedtend(obj) {
	poptab0();
	var periodid = obj.options[obj.selectedIndex].value;
	var frm = obj.form;
	var cv = frm.be_timeend.value;
	agent.call(surl + 'ajax_functions.php', 'updatedtend', 'v2', periodid, cv);
}
function bookedit(bookid) {
	poptab0();
	agent.call(surl + 'ajax_functions.php', 'bookedit', 'v2', bookid);
}
function pendingalert(bookid) {
	poptab0();
	agent.call(surl + 'ajax_functions.php', 'pendingalert', 'v2', bookid);
}
function pendingapprove(bookid) {
	poptab0();
	agent.call(surl + 'ajax_functions.php', 'pendingapprove', 'v2', bookid);
}
function pendingcancel(bookid) {
	poptab0();
	agent.call(surl + 'ajax_functions.php', 'pendingcancel', 'v2', bookid);
}
function bextender(obj) {
	var frm = obj.form;
	if (isNaN(parseInt(frm.be_resourceid.value))) {
		obj.checked = false;
		alert('Select a resource first');
		return;
	}
	if (obj.checked) {
		var dtout = frm.be_timeend.value;
		var ix = frm.be_resourceid.selectedIndex;
		var resid = frm.be_resourceid.options[ix].value;
		agent.call(surl + 'ajax_functions.php', 'extender', 'v2', resid, dtout);
		document.getElementById('extendbooking').style.display = 'block';
		return;
	}
	document.getElementById('extendbooking').style.display = 'none';
	document.getElementById('extendbooking').innerHTML = '';
	return;
}
function selectresources(catobj) {
	var frm = catobj.form;
	var ix = catobj.selectedIndex;
	var catid = catobj.options[ix].value;
	var timein = 0;
	var timeout = 0;
	if (frm.be_timestart.selectedIndex >= 0)
		timein = frm.be_timestart.options[frm.be_timestart.selectedIndex].value;
	if (frm.be_timeend.selectedIndex >= 0)
		timeout = frm.be_timeend.options[frm.be_timeend.selectedIndex].value;
	agent.call(surl + 'ajax_functions.php','selectresources','v2',catid, timein, timeout);
}
// 15/4/08 Can't find any reference to this function being called
function catselection() {
	poptab0();
	var frm = document.rc_form;
	var ix = frm.rc_categories.selectedIndex;
	var catid = frm.rc_categories.options[ix].value;
	agent.call(surl + 'ajax_functions.php','catselection','v2',catid, 0);
}
function resselection(resid) {
	poptab0();
	var frm = document.rc_form;
	frm.rc_resources.value = resid;
	var ix = frm.rc_categories.selectedIndex;
	var catid = frm.rc_categories.options[ix].value;
	agent.call(surl + 'ajax_functions.php','resselection','v2',catid,resid);
	agent.call(surl + 'ajax_functions.php','resourcedetail','v2',resid);
}
// A resource has been selected - we need to update the period list
function showimage(resobj) {
	var frm = resobj.form;
	var ix = resobj.selectedIndex;
	var resid = resobj.options[ix].value;
	agent.call(surl + 'ajax_functions.php','showimage','v2',resid);
	if (frm.be_timestart.selectedIndex < 0 || frm.be_timeend.selectedIndex < 0) {
		alert("Booking not completed - invalid periods");
		return bookingtable();
	}
	var timein = frm.be_timestart.options[frm.be_timestart.selectedIndex].value;
	var timeout = frm.be_timeend.options[frm.be_timeend.selectedIndex].value;
	agent.call(surl + 'ajax_functions.php','updateperiodselection','v2',resid,timein,timeout);
}

// Booking Options
// Booking Options
// Booking Options
function bosave() {
	poptab0();
	var frm = document.bo_form;
	var parms = form_to_array("bo_form");
	agent.call(surl + 'ajax_functions.php', 'bosave', 'v2', parms);
}

function optionchecked(cb, cntnotes) {
	var elem = document.getElementById("notes_" + cntnotes);
	if (elem) {
		if (cb.checked)
			elem.disabled = false;
		else {
			elem.value = "";
			elem.disabled = true;
		}
	}
}

function boedit(bkid) {
	poptab0();
	agent.call(surl + 'ajax_functions.php', 'boedit', 'v2', bkid);
}

// Repeat booking
// Repeat booking
// Repeat booking
function brepeater(obj) {
	var frm = obj.form;
	if (isNaN(parseInt(frm.be_resourceid.value))) {
		obj.checked = false;
		alert('Select a resource first');
		return;
	}
	if (obj.checked) {
		var dtin = frm.be_timestart.value;
		var repid = frm.be_repeatid.value;
		agent.call(surl + 'ajax_functions.php', 'repeater', 'v2', repid, dtin);
		document.getElementById('repeatbooking').style.display = 'block';
		return;
	}
	document.getElementById('repeatbooking').style.display = 'none';
	document.getElementById('repeatbooking').innerHTML = '';
	return;
}
// Pushed list repeats button
function listrepeats(repid, bkid) {
	agent.call(surl + 'ajax_functions.php', 'repeatform', 'v2', repid, bkid);
}
// The user selected a new frequency
function freshenddates(obj) {
	poptab0();
	var freq = obj.options[obj.selectedIndex].value;
	var repid = obj.form.rb_passingid.value;
	agent.call(surl + 'ajax_functions.php', 'freshenddates', 'v2', freq, repid); 
}
function rbsave() {
	poptab0();
	var can = eval("document.rb_form.save_cancel.value");
	if (can == "cancel") return bookingtable();
	var frm = document.rb_form;
	var parms = form_to_array("rb_form");
	agent.call(surl + 'ajax_functions.php', 'rbsave', 'v2', parms);
}
function bookdelete(bkid) {
	agent.call(surl + 'ajax_functions.php', 'bookdelete', 'v2', bkid);
}
// Push a calendar into this box
function endcalpop() {
	poptab0();
	agent.call(surl + 'ajax_functions.php','endcalpop','v2', 0);
}
function endcalpopback() {
	poptab0();
	agent.call(surl + 'ajax_functions.php','endcalpop','v2',-1);
}
function endcalpopforw() {
	poptab0();
	agent.call(surl + 'ajax_functions.php','endcalpop','v2',1);
}
function pickdaterb(szdate) {
	poptab0();
	// de = document.rb_form.rb_dateend;
	// de.options.length = 0;
	// de.options[0] = new Option(szdate,szdate);
	agent.call(surl + 'ajax_functions.php','endcalpopreset','v2', szdate);
}

// Adjust the date
function movetorb(timein) {
	poptab0();
	agent.call(surl + 'ajax_functions.php','bookingtable','v2',timein,0);
}


// Other generic stuff now...
var currenturl = unescape(window.location.href);
function delete_result(x) {
	if (x instanceof Array) {
		v2(x);
	} else {
		if (x.length == 0) {
			window.location = currenturl;
		} else {
			if (currenturl.indexOf("?") > 0)
				window.location = currenturl + '&infomsg=' + escape(x);
			else
				window.location = currenturl + '?infomsg=' + escape(x);
		}
	}
}
function delete_record(clazz, pid) {
	agent.call(surl + 'ajax_functions.php','delete_record','delete_result', clazz, pid);
}
function delete_record_check(clazz, pid, nurl) {
	if (confirm("Are you sure you want to delete this record?"))
		delete_record_go(clazz, pid, nurl);
}
function delete_record_go(clazz, pid, nurl) {
	var ix = currenturl.indexOf("?");
	if (ix > 0)
		currenturl = currenturl.substring(0,ix);
	if (nurl.length > 0) {
		if (nurl.substring(0,1) == '/')
			currenturl = nurl;
		else
			currenturl = currenturl + "?" + nurl;
	}
	agent.call(surl + 'ajax_functions.php','delete_record','delete_result', clazz, pid);
}

function stopspam() {
	var req = parseInt(document.forms[0].gm_spam1.value) + parseInt(document.forms[0].gm_spam2.value);
	var sol = parseInt(document.forms[0].gm_spam3.value);
	if (sol == req) 
		return true;
	alert("You must calculate the correct value to send this message");
	document.forms[0].gm_spam3.select();
	document.forms[0].gm_spam3.focus();
	return false;
}


function setdiv(o) {
	obj = document.getElementById(o);
	if (obj) {
		if (obj.style.display == 'none')
			obj.style.display = 'block';
		else
			obj.style.display = 'none';
	}
}
function popcal() {
	agent.call(surl + 'ajax_functions.php','popcal','v2','calendar');
}
function opdateforward() {
	agent.call(surl + 'ajax_functions.php','opdateforward','v2','calendar');
}
function opdateback() {
	agent.call(surl + 'ajax_functions.php','opdateback','v2','calendar');
}

function barresx(id,max) {
	for (var ix = 1; ix <= max; ix++) {
		if (ix == id)
			setdiv2('barres' + ix, 'block');
		else
			setdiv2('barres' + ix, 'none');
	}
}
function setdiv2(o,v) {
	var obj = document.getElementById(o);
	if (obj) 
		obj.style.display = v;
}

// Suggestion
function suggestion(phpfile) {
	agent.call(surl + 'ajax_functions.php','suggestion','v2',phpfile);
}
function sugsave(prefix) {
	poptab0();
	var can = eval("document.sug_form.save_cancel.value");
	if (can == "cancel") {
		agent.call(surl + 'ajax_functions.php', 'sugdefault', 'v2', 0);
	} else {
		var parms = form_to_array("sug_form");
		agent.call(surl + 'ajax_functions.php', 'sugsave', 'v2', parms);
	}
}

// Workout the screen size
var viewportwidth = 0;
var viewportheight = 0;
function setviewport() {
	if (typeof window.innerWidth != 'undefined') {
	  viewportwidth = window.innerWidth;
	  viewportheight = window.innerHeight;
 	} else if (screen) {
 		viewportwidth = screen.availWidth;
 		viewportheight = screen.availHeight;
	} else {
	  viewportwidth = document.body.clientWidth;
	  viewportheight = document.body.clientHeight;
	}
}

// Retrieves the dialog content from the server
function mydialog() {
	var afx = arguments[0];
	switch (arguments.length) {
	case 1:
		agent.call(surl + 'ajax_functions.php','mydialog','pop_dialog', afx);
		break;
	case 2:
		agent.call(surl + 'ajax_functions.php','mydialog','pop_dialog', afx, arguments[1]);
		break;
	case 3:
		agent.call(surl + 'ajax_functions.php','mydialog','pop_dialog', afx, arguments[1], arguments[2]);
		break;
	case 4:
		agent.call(surl + 'ajax_functions.php','mydialog','pop_dialog', afx, arguments[1], arguments[2], arguments[3]);
		break;
	}
}

// Dialog stuff
function pop_dialog(s) {
	pop_dialog_size(s, 500, 700);
}
function pop_dialog_size(s, height, width) {
	var dialog = document.getElementById('dialog');
	dialog.innerHTML = s;
	dialog.style.width = "auto";
	dialog.style.height = "auto";
	pop_dialog_show_size(height, width);
}
function pop_dialog_show() {
	pop_dialog_show_size(500, 700);
}
function pop_dialog_show_defaultsize() {
	pop_dialog_show_size(0, 0);
}
function pop_dialog_show_size(height, width) {
	var dialog = document.getElementById('dialog');
	dialog.className = 'dialog';
	dialog.style.display = 'block';
	if (viewportheight == 0 || msie)
		setviewport();
	// alert("ViewPort dim = " + viewportheight + " x " + viewportwidth);
	var shadecloth = document.getElementById('dialogshadecloth');
	if (shadecloth) {
		shadecloth.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=20) " +
			"progid:DXImageTransform.Microsoft.Blur(pixelRadius=5)";
		shadecloth.style.MozOpacity = 20/100;
		shadecloth.style.opacity = 20/100;
		
	} else {
		alert("ShadeCloth not found");
	}
	
	
	if (width > 0) 
		dialog.style.width = width + "px";
	if (height > 0) 
		dialog.style.height = height + "px";
		
	// alert("vpheight = " + viewportheight + " dialog.offsetHeight = " + dialog.offsetHeight);
	// alert("vpwidth = " + viewportwidth + " dialog.offsetWidth = " + dialog.offsetWidth);

	if (dialog.offsetHeight)
		dialog.style.top = Math.round((viewportheight - dialog.offsetHeight) / 2) + "px";
	else
		dialog.style.top = Math.round((viewportheight - height) / 2) + "px";
	
	if (dialog.offsetWidth)
		dialog.style.left = Math.round((viewportwidth - dialog.offsetWidth) / 2) + "px";
	else
		dialog.style.left = Math.round((viewportwidth - width) / 2) + "px";
		
	scrollTop();
}

function scrollTop() {
	window.scrollTo(0, 0); 
}
function scrollBottom() {
	if (document.body.scrollHeight) { 
	  window.scrollTo(0, document.body.scrollHeight); 
	} else if (screen.height) { // IE5 
	  window.scrollTo(0, screen.height); 
	}
}

function hide_dialog() {
	var shadecloth = document.getElementById('dialogshadecloth');
	shadecloth.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=100);";
	shadecloth.style.MozOpacity = 100;
	shadecloth.style.opacity = 100;
	var dialog = document.getElementById('dialog');
	dialog.innerHTML = "";
	dialog.style.display = 'none';
}

function preview(obj) {
	agent.call(surl + 'ajax_functions.php','preview', 'v2', obj.options[obj.selectedIndex].value);
}


// Utilities
// Utilities
// Utilities
function form_to_array(frmname) {
	var result = new Array();
	var frm = eval("document." + frmname);
	if (!frm) {
		result.push("ERR: Form " + frmname + " not found");
		return result;
	}
	for (ix = 0; ix < frm.elements.length; ix++) {
		var elem = frm.elements[ix];
		if (!elem.disabled) {
			result.push("~~" + elem.name);
			switch (elem.type) {
			case "select":
				result.push(elem.options[elem.selectedIndex].value);
				break;
			case "checkbox":
				if (elem.checked)
					result.push('true');
				else
					result.push('false');
				break;
			default:
				result.push(elem.value);
				break;
			}
		}
	}
	return result;
}

function go(url) {
	window.location = url;
}

function goReload() {
	window.location.reload();
}

// gm_forms validate and save button function
function validateSave(button, validfunc) {
	button.disabled = true;
	var buttonvalue = button.value;
	button.value = "Saving...";
	var frm = button.form;
	var vfix = validfunc.indexOf("(");
	var rawvf = null;
	if (validfunc && vfix) 
		rawvf = validfunc.substr(0,vfix);
	else
		rawvf = validfunc;
	var res = true;
	if (eval(rawvf))
		res = eval(validfunc);
	if (res)
		return frm.submit();
	button.value = buttonvalue;
	button.disabled = false;
	return;
}

function revalidateSave(button, txt) {
	button.value = txt;
	button.disabled = false;
	return;
}

// DateTime field support
function dtupdate(obj,dtcount) {
	var frm = obj.form;
	var ye = eval("frm.dt_ye_" + dtcount + ".value");
	if (ye.length == 2) {
		var year = parseInt(ye);
		if (year > 50)
			year += 1900;
		else
			year += 2000;
		ye = "" + year;
	} 
	var mo = eval("frm.dt_mo_" + dtcount + ".value");
	var da = eval("frm.dt_da_" + dtcount + ".value");
	var dttimeinc = null;
	if (eval("frm.dt_ho_" + dtcount)) {
		var numpattern=/^[0-9]*$/;
		var ho = eval("frm.dt_ho_" + dtcount + ".value");
		if (!numpattern.test(ho)) {
			alert("Invalid hours value");
			obj.focus();
			obj.select();
			return;
		}
		var mi = eval("frm.dt_mi_" + dtcount + ".value");
		if (!numpattern.test(mi)) { 
			alert("Invalid minutes value");
			obj.focus();
			obj.select();
			return;
		}
		dttimeinc = true;
	} else {
		dttimeinc = false;
	}
	var elem = document.getElementById("dtid_" + dtcount);
	if (elem) {
		if (dttimeinc)
			elem.value = ye + "/" + mo + "/" + da + " " + ho + ":" + mi;
		else
			elem.value = ye + "/" + mo + "/" + da;
	}
}

// ColourFields support
function updatesample(colourfield) {
	var fg = document.getElementById("cpfore" + colourfield);
	var bg = document.getElementById("cpback" + colourfield);
	var samp = document.getElementById("cpsamp" + colourfield);
	if (fg && bg && samp) {
		var fgval = fg.value;
		var bgval = bg.value;
		samp.innerHTML = "<p style='margin: 0px; padding: 3px; height: 16px; width: 80px; border: 1px solid black; color: #" + fgval + "; background-color: #" + bgval + ";'>Sample...</p>";
	}
}

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

function nullfunc() {
}
