

function showDiv(id) {
	document.getElementById(id).style.display = "block";
}

function hideDiv(id) {
	document.getElementById(id).style.display = "none";
}

function showDate(what, link) {
	showDiv("add_transaction_date_"+what);
	hideDiv(link.id);
	return false;
}

function showAddCategoryPopoutBox(link) {
	var obj = document.getElementById('addCategoryPopoutBox');
	document.getElementById('category_form').style.display = 'block';
	document.getElementById('category_form_target').style.display = 'none';
	var pos = findPos(link);
	obj.style.left = pos[0] - 5;
	obj.style.top = pos[1] + 25;
	obj.style.display = 'inline';
	return false;
}

function hideAddCategoryPopout() {
	var obj = document.getElementById('addCategoryPopoutBox');
	if(obj) {
		obj.style.display = 'none';
	}
	return false;
}

var cat = '';

function addCategory(catt) {
	cat = document.getElementById(catt).value;
	document.getElementById('category_form').style.display = 'none';
	document.getElementById('category_form_target').style.display = 'block';
	document.getElementById('category_form_target').innerHTML = "Adding category. Please wait...";
	setTimeout('addCategory2()', 300);
}

function addCategory2() {
	var obj = document.getElementById('category0');
	var obj2 = document.getElementById('category4');
	var elOptNew = document.createElement('option');
	elOptNew.text = cat;
	elOptNew.value = 7;
	elOptNew.selected = "selected";

	var elOptNew2 = document.createElement('option');
	elOptNew2.text = cat;
	elOptNew2.value = 7;
	elOptNew2.selected = "selected";

	try {
		obj.add(elOptNew, null);
		obj2.add(elOptNew2, null);
/*
		var idx = obj.length-1;
		obj.selectedIndex = idx;
		obj2.selectedIndex = idx;*/
	} catch(ex) {
		try {
			obj.add(elOptNew); // IE only
		} catch(exx1) {
		}
		try {
			obj2.add(elOptNew2); // IE only
		} catch(exx2) {
		}
	}

	document.getElementById('category_form_target').innerHTML = "Successfully added category<br><a href='#' onclick='return showAddCategoryPopoutBox(this);'>Add another category</a><br><a href='#' onclick='return hideAddCategoryPopout()'>I've finished</a>";

	return false;
}

function checkCategory(id) {
	 if(id == "selectback") {
		document.getElementById("category").style.display = "inline";
		document.getElementById("category_input").style.display = "none";
		document.getElementById("category").selectedIndex = 0;
		return false;
	}
	var val = document.getElementById(id).value;
	if(val == "") {
		document.getElementById(id).style.display = "none";
		document.getElementById(id+"_input").style.display = "inline";
	}
	return false;
}

var glob_emailid = '';
var glob_httpRequest = 0;
var glob_tm = 0;

function editEmailPopout(emailid) {
	glob_emailid = emailid;
	var obj = document.getElementById('editEmailPopoutBox');
	var link = document.getElementById("email_edit_"+glob_emailid);
	var pos = findPos(link);
	obj.style.left = pos[0] - 5;
	obj.style.top = pos[1] + 25;
	obj.innerHTML = "Loading...";
	obj.style.display = 'inline';
	glob_tm = setTimeout("editEmailDo()", 400);
	return false;
}

function editEmailDo() {
	var obj = document.getElementById('editEmailPopoutBox');
	var emailid = glob_emailid;
	var link = document.getElementById("email_edit_"+emailid);
	var pos = findPos(link);

	if(glob_httpRequest) {
		glob_httpRequest = '';
	}
	glob_httpRequest 	= __createObj();
	var url 				= "/my_account.php?a=eedit&email_id=" +emailid;
	var resp 			= "";

	glob_httpRequest.open("GET", url, true);
	glob_httpRequest.send(null);

	glob_httpRequest.onreadystatechange = function() {
		if (glob_httpRequest.readyState == 4 || glob_httpRequest.readyState == "done")   {
				resp = glob_httpRequest.responseText;
				obj.innerHTML = "<div><a href='#' style='float:right;' onclick='return hideEditEmailPopout()'>Close</a><br></div>" + resp;
				obj.style.left = pos[0] - 175;
				if((obj.style.width + obj.style.left) > 770) {
					obj.style.left = pos[0] - 245;
				}

				glob_httpRequest = false;
		}
	}

	return false;
}

function hideEditEmailPopout() {
	var obj = document.getElementById('editEmailPopoutBox');
	if(obj) {
		obj.style.display = 'none';
	}
	return false;
}

var glob_cliid = '';
var glob_httpRequest = 0;
var glob_tm = 0;

function editCLI(cliid) {
	glob_cliid = cliid;
	var obj = document.getElementById('editCLIPopoutBox');
	var link = document.getElementById("cli_edit_"+glob_cliid);
	var pos = findPos(link);
	obj.style.left = pos[0] - 5;
	obj.style.top = pos[1] + 25;
	obj.innerHTML = "Loading...";
	obj.style.display = 'inline';
	glob_tm = setTimeout("editCLIDo()", 400);
	return false;
}

function editCLIDo() {
	var obj = document.getElementById('editCLIPopoutBox');
	var cliid = glob_cliid;
	var link = document.getElementById("cli_edit_"+cliid);
	var pos = findPos(link);

	if(glob_httpRequest) {
		glob_httpRequest = '';
	}
	glob_httpRequest 	= __createObj();
	var url 				= "/my_account.php?a=cedit&cliid=" +cliid;
	var resp 			= "";

	glob_httpRequest.open("GET", url, true);
	glob_httpRequest.send(null);

	glob_httpRequest.onreadystatechange = function() {
		if (glob_httpRequest.readyState == 4 || glob_httpRequest.readyState == "done")   {
				resp = glob_httpRequest.responseText;
				obj.innerHTML = "<div><a href='#' style='float:right;' onclick='return hideEditCLIPopout()'>Close</a><br></div>" + resp;
				obj.style.left = pos[0] - 175;
				if((obj.style.width + obj.style.left) > 770) {
					obj.style.left = pos[0] - 245;
				}

				glob_httpRequest = false;
		}
	}

	return false;
}

function hideEditCLIPopout() {
	var obj = document.getElementById('editCLIPopoutBox');
	if(obj) {
		obj.style.display = 'none';
	}
	return false;
}




























var user_timeout = 0;
var user_obj = 0;

function checkUserLength(id) {
	if(user_timeout) {
		clearTimeout(user_timeout);
	}
	user_timeout = setTimeout("checkUserLength2()", 300)
	user_obj 		= document.getElementById(id);
}

function checkUserLength2() {
	var obj 		= user_obj;
	var username= obj.value;
	var valid	= true;
	var id 		= obj.id;

	if(username.length == 0) {
		obj.className = "";
		document.getElementById(id+"_error").style.display = "none";
		return false;
	}

	if(username.length < 3) {
		valid = false;
	}

	if(!valid) {
		obj.className = "invalid_input";
		document.getElementById(id+"_error").style.display = "block";
		document.getElementById(id+"_error").innerHTML = "Username must be at least 3 characters long";
	} else {
		/*obj.className = "valid_input";*/
		obj.className = "";
		document.getElementById(id+"_error").style.display = "none";
	}

	return false;
}


function checkUsernameAvailability(id) {
	if(user_timeout) {
		clearTimeout(user_timeout);
	}
	user_timeout = setTimeout("checkUsernameAvailability2()", 300)
	user_obj 		= document.getElementById(id);
	return false;
}

function checkUsernameAvailability2() {
	var obj 		= user_obj;
	var username= obj.value;
	var valid	= true;
	var id 		= obj.id;

	if(username.length == 0) {
		obj.className = "";
		document.getElementById(id+"_error").style.display = "none";
		return false;
	}

	if(glob_httpRequest) {
		glob_httpRequest = '';
	}

	glob_httpRequest 	= __createObj();
	var url 				= "/my_account.php?a=check_username&username=" + username;
	var resp 			= "";

	glob_httpRequest.open("GET", url, true);
	glob_httpRequest.send(null);

	glob_httpRequest.onreadystatechange = function() {
		if (glob_httpRequest.readyState == 4 || glob_httpRequest.readyState == "done")   {
				resp = glob_httpRequest.responseText;

				if(resp == "NO") {
					obj.className = "invalid_input";
					document.getElementById(id+"_error").style.display = "block";
					document.getElementById(id+"_error").innerHTML = "Username not available";
				} else {
					obj.className = "valid_input";
					document.getElementById(id+"_error").style.display = "none";
				}


				glob_httpRequest = false;
		}
	}


	return false;
}


var pass_timeout 	= 0;
var pass_obj 		= 0;

function checkRepeatPassword(id) {
	if(pass_timeout) {
		clearTimeout(pass_timeout);
	}
	pass_timeout = setTimeout("checkRepeatPassword2()", 300)
	pass_obj 		= document.getElementById(id);
}

function checkRepeatPassword2() {
	var obj 		= pass_obj;
	var password= obj.value;
	var valid	= true;
	var id 		= obj.id;

	if(password.length == 0) {
		obj.className = "";
		document.getElementById(id+"_error").style.display = "none";
		return false;
	}

	if(password != document.getElementById('user_pass').value) {
		valid = false;
	}

	if(!valid) {
		obj.className = "invalid_input";
		document.getElementById(id+"_error").style.display = "block";
		document.getElementById(id+"_error").innerHTML = "Passwords must match";
	} else {
		obj.className = "valid_input";
		document.getElementById(id+"_error").style.display = "none";
	}

	return false;
}

function checkPasswordLength(id) {
	if(pass_timeout) {
		clearTimeout(pass_timeout);
	}
	pass_timeout = setTimeout("checkPasswordLength2()", 300)
	pass_obj 		= document.getElementById(id);
}

function checkPasswordLength2() {
	var obj 		= pass_obj;
	var password= obj.value;
	var valid	= true;
	var id 		= obj.id;

	if(password.length == 0) {
		obj.className = "";
		document.getElementById(id+"_error").style.display = "none";
		return false;
	}

	if(password.length < 4) {
		valid = false;
	}

	if(!valid) {
		obj.className = "invalid_input";
		document.getElementById(id+"_error").style.display = "block";
		document.getElementById(id+"_error").innerHTML = "Password must be at least 4 characters long";
	} else {
		obj.className = "valid_input";
		document.getElementById(id+"_error").style.display = "none";
	}

	return false;
}


function checkEmailAddress(id, length) {
	var obj 		= document.getElementById(id);
	var email 	= obj.value;

	if(length && email.length < 4) {
		return false;
	}

	var filter 	= /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var valid 	= true;
	if (!filter.test(email)) {
		valid = false;
	}

	if(!valid) {
		obj.className = "invalid_input";
	} else {
		obj.className = "valid_input";
	}

	return valid;
}


function hideAndShowById(hide, show) {
	if(document.getElementById(hide).style.display == 'none') {
		document.getElementById(hide).style.display = 'block';
		document.getElementById(show).innerHTML = "Hide" + document.getElementById(show).innerHTML.substring(4);
		/*document.getElementById(show).className = '';*/
	} else {
		document.getElementById(hide).style.display = 'none';
		document.getElementById(show).innerHTML = "Show" + document.getElementById(show).innerHTML.substring(4);
		/*document.getElementById(show).className = 'graph_hide';*/
	}

	return false;
}

function findPos(obj) {
	var curleft = 0;
	var curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}

function showAddCliPopout(link) {
	hideAddTransactionPopout();
	hideRAddTransactionPopout();
	hideEditTransactionPopout();
	hideAddEmailPopout();
	var link = document.getElementById(link);
	var obj = document.getElementById('addCliPopoutBox');
	var pos = findPos(link);
	obj.style.left = pos[0] - 5;
	obj.style.top = pos[1] + 25;
	obj.style.display = 'inline';
	return false;
}

function hideAddCliPopout() {
	var obj = document.getElementById('addCliPopoutBox');
	if(obj) {
		obj.style.display = 'none';
	}
	return false;
}


function showAddEmailPopout(link) {
	hideAddTransactionPopout();
	hideRAddTransactionPopout();
	hideEditTransactionPopout();
	hideAddCliPopout();
	var link = document.getElementById(link);
	var obj = document.getElementById('addEmailPopoutBox');
	var pos = findPos(link);
	obj.style.left = pos[0] - 5;
	obj.style.top = pos[1] + 25;
	obj.style.display = 'inline';
	return false;
}


function hideAddEmailPopout() {
	var obj = document.getElementById('addEmailPopoutBox');
	if(obj) {
		obj.style.display = 'none';
	}
	return false;
}


function showDatesPopout(link) {
	hideAddTransactionPopout();
	hideRAddTransactionPopout();
	hideEditTransactionPopout();
	var link = document.getElementById(link);
	var obj = document.getElementById('chooseDatesPopoutBox');
	var pos = findPos(link);
	obj.style.left = pos[0] - 5;
	obj.style.top = pos[1] + 25;
	obj.style.display = 'inline';
	return false;
}


function hideDatesPopout() {
	var obj = document.getElementById('chooseDatesPopoutBox');
	if(obj) {

		obj.style.display = 'none';
	}
	return false;
}

var glob_tid = '';
var glob_httpRequest = 0;
var glob_tm = 0;

function editTransaction(transaction_id) {
	glob_tid = transaction_id;
	hideAddTransactionPopout();
	hideRAddTransactionPopout();
	var obj = document.getElementById('editTransactionPopoutBox');
	var link = document.getElementById("trans_edit_"+transaction_id);
	var pos = findPos(link);
	obj.style.left = pos[0] - 5;
	obj.style.top = pos[1] + 25;
	obj.innerHTML = "Loading...";
	obj.style.display = 'inline';
	glob_tm = setTimeout("editTransactionDo()", 400);
	return false;
}

function editTransactionDo() {
	var obj = document.getElementById('editTransactionPopoutBox');
	var transaction_id = glob_tid;
	var link = document.getElementById("trans_edit_"+transaction_id);
	var pos = findPos(link);

	if(glob_httpRequest) {
		glob_httpRequest = '';
	}
	glob_httpRequest 	= __createObj();
	var url 				= "/a.php?act=edit&transaction_id=" + transaction_id;
	var resp 			= "";

	glob_httpRequest.open("GET", url, true);
	glob_httpRequest.send(null);

	glob_httpRequest.onreadystatechange = function() {
		if (glob_httpRequest.readyState == 4 || glob_httpRequest.readyState == "done")   {
				resp = glob_httpRequest.responseText;
				obj.innerHTML = "<div><a href='#' style='float:right;' onclick='return hideEditTransactionPopout()'>Close</a><br></div>" + resp;
				obj.style.left = pos[0] - 175;
				if((obj.style.width + obj.style.left) > 770) {
					obj.style.left = pos[0] - 245;
				}

				glob_httpRequest = false;
		}
	}

	return false;
}

function hideEditTransactionPopout() {
	var obj = document.getElementById('editTransactionPopoutBox');
	if(obj) {
		obj.style.display = 'none';
	}
	return false;
}













var glob_tid = '';
var glob_httpRequest = 0;
var glob_tm = 0;

function editRTransaction(transaction_id) {
	glob_tid = transaction_id;
	hideAddTransactionPopout();
	hideRAddTransactionPopout();
	var obj = document.getElementById('editTransactionPopoutBox');
	var link = document.getElementById("trans_redit_"+transaction_id);
	var pos = findPos(link);
	obj.style.left = pos[0] - 5;
	obj.style.top = pos[1] + 25;
	obj.innerHTML = "Loading...";
	obj.style.display = 'inline';
	glob_tm = setTimeout("editRTransactionDo()", 400);
	return false;
}

function editRTransactionDo() {
	var obj = document.getElementById('editTransactionPopoutBox');
	var transaction_id = glob_tid;
	var link = document.getElementById("trans_redit_"+transaction_id);
	var pos = findPos(link);

	if(glob_httpRequest) {
		glob_httpRequest = '';
	}
	glob_httpRequest 	= __createObj();
	var url 				= "/a.php?act=redit&transaction_id=" + transaction_id;
	var resp 			= "";

	glob_httpRequest.open("GET", url, true);
	glob_httpRequest.send(null);

	glob_httpRequest.onreadystatechange = function() {
		if (glob_httpRequest.readyState == 4 || glob_httpRequest.readyState == "done")   {
				resp = glob_httpRequest.responseText;
				obj.innerHTML = "<div><a href='#' style='float:right;' onclick='return hideEditTransactionPopout()'>Close</a><br></div>" + resp;
				obj.style.left = pos[0] - 175;
				if((obj.style.width + obj.style.left) > 770) {
					obj.style.left = pos[0] - 245;
				}

				glob_httpRequest = false;
		}
	}

	return false;
}

function hideEditRTransactionPopout() {
	var obj = document.getElementById('editTransactionPopoutBox');
	if(obj) {
		obj.style.display = 'none';
	}
	return false;
}




















function showRTab(what) {
	var li_obj = document.getElementById("r"+what + "_tab"+glob_tid);
	var content_obj = document.getElementById("tab_radd_transaction_" + what+glob_tid);

	li_obj.className = 'selected';
	content_obj.style.display = 'block';

	if(what == 'debit') {
		li_obj = document.getElementById("rcredit_tab"+glob_tid);
		content_obj = document.getElementById("tab_radd_transaction_credit"+glob_tid);
	} else {
		li_obj = document.getElementById("rdebit_tab"+glob_tid);
		content_obj = document.getElementById("tab_radd_transaction_debit"+glob_tid);
	}

	li_obj.className = '';
	content_obj.style.display = 'none';
	return false;
}


function showTab(what) {
	var li_obj = document.getElementById(what + "_tab"+glob_tid);
	var content_obj = document.getElementById("tab_add_transaction_" + what+glob_tid);

	li_obj.className = 'selected';
	content_obj.style.display = 'block';

	if(what == 'debit') {
		li_obj = document.getElementById("credit_tab"+glob_tid);
		content_obj = document.getElementById("tab_add_transaction_credit"+glob_tid);
	} else {
		li_obj = document.getElementById("debit_tab"+glob_tid);
		content_obj = document.getElementById("tab_add_transaction_debit"+glob_tid);
	}

	li_obj.className = '';
	content_obj.style.display = 'none';
	return false;
}


function showAddTransactionPopout(link) {
	glob_tid = '';
	hideRAddTransactionPopout();
	hideEditTransactionPopout();
	var link = document.getElementById(link);
	var obj = document.getElementById('addTransactionPopoutBox'+glob_tid);
	var pos = findPos(link);
	obj.style.left = pos[0] - 5;
	obj.style.top = pos[1] + 25;
	obj.style.display = 'inline';
	return false;
}

function hideAddTransactionPopout() {
	var obj = document.getElementById('addTransactionPopoutBox'+glob_tid);
	if(obj) {
		obj.style.display = 'none';
	}
	obj = document.getElementById('addTransactionPopoutBox');
	if(obj) {
		obj.style.display = 'none';
	}
	return false;
}

function showRAddTransactionPopout(link) {
	glob_tid = '';
	hideAddTransactionPopout();
	hideEditTransactionPopout();
	var link = document.getElementById(link);
	var obj = document.getElementById('raddTransactionPopoutBox'+glob_tid);
	var pos = findPos(link);
	obj.style.left = pos[0] - 5;
	obj.style.top = pos[1] + 25;
	obj.style.display = 'inline';
	return false;
}

function hideRAddTransactionPopout() {
	var obj = document.getElementById('raddTransactionPopoutBox'+glob_tid);
	if(obj) {
		obj.style.display = 'none';
	}
	obj = document.getElementById('raddTransactionPopoutBox');
	if(obj) {
		obj.style.display = 'none';
	}
	return false;
}

var items = Array();
var item_count = -1;

function showAutoComplete(litems, autocomplete_where, pos_where) {
	var a_obj = document.getElementById(autocomplete_where);
	var pos_obj = document.getElementById(pos_where);

	a_obj.innerHTML = "<div style='width: 200px;overflow:auto;max-height: 120px;'>";

	if(litems.length > 0) {
		for(i=0;i<litems.length;i++) {
			if(litems[i].length > 0) {
				a_obj.innerHTML += "<div class='autocomplete_option' onclick='autoCompleteSetSpentAt(\""+litems[i]+"\")'>" + litems[i] + "</div>";
			}
		}
		a_obj.innerHTML 		+= "</div>";
		a_obj.style.top 		= pos_obj.offsetTop + 20;
		a_obj.style.left 		= pos_obj.offsetLeft;
		a_obj.style.display 	= "inline";
	} else {
		a_obj.innerHTML = "No autocomplete matches";
	}
}

function MgOnKeyDown(event) {
  // we process the key. if it is a "normal" character, we only react after
  // a specified timeout (see below).
  // "event" only gets set if the handler was assigned from within
  // javascript, not in the html code. this is done in onFocus().

  if(!event) {
    event = window.event;
  }

  if(!event) {
  	return false;
  }

  alert(event.keyCode);
  ///////////////// DOWN //////////////////
  if(event.keyCode==40) {  // "down"
    item_count++;
    if(item_count >= items.length) {
    	item_count = 0;
    }
    alert(item_count);
  }

  ///////////////// UP //////////////////
  if(event.keyCode==38) {  // "up"
    if(!theMgBox.isOpenAndFilled) {
      theMgBox.timeoutReached(theMgBox.textboxid);
    } else {
      if(theMgBox.highlightedline!=null) {
        // change currently hightlighted line back to normal
        hBox.childNodes[0].childNodes[theMgBox.highlightedline].className="";
        // advance selection by one (upwards)
        theMgBox.highlightedline = (theMgBox.highlightedline==0) ?
                                   theMgBox.html_text_array.length-1
                                   : theMgBox.highlightedline-1;
      } else {
        theMgBox.highlightedline = theMgBox.html_text_array.length-1;
      }
      // highlight the new line
      hBox.childNodes[0].childNodes[theMgBox.highlightedline].className="mgHighlighted";
    }
  }

  ///////////////// ENTER //////////////////
  if(event.keyCode==13) {  // "ENTER"
  	alert("Dont press enter, Rar");
    if(!theMgBox.isOpenAndFilled) {
      theMgBox.timeoutReached(theMgBox.textboxid);
    } else {
      theMgBox.hideMgBox();

      // copy text into edit field
      var hTextbox = getElem("id",theMgBox.textboxid);
      hTextbox.value = theMgBox.raw_text_array[theMgBox.highlightedline];
      theMgBox.oldcontents = theMgBox.raw_text_array[theMgBox.highlightedline];

      // Remember author ID in hidden input field (if it exists)
      var hHiddenIdBox = getElem("id",theMgBox.textboxid+"_id");
      if( hHiddenIdBox != null ) {
        hHiddenIdBox.value = theMgBox.id_array[theMgBox.highlightedline];
      }

      // call hook if present
      if(typeof mgBox_onEnter_hook == 'function') {
        mgBox_onEnter_hook(theMgBox.textboxid);
      }
    }
  }
}










function autoCompleteSetSpentAt(what) {
	document.getElementById('spent_at').value = what;
	document.getElementById('autocomplete_at').style.display = 'none';
	document.getElementById('autocomplete_at').innerHTML = '';
}

var autocompletespentat_time;
var autocompletespentat_obj;

function autoCompleteSpentAt(obj) {
	var spentat = obj.value;
	if(spentat.length < 3) {
		return true;
	}
	clearTimeout(autocompletespentat_time);
	autocompletespentat_obj = obj;
	autocompletespentat_time = setTimeout("autoCompleteSpentAtDo()", 200);
}

function autoCompleteSpentAtDo() {
	if(httpRequest) {
		httpRequest = false;
		document.getElementById('autocomplete_at').style.display = 'none';
		document.getElementById('autocomplete_at').innerHTML = '';
	}
	var spentat			= autocompletespentat_obj.value;
	var httpRequest 	= __createObj();
	var url 				= "/autocomplete.php?a=spent_at&s=" + spentat;
	var resp 			= "";
	var a_obj			= document.getElementById('autocomplete_at');
	var i					= 0;

	httpRequest.open("GET", url, true);
	httpRequest.send(null);

	httpRequest.onreadystatechange = function() {
		if (httpRequest.readyState == 4 || httpRequest.readyState == "done")   {
				resp = httpRequest.responseText;
				var parts = resp.split("\n");
				items = parts;
				showAutoComplete(items, "autocomplete_at", "spent_at");
				httpRequest = false;
		}
	}
}


































function autoCompleteSetSpentOn(what) {
	document.getElementById('spent_on').value = what;
	document.getElementById('autocomplete_on').style.display = 'none';
	document.getElementById('autocomplete_on').innerHTML = '';
}

var autocompletespenton_time;
var autocompletespenton_obj;

function autoCompleteSpentOn(obj) {
	var spenton = obj.value;
	if(spenton.length < 3) {
		return true;
	}
	clearTimeout(autocompletespenton_time);
	autocompletespenton_obj = obj;
	autocompletespenton_time = setTimeout("autoCompleteSpentOnDo()", 200);
}

function autoCompleteSpentOnDo() {
	if(httpRequest) {
		httpRequest = false;
		document.getElementById('autocomplete_on').style.display = 'none';
		document.getElementById('autocomplete_on').innerHTML = '';
	}
	var spenton			= autocompletespenton_obj.value;
	var httpRequest 	= __createObj();
	var url 				= "/autocomplete.php?a=spent_on&s=" + spenton;
	var resp 			= "";
	var a_obj			= document.getElementById('autocomplete_on');
	var i					= 0;

	httpRequest.open("GET", url, true);
	httpRequest.send(null);

	httpRequest.onreadystatechange = function() {
		if (httpRequest.readyState == 4 || httpRequest.readyState == "done")   {
				resp = httpRequest.responseText;
				var parts = resp.split("\n");
				a_obj.innerHTML = "<div style='width: 200px;overflow:auto;max-height: 120px;'>";

				if(parts.length > 0) {
					for(i=0;i<parts.length;i++) {
						if(parts[i].length > 0) {
							a_obj.innerHTML += "<div class='autocomplete_option' onclick='autoCompleteSetSpentOn(\""+parts[i]+"\")'>" + parts[i] + "</div>";
						}
					}
					a_obj.innerHTML 		+= "</div>";
					a_obj.style.top 		= autocompletespenton_obj.offsetTop + 20;
					a_obj.style.left 		= autocompletespenton_obj.offsetLeft;
					a_obj.style.display 	= "inline";
				} else {
					a_obj.innerHTML = "No autocomplete matches";
				}
				httpRequest = false;
		}
	}
}


/** DATECHOOSER **/

/*
DateChooser 2.9
February 13, 2008
For usage details see http://yellow5.us/projects/datechooser/

Creative Commons Attribution 2.0 License
http://creativecommons.org/licenses/by/2.0/
*/

if (!objPHPDate){
	var objPHPDate ={
		/* These values are defaults. Please feel free to modify them as needed. */

		aDay: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
		aShortDay: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
		aLetterDay: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
		aMonth: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
		aShortMonth: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
		aSuffix: ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st'],

		/* End user-editable values */

		sTimezoneOffset: '',

		GetTimezoneOffset: function() {
			var objLocal = new Date();
			objLocal.setHours(12);
			objLocal.setMinutes(0);
			objLocal.setSeconds(0);
			objLocal.setMilliseconds(0);

			var objUTC = new Date();
			objUTC.setMilliseconds(objLocal.getUTCMilliseconds());
			objUTC.setSeconds(objLocal.getUTCSeconds());
			objUTC.setMinutes(objLocal.getUTCMinutes());
			objUTC.setHours(objLocal.getUTCHours());
			objUTC.setDate(objLocal.getUTCDate());
			objUTC.setMonth(objLocal.getUTCMonth());
			objUTC.setFullYear(objLocal.getUTCFullYear());

			this.sTimezoneOffset = ((objLocal.getTime() - objUTC.getTime()) / (1000 * 3600));
			var bNegative = (this.sTimezoneOffset < 0);

			this.sTimezoneOffset  = bNegative ? (this.sTimezoneOffset + '').substring(1) : this.sTimezoneOffset + '';
			this.sTimezoneOffset  = this.sTimezoneOffset.replace(/\.5/, (parseInt('$1', 10) * 60) + '');
			this.sTimezoneOffset += (this.sTimezoneOffset.substring(this.sTimezoneOffset.length - 3) != ':30') ? ':00' : '';
			this.sTimezoneOffset  = (this.sTimezoneOffset.substr(0, this.sTimezoneOffset.indexOf(':')).length == 1) ? '0' + this.sTimezoneOffset : this.sTimezoneOffset;
			this.sTimezoneOffset  = bNegative ? '-' + this.sTimezoneOffset : '+' + this.sTimezoneOffset;

			delete objLocal;
			delete objUTC;
			return true;
		},

		PHPDate: function() {
			var sFormat = (arguments.length > 0) ? arguments[0] : '';

			var nYear = this.getFullYear();
			var sYear = nYear + '';

			var nMonth = this.getMonth();
			var sMonth = (nMonth + 1) + '';
			var sPaddedMonth = (sMonth.length == 1) ? '0' + sMonth : sMonth;

			var nDate = this.getDate();
			var sDate = nDate + '';
			var sPaddedDate = (sDate.length == 1) ? '0' + sDate : sDate;

			var nDay = this.getDay();
			var sDay = nDay + '';

			sFormat = sFormat.replace(/([cDdFjLlMmNnrSUwYy])/g, 'y5-cal-regexp:$1');
			sFormat = sFormat.replace(/y5-cal-regexp:c/g, sYear + '-' + sPaddedMonth + '-' + sPaddedDate + 'T00:00:00' + objPHPDate.sTimezoneOffset);
			sFormat = sFormat.replace(/y5-cal-regexp:D/g, objPHPDate.aShortDay[nDay]);
			sFormat = sFormat.replace(/y5-cal-regexp:d/g, sPaddedDate);
			sFormat = sFormat.replace(/y5-cal-regexp:F/g, objPHPDate.aMonth[nMonth]);
			sFormat = sFormat.replace(/y5-cal-regexp:j/g, nDate);
			sFormat = sFormat.replace(/y5-cal-regexp:L/g, objPHPDate.aLetterDay[nDay]);
			sFormat = sFormat.replace(/y5-cal-regexp:l/g, objPHPDate.aDay[nDay]);
			sFormat = sFormat.replace(/y5-cal-regexp:M/g, objPHPDate.aShortMonth[nMonth]);
			sFormat = sFormat.replace(/y5-cal-regexp:m/g, sPaddedMonth);
			sFormat = sFormat.replace(/y5-cal-regexp:N/g, (nDay == 0) ? 7 : nDay);
			sFormat = sFormat.replace(/y5-cal-regexp:n/g, sMonth);
			sFormat = sFormat.replace(/y5-cal-regexp:r/g, objPHPDate.aShortDay[nDay] + ', ' + sPaddedDate + ' ' + objPHPDate.aShortMonth[nMonth] + ' ' + sYear + ' 00:00:00 ' + objPHPDate.sTimezoneOffset.replace(/:/, ''));
			sFormat = sFormat.replace(/y5-cal-regexp:S/g, objPHPDate.aSuffix[nDate]);
			sFormat = sFormat.replace(/y5-cal-regexp:U/g, parseInt((this.getTime() / 1000), 10));
			sFormat = sFormat.replace(/y5-cal-regexp:w/g, nDay);
			sFormat = sFormat.replace(/y5-cal-regexp:Y/g, sYear);
			sFormat = sFormat.replace(/y5-cal-regexp:y/g, sYear.substring(2));

			return sFormat;
		}
	};

	objPHPDate.GetTimezoneOffset();
	Date.prototype.getPHPDate = objPHPDate.PHPDate;
}

function DateChooser()
{
	/* These values are defaults. Please feel free to modify them as needed. */

	var nWeekStartDay = 0;
	var nXOffset = 0;
	var nYOffset = 0;
	var nTimeout = 0;
	var objAllowedDays = {'0':true, '1':true, '2':true, '3':true, '4':true, '5':true, '6':true};
	var fnUpdate = null;
	var sDefaultIcon = false;
	var objUpdateFields = {};
	var objEarliestDate = null;
	var objLatestDate = null;

	/* End user-editable values */

	if (!arguments || !document.getElementById || !document.getElementsByTagName) return null;
	var ndBodyElement = document.getElementsByTagName('body').length ? document.getElementsByTagName('body')[0] : document;
	var objTimeout = null;
	var ndFrame = null;

	/*@cc_on@*/
	/*@if(@_jscript_version < 6)
		if (document.getElementById('iframehack'))
		{
			ndFrame = document.getElementById('iframehack');
		}
		else
		{
			ndFrame = xb.createElement('iframe');
			ndFrame.id = 'iframehack';
			ndFrame.src = 'javascript:null;';
			ndFrame.scrolling = 'no';
			ndFrame.frameBorder = 0;
			ndFrame.style.border = '0';
			ndFrame.style.padding = 0;
			ndFrame.style.display = 'none';
			ndFrame.style.position = 'absolute';
			ndFrame.style.zIndex = '5000';

			ndBodyElement.appendChild(ndFrame);
		}
	/*@end@*/

	var nDateChooserID = 0;
	while (document.getElementById('calendar' + nDateChooserID)) ++nDateChooserID;
	var sDateChooserID = 'calendar' + nDateChooserID;

	var objSelectedDate = null;

	var objStartDate = new Date();
	objStartDate.setHours(12);
	objStartDate.setMinutes(0);
	objStartDate.setSeconds(0);
	objStartDate.setMilliseconds(0);

	var objMonthYear = new Date(objStartDate);
	objMonthYear.setDate(1);

	var ndDateChooser = xb.createElement('div');
	ndDateChooser.id = sDateChooserID;
	ndDateChooser.className = 'calendar';
	ndDateChooser.style.visibility = 'hidden';
	ndDateChooser.style.position = 'absolute';
	ndDateChooser.style.zIndex = '5001';
	ndDateChooser.style.top = '0';
	ndDateChooser.style.left = '0';
	ndBodyElement.appendChild(ndDateChooser);

	var AddClickEvents = function()
	{
		var aNavLinks = ndDateChooser.getElementsByTagName('thead')[0].getElementsByTagName('a');
		for (var nNavLink = 0; aNavLinks[nNavLink]; ++nNavLink)
		{
			events.add(aNavLinks[nNavLink], 'click', function(e)
			{
				e = e || events.fix(event);
				var ndClicked = e.target || e.srcElement;
				if (ndClicked.nodeName == '#text') ndClicked = ndClicked.parentNode;

				var sClass = ndClicked.className;

				if (sClass == 'previousyear')
				{
					objMonthYear.setFullYear(objMonthYear.getFullYear() - 1);
					if (objEarliestDate && objEarliestDate.getTime() > objMonthYear.getTime())
					{
						objMonthYear.setMonth(objEarliestDate.getMonth());
						objMonthYear.setFullYear(objEarliestDate.getFullYear());
					}
				}
				else if (sClass == 'previousmonth')
				{
					objMonthYear.setMonth(objMonthYear.getMonth() - 1);
					if (objEarliestDate && objEarliestDate.getTime() > objMonthYear.getTime())
					{
						objMonthYear.setMonth(objEarliestDate.getMonth());
						objMonthYear.setFullYear(objEarliestDate.getFullYear());
					}
				}
				else if (sClass == 'currentdate')
				{
					objMonthYear.setMonth(objStartDate.getMonth());
					objMonthYear.setFullYear(objStartDate.getFullYear());
				}
				else if (sClass == 'nextmonth')
				{
					objMonthYear.setMonth(objMonthYear.getMonth() + 1);
					if (objLatestDate && objLatestDate.getTime() < objMonthYear.getTime())
					{
						objMonthYear.setMonth(objLatestDate.getMonth());
						objMonthYear.setFullYear(objLatestDate.getFullYear());
					}
				}
				else if (sClass == 'nextyear')
				{
					objMonthYear.setFullYear(objMonthYear.getFullYear() + 1);
					if (objLatestDate && objLatestDate.getTime() < objMonthYear.getTime())
					{
						objMonthYear.setMonth(objLatestDate.getMonth());
						objMonthYear.setFullYear(objLatestDate.getFullYear());
					}
				}

				RefreshDisplay();
				return false;
			});
		}

		var aDateLinks = ndDateChooser.getElementsByTagName('tbody')[0].getElementsByTagName('a');
		for (var nDateLink = 0; aDateLinks[nDateLink]; ++nDateLink)
		{
			events.add(aDateLinks[nDateLink], 'click', function(e)
			{
				e = e || events.fix(event);
				var ndClicked = e.target || e.srcElement;
				if (ndClicked.nodeName == '#text') ndClicked = ndClicked.parentNode;

				for (var nLink = 0; aDateLinks[nLink]; ++nLink)
				{
					if (aDateLinks[nLink].className == 'selecteddate') aDateLinks[nLink].removeAttribute('class');
				}

				var objTempDate = new Date(objMonthYear);
				objTempDate.setDate(parseInt(ndClicked.childNodes[0].nodeValue, 10));

				var nTime = objTempDate.getTime();
				var sWeekday = objTempDate.getPHPDate('w');
				delete objTempDate;

				if (objEarliestDate && objEarliestDate.getTime() > nTime) return false;
				if (objLatestDate && objLatestDate.getTime() < nTime) return false;
				if (!objAllowedDays[sWeekday]) return false;

				objMonthYear.setTime(nTime);
				objMonthYear.setDate(1);
				if (!objSelectedDate) objSelectedDate = new Date(nTime);
				objSelectedDate.setTime(nTime);
				ndClicked.className = 'selecteddate';

				if (ndFrame) ndFrame.style.display = 'none';
				ndDateChooser.style.visibility = 'hidden';

				if (objTimeout) clearTimeout(objTimeout);

				UpdateFields();

				if (fnUpdate) fnUpdate(objSelectedDate);
				return false;
			});
		}

		return true;
	};

	var UpdateFields = function()
	{
		if (!objSelectedDate) return true;

		for (var sFieldName in objUpdateFields)
		{
			var ndField = document.getElementById(sFieldName);
			if (ndField) ndField.value = objSelectedDate.getPHPDate(objUpdateFields[sFieldName]);
		}

		return true;
	};

	var RefreshDisplay = function()
	{
		var ndTable, ndTHead, ndTR, ndTH, ndA, ndTBody, ndTD, nTime, sWeekday;
		var sClass = '';

		var objTempDate = new Date(objMonthYear);

		var objToday = new Date();
		objToday.setHours(12);
		objToday.setMinutes(0);
		objToday.setSeconds(0);
		objToday.setMilliseconds(0);

		ndTable = xb.createElement('table');
		ndTable.setAttribute('summary', 'DateChooser');

		ndTHead = xb.createElement('thead');
		ndTable.appendChild(ndTHead);

		ndTR = xb.createElement('tr');
		ndTHead.appendChild(ndTR);

		ndTH = xb.createElement('th');
		ndTR.appendChild(ndTH);
		ndA = xb.createElement('a');
		ndA.className = 'previousyear';
		ndA.setAttribute('href', '#');
		ndA.setAttribute('title', 'Previous Year');
		ndTH.appendChild(ndA);
		ndA.appendChild(document.createTextNode(String.fromCharCode(171)));

		ndTH = xb.createElement('th');
		ndTR.appendChild(ndTH);
		ndA = xb.createElement('a');
		ndA.className = 'previousmonth';
		ndA.setAttribute('href', '#');
		ndA.setAttribute('title', 'Previous Month');
		ndTH.appendChild(ndA);
		ndA.appendChild(document.createTextNode(String.fromCharCode(60)));

		ndTH = xb.createElement('th');
		ndTH.setAttribute('colspan', '3');
		/*@cc_on@*/
		/*@if(@_jscript)
			ndTH.colSpan = '3';
		/*@end@*/
		ndTR.appendChild(ndTH);
		ndA = xb.createElement('a');
		ndA.className = 'currentdate';
		ndA.setAttribute('href', '#');
		ndA.setAttribute('title', 'Current Date');
		ndTH.appendChild(ndA);
		ndA.appendChild(document.createTextNode(objMonthYear.getPHPDate("M Y")));

		ndTH = xb.createElement('th');
		ndTR.appendChild(ndTH);
		ndA = xb.createElement('a');
		ndA.className = 'nextmonth';
		ndA.setAttribute('href', '#');
		ndA.setAttribute('title', 'Next Month');
		ndTH.appendChild(ndA);
		ndA.appendChild(document.createTextNode(String.fromCharCode(62)));

		ndTH = xb.createElement('th');
		ndTR.appendChild(ndTH);
		ndA = xb.createElement('a');
		ndA.className = 'nextyear';
		ndA.setAttribute('href', '#');
		ndA.setAttribute('title', 'Next Year');
		ndTH.appendChild(ndA);
		ndA.appendChild(document.createTextNode(String.fromCharCode(187)));

		ndTR = xb.createElement('tr');
		ndTHead.appendChild(ndTR);

		for (var nDay = 0; objPHPDate.aLetterDay[nDay]; ++nDay)
		{
			ndTD = xb.createElement('td');
			ndTR.appendChild(ndTD);
			ndTD.appendChild(document.createTextNode(objPHPDate.aLetterDay[(nWeekStartDay + nDay) % objPHPDate.aLetterDay.length]));
		}

		ndTBody = xb.createElement('tbody');
		ndTable.appendChild(ndTBody);

		while (objTempDate.getMonth() == objMonthYear.getMonth())
		{
			ndTR = xb.createElement('tr');
			ndTBody.appendChild(ndTR);

			for (nDay = 0; nDay < 7; ++nDay)
			{
				var nWeek = (nWeekStartDay + nDay) % objPHPDate.aLetterDay.length;
				if ((objTempDate.getUTCDay() == nWeek) && (objTempDate.getMonth() == objMonthYear.getMonth()))
				{
					nTime = objTempDate.getTime();
					sWeekday = objTempDate.getPHPDate('w');

					sClass  = (objSelectedDate && (objTempDate.getTime() == objSelectedDate.getTime())) ? 'selectedday' : '';
					sClass += (objTempDate.getTime() == objToday.getTime()) ? ' today' : '';
					sClass  = ((sClass.length > 0) && (sClass[1] == ' ')) ? sClass.substr(1, sClass.length - 1) : sClass;

					ndTD = xb.createElement('td');
					if ((objEarliestDate && objEarliestDate.getTime() > nTime) || (objLatestDate && objLatestDate.getTime() < nTime) || !objAllowedDays[sWeekday]) ndTD.className = 'invalidday';
					ndTR.appendChild(ndTD);

					ndA = xb.createElement('a');
					if (sClass.length > 0) ndA.className = sClass;
					ndA.setAttribute('href', '#');
					ndTD.appendChild(ndA);
					ndA.appendChild(document.createTextNode(objTempDate.getDate()));

					objTempDate.setDate(objTempDate.getDate() + 1);
				}
				else
				{
					ndTD = xb.createElement('td');
					ndTR.appendChild(ndTD);
				}
			}
		}

		while (ndDateChooser.hasChildNodes()) ndDateChooser.removeChild(ndDateChooser.firstChild);
		ndDateChooser.appendChild(ndTable);

		if (ndFrame)
		{
			ndFrame.style.display = 'block';
			ndFrame.style.top = ndDateChooser.style.top;
			ndFrame.style.left = ndDateChooser.style.left;
			ndFrame.style.width = (ndTable.clientWidth + 2) + 'px';
			ndFrame.style.height = (ndTable.clientHeight + 4) + 'px';
		}

		AddClickEvents();

		delete objTempDate;
		delete objToday;
		return true;
	};

	var DisplayDateChooser = function()
	{
		var sPositionX = (arguments.length > 0) ? arguments[0] : 'auto';
		var sPositionY = (arguments.length > 1) ? arguments[1] : 'auto';

		var ndStyle = ndDateChooser.style;
		ndStyle.top = sPositionY + '';
		ndStyle.left = sPositionX + '';

		ndDateChooser.style.visibility = 'visible';
		if (objTimeout) clearTimeout(objTimeout);

		if (objSelectedDate)
		{
			objMonthYear.setTime(objSelectedDate.getTime());
		}
		else
		{
			objMonthYear.setTime(objStartDate.getTime());
		}

		objMonthYear.setHours(12);
		objMonthYear.setMinutes(0);
		objMonthYear.setSeconds(0);
		objMonthYear.setMilliseconds(0);
		objMonthYear.setDate(1);

		return RefreshDisplay();
	};

	var GetPosition = function(ndNode)
	{
		var nTop = 0, nLeft = 0;
		if (ndNode.offsetParent)
		{
			nTop = ndNode.offsetTop;
			nLeft = ndNode.offsetLeft;

			while (ndNode.offsetParent)
			{
				ndNode = ndNode.offsetParent;

				nTop += ndNode.offsetTop;
				nLeft += ndNode.offsetLeft;
			}
		}

		return ({'top' : nTop, 'left' : nLeft});
	};

	this.displayPosition = function()
	{
		var sPositionX = (arguments.length > 0) ? arguments[0] : 'auto';
		var sPositionY = (arguments.length > 1) ? arguments[1] : 'auto';

		return DisplayDateChooser(sPositionX, sPositionY);
	};

	this.display = function(e)
	{
		e = e || events.fix(event);

		var ndClicked = e.target || e.srcElement;
		if (ndClicked.nodeName == '#text') ndClicked = ndClicked.parentNode;

		var objPosition = GetPosition(ndClicked);

		DisplayDateChooser(objPosition.left + nXOffset + 'px', objPosition.top + nYOffset + 'px');

		return false;
	};

	this.setXOffset = function()
	{
		nXOffset = ((arguments.length > 0) && (typeof(arguments[0]) == 'number')) ? parseInt(arguments[0], 10) : nXOffset;

		return true;
	};

	this.setYOffset = function()
	{
		nYOffset = ((arguments.length > 0) && (typeof(arguments[0]) == 'number')) ? parseInt(arguments[0], 10) : nYOffset;

		return true;
	};

	this.setCloseTime = function()
	{
		nTimeout = ((arguments.length > 0) && (typeof(arguments[0]) == 'number') && (arguments[0] >= 0)) ? arguments[0] : nTimeout;

		return true;
	};

	this.setUpdateFunction = function()
	{
		if ((arguments.length > 0) && (typeof(arguments[0]) == 'function')) fnUpdate = arguments[0];

		return true;
	};

	this.setUpdateField = function()
	{
		objUpdateFields = {};
		if ((typeof(arguments[0]) == 'string') && (typeof(arguments[1]) == 'string') && document.getElementById(arguments[0]))
		{
			objUpdateFields[arguments[0]] = arguments[1];
		}
		else if ((typeof(arguments[0]) == 'object') && (typeof(arguments[1]) == 'object'))
		{
			for (var nField = 0; arguments[0][nField] !== undefined; ++nField)
			{
				if (nField >= arguments[1].length) break;
				objUpdateFields[arguments[0][nField]] = arguments[1][nField];
			}
		}
		else if (typeof(arguments[0]) == 'object')
		{
			objUpdateFields = arguments[0];
		}

		return true;
	};

	this.setLink = function()
	{
		var sLinkText = ((arguments.length > 0) && (typeof(arguments[0]) == 'string')) ? arguments[0] : 'Choose a date';
		var ndNode = ((arguments.length > 1) && (typeof(arguments[1]) == 'string')) ? document.getElementById(arguments[1]) : null;
		var bPlaceRight = ((arguments.length <= 2) || arguments[2]);
		var sTitleText = ((arguments.length > 3) && (typeof(arguments[3]) == 'string')) ? arguments[3] : 'Click to choose a date';

		if (!ndNode) return false;

		var ndAnchor = xb.createElement('a');
		ndAnchor.className = 'calendarlink';
		ndAnchor.href = '#';

		if (sTitleText.length > 0) ndAnchor.setAttribute('title', sTitleText);
		ndAnchor.appendChild(document.createTextNode(sLinkText));

		if (bPlaceRight)
		{
			if (ndNode.nextSibling)
			{
				ndNode.parentNode.insertBefore(ndAnchor, ndNode.nextSibling);
			}
			else
			{
				ndNode.parentNode.appendChild(ndAnchor);
			}
		}
		else
		{
			ndNode.parentNode.insertBefore(ndAnchor, ndNode);
		}

		events.add(ndAnchor, 'click', this.display);

		return true;
	};

	this.setIcon = function()
	{
		var sIconFile = ((arguments.length > 0) && (typeof(arguments[0]) == 'string')) ? arguments[0] : sDefaultIcon;
		var ndNode = ((arguments.length > 1) && (typeof(arguments[1]) == 'string')) ? document.getElementById(arguments[1]) : null;
		var bPlaceRight = ((arguments.length <= 2) || arguments[2]);
		var sTitleText = ((arguments.length > 3) && (typeof(arguments[3]) == 'string')) ? arguments[3] : 'Click to choose a date';

		if (!ndNode || !sIconFile) return false;

		var ndIcon = xb.createElement('img');
		ndIcon.className = 'calendaricon';
		ndIcon.src = sIconFile;
		ndIcon.setAttribute('alt', 'DateChooser Icon ' + (nDateChooserID + 1));
		if (sTitleText.length > 0) ndIcon.setAttribute('title', sTitleText);

		if (bPlaceRight)
		{
			if (ndNode.nextSibling)
			{
				ndNode.parentNode.insertBefore(ndIcon, ndNode.nextSibling);
			}
			else
			{
				ndNode.parentNode.appendChild(ndIcon);
			}
		}
		else
		{
			ndNode.parentNode.insertBefore(ndIcon, ndNode);
		}

		events.add(ndIcon, 'click', this.display);

		return true;
	};

	this.setStartDate = function()
	{
		if (!arguments.length || !(typeof(arguments[0]) == 'object') || !arguments[0].getTime) return false;

		objStartDate.setTime(arguments[0].getTime());
		objStartDate.setHours(12);
		objStartDate.setMinutes(0);
		objStartDate.setSeconds(0);
		objStartDate.setMilliseconds(0);

		if (objEarliestDate && objEarliestDate.getTime() > objStartDate.getTime())
		{
			objStartDate.setTime(objEarliestDate.getTime());
		}
		else if (objLatestDate && objLatestDate.getTime() < objStartDate.getTime())
		{
			objStartDate.setTime(objLatestDate.getTime());
		}

		objMonthYear.setMonth(objStartDate.getMonth());
		objMonthYear.setFullYear(objStartDate.getFullYear());

		if (!objSelectedDate) objSelectedDate = new Date(objStartDate);
		objSelectedDate.setTime(objStartDate);

		return true;
	};

	this.setEarliestDate = function()
	{
		if (!arguments.length || (typeof(arguments[0]) != 'object') || !arguments[0].getTime) return false;

		objEarliestDate = new Date();
		objEarliestDate.setTime(arguments[0].getTime());
		objEarliestDate.setHours(12);
		objEarliestDate.setMinutes(0);
		objEarliestDate.setSeconds(0);
		objEarliestDate.setMilliseconds(0);

		if (objEarliestDate.getTime() > objStartDate.getTime())
		{
			objStartDate.setTime(objEarliestDate.getTime());
			objMonthYear.setMonth(objEarliestDate.getMonth());
			objMonthYear.setFullYear(objEarliestDate.getFullYear());
		}

		if (objSelectedDate && (objEarliestDate.getTime() > objSelectedDate.getTime()))
		{
			objSelectedDate.setTime(objEarliestDate.getTime());
			objMonthYear.setMonth(objEarliestDate.getMonth());
			objMonthYear.setFullYear(objEarliestDate.getFullYear());
		}

		return true;
	};

	this.setLatestDate = function()
	{
		if (!arguments.length || !(typeof(arguments[0]) == 'object') || !arguments[0].getTime) return false;

		objLatestDate = new Date();
		objLatestDate.setTime(arguments[0].getTime());
		objLatestDate.setHours(12);
		objLatestDate.setMinutes(0);
		objLatestDate.setSeconds(0);
		objLatestDate.setMilliseconds(0);

		if (objLatestDate.getTime() < objStartDate.getTime())
		{
			objStartDate.setTime(objLatestDate.getTime());
			objMonthYear.setMonth(objLatestDate.getMonth());
			objMonthYear.setFullYear(objLatestDate.getFullYear());
		}

		if (objSelectedDate && (objLatestDate.getTime() < objSelectedDate.getTime()))
		{
			objSelectedDate.setTime(objLatestDate.getTime());
			objMonthYear.setMonth(objLatestDate.getMonth());
			objMonthYear.setFullYear(objLatestDate.getFullYear());
		}

		return true;
	};

	this.setAllowedDays = function()
	{
		if (!arguments.length || !(typeof(arguments[0]) == 'object')) return false;

		var nCount;
		for (nCount = 0; nCount < 7; ++nCount)
		{
			objAllowedDays[nCount + ''] = false;
		}

		for (nCount = 0; arguments[0][nCount] !== undefined; ++nCount)
		{
			objAllowedDays[arguments[0][nCount] + ''] = true;
		}

		return true;
	};

	this.setWeekStartDay = function()
	{
		if (!arguments.length || !(typeof(arguments[0]) == 'number')) return false;

		var nNewStartDay = parseInt(arguments[0], 10);
		if ((nNewStartDay < 0) || (nNewStartDay > 6)) return false;

		nWeekStartDay = nNewStartDay;

		return true;
	};

	this.getSelectedDate = function()
	{
		return objSelectedDate;
	};

	this.setSelectedDate = function(objDate)
	{
		if (!objSelectedDate) objSelectedDate = new Date(objDate);

		objSelectedDate.setTime(objDate.getTime());
		objSelectedDate.setHours(12);
		objSelectedDate.setMinutes(0);
		objSelectedDate.setSeconds(0);
		objSelectedDate.setMilliseconds(0);

		UpdateFields();

		return true;
	};

	this.updateFields = function()
	{
		return UpdateFields();
	};

	var clickWindow = function(e)
	{
		e = e || events.fix(event);
		var ndTarget = e.target || e.srcElement;
		if (ndTarget.nodeName == '#text') ndTarget = ndTarget.parentNode;

		while (ndTarget && (ndTarget != document))
		{
			if (ndTarget.className == 'calendar') return true;
			ndTarget = ndTarget.parentNode;
		}

		for (var nCount = 0; nCount <= nDateChooserID; ++nCount)
		{
			if (ndFrame) ndFrame.style.display = 'none';
			document.getElementById('calendar' + nCount).style.visibility = 'hidden';
		}

		return true;
	};

	var mouseoverDateChooser = function()
	{
		if (objTimeout) clearTimeout(objTimeout);
		return true;
	};

	var mouseoutDateChooser = function()
	{
		if (nTimeout > 0) objTimeout = setTimeout('document.getElementById("' + sDateChooserID + '").style.visibility = "hidden"; if (document.getElementById("iframehack")) document.getElementById("iframehack").style.display = "none";', nTimeout);

		return true;
	};

	events.add(ndDateChooser, 'mouseover', mouseoverDateChooser);
	events.add(ndDateChooser, 'mouseout', mouseoutDateChooser);
	events.add(document, 'mousedown', clickWindow);

	return true;
}

if (!Array.prototype.push)
{
	Array.prototype.push = function()
	{
		for (var nCount = 0; arguments[nCount] !== undefined; nCount++)
		{
			this[this.length] = arguments[nCount];
		}

		return this.length;
	};
}

if (!xb)
{
	var xb =
	{
		createElement: function(sElement)
		{
			if (document.createElementNS) return document.createElementNS('http://www.w3.org/1999/xhtml', sElement);
			if (document.createElement) return document.createElement(sElement);

			return null;
		},

		getElementsByAttribute: function(ndNode, sAttributeName, sAttributeValue)
		{
			var aReturnElements = [];

			if (!ndNode.all && !ndNode.getElementsByTagName) return aReturnElements;

			var rAttributeValue = RegExp('(^|\\s)' + sAttributeValue + '(\\s|$)');
			var sValue, aElements = ndNode.all || ndNode.getElementsByTagName('*');

			for (var nIndex = 0; aElements[nIndex]; ++nIndex)
			{
				if (!aElements[nIndex].getAttribute) continue;
				sValue = (sAttributeName == 'class') ? aElements[nIndex].className : aElements[nIndex].getAttribute(sAttributeName);
				if ((typeof(sValue) != 'string') || (sValue.length == 0)) continue;

				if (rAttributeValue.test(sValue)) aReturnElements.push(aElements[nIndex]);
			}

			return aReturnElements;
		},

		getOption: function(ndNode, sOption)
		{
			var sText = ndNode.getAttribute(sOption);
			if (sText) return sText;

			var sDefault = (arguments.length == 3) ? arguments[2] : false;
			var aMatch = ndNode.className.match(RegExp('(?:^|\\s)' + sOption + '=(?:\\\'|\\\")([^\\\'\\\"]+)(?:\\\'|\\\"|$)'));

			return aMatch ? aMatch[1] : sDefault;
		}
	};
}

// This is a variation of the addEvent script written by Dean Edwards (dean.edwards.name).
if (!events)
{
	var events =
	{
		nEventID: 1,

		add: function(ndElement, sType, fnHandler)
		{
			if (!fnHandler.$$nEventID) fnHandler.$$nEventID = this.nEventID++;
			if (ndElement.objEvents === undefined) ndElement.objEvents = {};

			var aHandlers = ndElement.objEvents[sType];
			if (!aHandlers)
			{
				aHandlers = ndElement.objEvents[sType] = {};
				if (ndElement['on' + sType]) aHandlers[0] = ndElement['on' + sType];
			}

			aHandlers[fnHandler.$$nEventID] = fnHandler;
			ndElement['on' + sType] = this.handle;

			return true;
		},

		handle: function(e)
		{
			e = e || events.fix(event);

			var bReturn = true, aHandlers = this.objEvents[e.type];
			for (var nIndex in aHandlers)
			{
				this.$$handle = aHandlers[nIndex];
				if (this.$$handle(e) === false) bReturn = false;
			}

			return bReturn;
		},

		fix: function(e)
		{
			e.preventDefault = this.fix.preventDefault;
			e.stopPropagation = this.fix.stopPropagation;

			return e;
		}
	};

	events.fix.preventDefault = function()
	{
		this.returnValue = false;

		return true;
	}

	events.fix.stopPropagation = function()
	{
		this.cancelBubble = true;

		return true;
	}
}

events.add(window, 'load', function()
{
	var ndDateChooser, ndElement, sLastID, sLinkID, objUpdateField, objDate, aPatternNodes;
	var sDateFormat, sIcon, sText, sXOffset, sYOffset, sCloseTime, sOnUpdate, sStartDate, sEarliestDate, sLatestDate, sAllowedDays, sWeekStartDay, sLinkPosition;
	var nFieldID = 0;

	objDate = new Date();
	objDate.setHours(12);
	objDate.setMinutes(0);
	objDate.setMilliseconds(0);

	var aElements = xb.getElementsByAttribute(document, 'class', 'datechooser');
	for (var nIndex = 0; aElements[nIndex]; ++nIndex)
	{
		ndDateChooser = aElements[nIndex];
		if (!ndDateChooser.id) ndDateChooser.id = 'dc-id-' + (++nFieldID);
		sLastID = ndDateChooser.id;

		sDateFormat = xb.getOption(ndDateChooser, 'dc-dateformat');
		sIcon = xb.getOption(ndDateChooser, 'dc-iconlink');
		sText = xb.getOption(ndDateChooser, 'dc-textlink');
		sXOffset = xb.getOption(ndDateChooser, 'dc-offset-x');
		sYOffset = xb.getOption(ndDateChooser, 'dc-offset-y');
		sCloseTime = xb.getOption(ndDateChooser, 'dc-closetime');
		sOnUpdate = xb.getOption(ndDateChooser, 'dc-onupdate');
		sStartDate = xb.getOption(ndDateChooser, 'dc-startdate');
		sEarliestDate = xb.getOption(ndDateChooser, 'dc-earliestdate');
		sLatestDate = xb.getOption(ndDateChooser, 'dc-latestdate');
		sAllowedDays = xb.getOption(ndDateChooser, 'dc-alloweddays');
		sWeekStartDay = xb.getOption(ndDateChooser, 'dc-weekstartday');
		sLinkPosition = xb.getOption(ndDateChooser, 'dc-linkposition');

		if (sLinkPosition) sLinkID = ndDateChooser.id;

		objUpdateField = {};
		if (sDateFormat) objUpdateField[ndDateChooser.id] = sDateFormat;

		aPatternNodes = ndDateChooser.all || ndDateChooser.getElementsByTagName('*');
		for (var nPattern = 0; aPatternNodes[nPattern]; ++nPattern)
		{
			ndElement = aPatternNodes[nPattern];

			sDateFormat = xb.getOption(ndElement, 'dc-dateformat');
			if (!sDateFormat) continue;

			if (!ndElement.id) ndElement.id = 'dc-id-' + (++nFieldID);

			sLastID = ndElement.id;
			objUpdateField[sLastID] = sDateFormat;

			if (!sLinkPosition) xb.getOption(ndElement, 'dc-linkposition');
			if (sLinkPosition) sLinkID = sLastID;
		}

		if (!sLinkPosition)
		{
			sLinkID = sLastID;
			sLinkPosition = 'right';
		}

		ndDateChooser.DateChooser = new DateChooser();
		if (sXOffset) ndDateChooser.DateChooser.setXOffset(sXOffset);
		if (sYOffset) ndDateChooser.DateChooser.setYOffset(sYOffset);
		if (sCloseTime) ndDateChooser.DateChooser.setCloseTime(sCloseTime);
		if (sOnUpdate) ndDateChooser.DateChooser.setUpdateFunction(eval(sOnUpdate));

		if (sStartDate)
		{
			objDate = new Date();
			objDate.setDate(parseInt(sStartDate.substring(2, 4), 10));
			objDate.setMonth(parseInt(sStartDate.substring(0, 2), 10) - 1);
			objDate.setFullYear(parseInt(sStartDate.substring(4), 10));

			ndDateChooser.DateChooser.setStartDate(objDate);
		}

		if (sEarliestDate)
		{
			objDate = new Date();
			objDate.setDate(parseInt(sEarliestDate.substring(2, 4), 10));
			objDate.setMonth(parseInt(sEarliestDate.substring(0, 2), 10) - 1);
			objDate.setFullYear(parseInt(sEarliestDate.substring(4), 10));

			ndDateChooser.DateChooser.setEarliestDate(objDate);
		}

		if (sLatestDate)
		{
			objDate = new Date();
			objDate.setDate(parseInt(sLatestDate.substring(2, 4), 10));
			objDate.setMonth(parseInt(sLatestDate.substring(0, 2), 10) - 1);
			objDate.setFullYear(parseInt(sLatestDate.substring(4), 10));

			ndDateChooser.DateChooser.setLatestDate(objDate);
		}

		if (sAllowedDays) ndDateChooser.DateChooser.setAllowedDays(sAllowedDays.split(','));
		if (sWeekStartDay) ndDateChooser.DateChooser.setWeekStartDay(parseInt(sWeekStartDay, 10));
		if (sIcon) ndDateChooser.DateChooser.setIcon(sIcon, sLinkID, (sLinkPosition != 'left'));
		if (sText) ndDateChooser.DateChooser.setLink(sText, sLinkID, (sLinkPosition != 'left'));
		ndDateChooser.DateChooser.setUpdateField(objUpdateField);
	}

	delete objDate;

	return true;
});


/** MGBOX **/

//
// mgbox.js
//
// All mgBox related functions.
// There should not be any need to modify this file,
// customisation can be achieved through various
// "hook" functions.
//
// Feel free to use as you please, but please retain this
// copyright notice.
//
// 2005-02-10 MGrill Version 1.00
// 2005-02-17 MGrill added onLoad hook
//
// see http://www.dcs.lancs.ac.uk/~grill/mgbox/
//

// This is the mgBox class declaration.
// The one and only global mgBox object will be called "theMgBox",
// this object will be instantiated further down.
function mgBox() {
  if(typeof MGBOX_ASSIST_CGI_TEMPLATE == 'undefined') {
    this.ASSIST_CGI_TEMPLATE = "cgi/assist_@.php?s=";
  } else {
    this.ASSIST_CGI_TEMPLATE = MGBOX_ASSIST_CGI_TEMPLATE;
  }
  this.IDLETIME = 300;  // after this duration we start processing the user input!
  this.timerid=null;    // will hold the timer that waits until the user does nothing for IDLETIME ms.
  this.oldcontents="";  // the previous contents of the text box
  this.textboxid="";    // our textbox - will get updated in call to onFocus() later on...
  this.textfieldhandle=null;  // handle to our textbox, see above
  this.httprequest = createXMLHttpRequest();  // the one and only active httprequest object...
  this.httprequestactive = false;
  this.highlightedline = null;
  this.html_text_array = Array(); // results from database
  this.raw_text_array = Array();  // queries go into
  this.id_array = Array();        // these three arrays
  this.isOpenAndFilled = false;
}

function doIt(s) {
	alert(s);
}

function MgOnKeyPress(event) {
	if(!event) {
    event = window.event;
  }
  if(event.keyCode==13) {  // "ENTER"
  	return false;
  }
}

// gets called whenever a keydown event happens
function MgOnKeyDown(event) {
  // we process the key. if it is a "normal" character, we only react after
  // a specified timeout (see below).
  // "event" only gets set if the handler was assigned from within
  // javascript, not in the html code. this is done in onFocus().
  if(!event) {
    event = window.event;
  }
  var hBox = getElem("id","mgBox");

  ////////////////// ESCAPE ///////////////
  if(event.keyCode==27) {
  	theMgBox.hideMgBox();
  }

  ///////////////// DOWN //////////////////
  if(event.keyCode==40) {  // "down"
    if(!theMgBox.isOpenAndFilled) {
      theMgBox.timeoutReached(theMgBox.textboxid);
    } else {
      if(theMgBox.highlightedline!=null && theMgBox.highlightedline>=0) {
        // change currently hightlighted line back to normal
        //alert(theMgBox.highlightedline);
        hBox.childNodes[0].childNodes[theMgBox.highlightedline].className="";
        // advance selection by one
        theMgBox.highlightedline++;
        //alert(theMgBox.highlightedline);
      } else {
        if (theMgBox.html_text_array.length>0) {
          theMgBox.highlightedline = 0;
        }
      }
      // highlight the new line
      hBox.childNodes[0].childNodes[theMgBox.highlightedline].className="mgHighlighted";
    }
  }

  ///////////////// UP //////////////////
  if(event.keyCode==38) {  // "up"
    if(!theMgBox.isOpenAndFilled) {
      theMgBox.timeoutReached(theMgBox.textboxid);
    } else {
      if(theMgBox.highlightedline!=null) {
        // change currently hightlighted line back to normal
        hBox.childNodes[0].childNodes[theMgBox.highlightedline].className="";
        // advance selection by one (upwards)
        theMgBox.highlightedline = (theMgBox.highlightedline==0) ?
                                   theMgBox.html_text_array.length-1
                                   : theMgBox.highlightedline-1;
      } else {
        theMgBox.highlightedline = theMgBox.html_text_array.length-1;
      }
      // highlight the new line
      hBox.childNodes[0].childNodes[theMgBox.highlightedline].className="mgHighlighted";
    }
  }

  ///////////////// ENTER //////////////////
  if(event.keyCode==13) {  // "ENTER"
    if(!theMgBox.isOpenAndFilled) {
      theMgBox.timeoutReached(theMgBox.textboxid);
    } else {
      theMgBox.hideMgBox();

      // copy text into edit field
      var hTextbox = getElem("id",theMgBox.textboxid);
      if(theMgBox.raw_text_array[theMgBox.highlightedline] != undefined) {
	      hTextbox.value = theMgBox.raw_text_array[theMgBox.highlightedline];
	      theMgBox.oldcontents = theMgBox.raw_text_array[theMgBox.highlightedline];

	      // Remember author ID in hidden input field (if it exists)
	      var hHiddenIdBox = getElem("id",theMgBox.textboxid+"_id");
	      if( hHiddenIdBox != null) {
	        hHiddenIdBox.value = theMgBox.id_array[theMgBox.highlightedline];
	      }
	      /*
	      theMgBox.textfieldhandle.onkeydown = null;
		  theMgBox.textfieldhandle.onkeyup = null;
		  theMgBox.textfieldhandle.onblur = null;
		  theMgBox.hideMgBox();

		  // call hook function if it exists
		  if(typeof mgBox_onBlur_hook == 'function') {
		    mgBox_onBlur_hook(theMgBox.textboxid);
		  }

		  // reset some MgBox related properties to make sure it
		  // doesn't suddenly pop up!
		  theMgBox.textboxid = "";
		  theMgBox.oldcontents = "";
		  theMgBox.httprequestactive = false;
		  theMgBox.handle = null;*/
      }

      // call hook if present
      if(typeof mgBox_onEnter_hook == 'function') {
        mgBox_onEnter_hook(theMgBox.textboxid);
      }
    }
    return false;
  }
}
mgBox.prototype.onKeyDown = MgOnKeyDown;
mgBox.prototype.onKeyPress = MgOnKeyPress;

function MgOnFocus(event) {
  // we store our parent id within the MgBox object, so that later on we
  // can check whether a delayed result does actually belong to the currently
  // active box
  // we also reset some other properties

  // first we need to find out the id of our textfield, though:
  if( event == null ) {
    event = window.event;
  }
  var hElement = ( event.srcElement ) ? event.srcElement : event.originalTarget;
  var id=hElement.id;

  theMgBox.textboxid = id;
  if( !id ) {
    alert( 'Error: every mgBox needs a unique ID attribute!' );
  }
  theMgBox.httprequestactive = false;
  theMgBox.textfieldhandle = getElem("id",id);
  theMgBox.oldcontents= theMgBox.textfieldhandle.value;  // old contents = current contents

  // we attach the keydown handler
  theMgBox.textfieldhandle.onkeydown = theMgBox.onKeyDown;
  theMgBox.textfieldhandle.onkeyup = theMgBox.onKeyUp;
  theMgBox.textfieldhandle.onblur = theMgBox.onBlur;
  theMgBox.textfieldhandle.onkeypress = theMgBox.onKeyPress
}
mgBox.prototype.onFocus = MgOnFocus;

function MgOnBlur(event) {
  theMgBox.textfieldhandle.onkeydown = null;
  theMgBox.textfieldhandle.onkeyup = null;
  theMgBox.textfieldhandle.onblur = null;
  theMgBox.hideMgBox();

  // call hook function if it exists
  if(typeof mgBox_onBlur_hook == 'function') {
    mgBox_onBlur_hook(theMgBox.textboxid);
  }

  // reset some MgBox related properties to make sure it
  // doesn't suddenly pop up!
  theMgBox.textboxid = "";
  theMgBox.oldcontents = "";
  theMgBox.httprequestactive = false;
  theMgBox.handle = null;
}
mgBox.prototype.onBlur = MgOnBlur;

function MgOnKeyUp(event) {
  // we process the results of the previous keypress.
  // "event" only gets set if the handler was assigned from within
  // javascript, not in the html code. this is done in onFocus().
  if(!event) {
    event = window.event;
  }

  var id=theMgBox.textboxid;
  var mytextbox = getElem("id",id);
  var textfieldcontents = mytextbox.value;

  if(textfieldcontents.length < 2) {
  		return true;
  }

  if(textfieldcontents!=theMgBox.oldcontents) {
    // execute new query to fill listbox
    theMgBox.oldcontents = textfieldcontents;

    // call hook if present
    if(typeof mgBox_onContentsChange_hook == 'function') {
      mgBox_onContentsChange_hook(id);
    }

    // We also try to parse the entry if a suitable
    // parsing function exists
    var parse_function = "mgBox_parse_"+id.removeTrailingDigitsIfPresent()+"_field";
    if (eval("typeof "+parse_function)=='function') {
      eval(parse_function+"('"+id+"')");
    }

    // we reset our timeout timer (search will only spring into action when the user does nothing
    // for IDLETIME ms so that we don't slow down the user experience.
    if (theMgBox.timerid!=null) {
      clearTimeout(theMgBox.timerid);
    }
    theMgBox.timerid = setTimeout("theMgBox.timeoutReached('"+theMgBox.textboxid+"')",theMgBox.IDLETIME);
  }
}
mgBox.prototype.onKeyUp = MgOnKeyUp;

function MgTimeoutReached(id) {
  // user was idle for IDLETIME ms, do some processing!
  this.timerid = null;

	// has the focus changed in the meantime?
  if (id!=theMgBox.textboxid) {
    return;
  }

  // we update the listbox if the contents of the text field have changed
  var mytextbox = getElem("id",id);
  var textfieldcontents = mytextbox.value;
  if(1) {
    // execute new query to fill listbox

    // first, show "updating..." indicator inside mgBox DIV
    var mgBoxDiv = getElem("id","mgBox");
    mgBoxDiv.innerHTML = "searching for '"+textfieldcontents+"'...";
    theMgBox.isOpenAndFilled = false;
    theMgBox.highlightedline = null;  // reset selection


    // cancel any previous http requests that are still active
    if( theMgBox.httprequestactive ) {
      // cancel currently ongoing request
      //this.httprequest.abort(); // see http://www.w3schools.com/dom/dom_http.asp
      // creates empty results, so we simply create a new object instead...
      delete theMgBox.httprequest; // not sure whether we need to delete objects, we do it just in case...
      theMgBox.httprequest = createXMLHttpRequest(); // create a new one...
      theMgBox.httprequestactive = false;
    }
    if( !theMgBox.httprequestactive ) {
      theMgBox.httprequestactive = true;
      // build name of cgi, based on textbox id (less 2-digit suffix if present)
      var cgi_name = theMgBox.ASSIST_CGI_TEMPLATE.replace(/@/,
                      theMgBox.textboxid.removeTrailingDigitsIfPresent());
      theMgBox.httprequest.open("GET", cgi_name+URLEncode(textfieldcontents),true);
      theMgBox.httprequest.onreadystatechange=function() {

// Ready States
//    * 0: UNINITIALIZED open() has not been called yet
//    * 1: LOADING Request not yet made (send() not called)
//    * 2: LOADED Contact established with server and HTTP status code recieved
//    * 3: INTERACTIVE In Mozilla, called multiple times while response is fetched - every 4096 bytes of response
//    * 4: COMPLETED Response complete

        if (theMgBox.httprequest.readyState==4) {
        	// make sure the box is displayed (this may be the first time!!!)
    		theMgBox.showMgBox();
        	// has the focus changed in the meantime?
          if (theMgBox.httprequestactive == false) {
            return;
          }

          //alert(theMgBox.httprequest.readyState.toString() + " - " + theMgBox.httprequest.responseText)
          var mgBoxDiv = getElem("id","mgBox");
          // store result in internal arrays
          var result_array = theMgBox.httprequest.responseText.split("\n");
            delete theMgBox.html_text_array;
            delete theMgBox.raw_text_array;
            delete theMgBox.id_array;
            theMgBox.html_text_array = new Array();
            theMgBox.raw_text_array = new Array();
            theMgBox.id_array = new Array();
            var total_html='<ul>';

            for(var i=0; i<result_array.length; i++) { // ignore line after last \n
              theMgBox.html_text_array.push(result_array[i]);
              theMgBox.raw_text_array.push(result_array[i]);
              theMgBox.id_array.push(i);
              total_html = total_html + '<li onclick="doIt(' + result_array[i] + '">' + result_array[i] + '</li>';
            }
            total_html = total_html + '</ul>'
            mgBoxDiv.innerHTML = total_html;
            // highlight the first line
            theMgBox.highlightedline = null;
//            mgBoxDiv.childNodes[0].childNodes[theMgBox.highlightedline].className="mgHighlighted";
            theMgBox.isOpenAndFilled = true;
          theMgBox.httprequestactive = false;
        }
      }
      theMgBox.httprequest.send(null);   // this will send the request
    }
  }
  // otherwise we do nothing
}
mgBox.prototype.timeoutReached = MgTimeoutReached;

function MgShowMgBox() {
  box = getElem("id","mgBox","");
  par = this.textfieldhandle;
  x = findPosX(par);
  y = findPosY(par);
  box.style.top=y+par.offsetHeight;
  box.style.left=x;
  box.style.visibility = "visible";
}
mgBox.prototype.showMgBox = MgShowMgBox;

function MgHideMgBox() {
  getElem("id","mgBox","").style.visibility = "hidden";
  theMgBox.isOpenAndFilled = false;
}
mgBox.prototype.hideMgBox = MgHideMgBox;

// iterate through all text fields, install handlers for
// all text fields with attribute "mgBox"
function MgInitMgBoxes() {

// This function was inspired by Mircho Mirev's cAutocomplete.autoInit()
//  mo /mo@momche.net/
//	Copyright (c) 2004 Mircho Mirev
//
  var nI = 0;
  var sLangAtt;
  var hTextField=null;

  var nInputsLength = document.getElementsByTagName( 'INPUT' ).length
  for( nI = 0; nI < nInputsLength; nI++ ) {
    if( document.getElementsByTagName( 'INPUT' )[ nI ].type.toLowerCase() == 'text' ) {
      sLangAtt = document.getElementsByTagName( 'INPUT' )[ nI ].getAttribute( 'mgBox' )
      if( sLangAtt != null && sLangAtt.length > 0 ) {
        //alert("i think i found one");
        hTextField=document.getElementsByTagName( 'INPUT' )[ nI ];
        //alert(hTextField.onfocus);
        hTextField.onfocus=theMgBox.onFocus;
        hTextField.onblur=theMgBox.onBlur;
        //alert(hTextField.onfocus);
      }
    }
  }

  // call hook if present
  if(typeof mgBox_onLoad_hook == 'function') {
    mgBox_onLoad_hook();
  }
}
mgBox.prototype.initMgBoxes = MgInitMgBoxes;


/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
////
////  the "main()" function
////
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
theMgBox = new mgBox();

// Attach onLoad handler...
if( window.attachEvent ) {
  window.attachEvent( 'onload', theMgBox.initMgBoxes )
} else if( window.addEventListener ) {
  window.addEventListener( 'load', theMgBox.initMgBoxes, false )
}

