//***************************************************
// all code and functions copyright 2002-2003 ( T W E E K ! )
// created by Ray Cauchi - ray@tweek.com.au - December 2002
//
//***************************************************

/*******************************************************************************
 * BROWSER DETECTION AND VERSION
 ******************************************************************************/
var MSIE = false;   // Is Internet Explorer
var MSIE_V = false; // IE Version

var ieIndex = navigator.userAgent.indexOf('MSIE');
if(ieIndex>=0 && navigator.userAgent.indexOf('Opera')<0)MSIE=true;
if (MSIE) MSIE_V = navigator.userAgent.substring(ieIndex+5,ieIndex+8);

/**
 * $
 * Returns array or a single element built from ID's or Object references, eg.
 * var a = $('elem1', 'elem2', myElement, myOtherElement);
 */
function $()
{
    var elems = new Array();
    for (var i = 0; i < arguments.length; i++)
    {
        var elem = arguments[i];
        if (typeof elem == 'string') elem = document.getElementById(elem);
        if (arguments.length == 1) return elem;
        elems.push(elem);
    }
    return elems;
}

// frame buster
if (window != top) top.location.href = location.href;

// custom error handler
onerror = handleErrors;

var msg = null;

function handleErrors(errorMessage, url, line)
{
	msg = "There was an error on this page.\n\n";
	msg += "An internal programming error may keep\n";
	msg += "this page from displaying properly.\n";
	msg += "Click OK to continue.\n\n";
	msg += "Error message: " + errorMessage + "\n";
	msg += "URL: " + url + "\n";
	msg += "Line #: " + line;
	alert(msg);
	return true;
}

// function to activate check URL button (Associated Documents)
function tweek_activate_checkurl(url)
{
	var thisbutton = document.lamodify.urlcheck;
	var thisurl = (url == '') ? document.lamodify.url : url;
	var exp = /^(((http(s?))|(ftp(s?)))\:\/\/)?(www.|[a-zA-Z].)[a-zA-Z0-9\-\.]+\.([a-z]{2,3})(\:[0-9]+)*(\/($|[a-zA-Z0-9\.\,\;\?\'\\\+&%\$#\=~_\-]+))*$/;
    var regex = new RegExp(exp);
    var result;
	result = regex.test(thisurl.value);
	thisbutton.disabled = (result == false) ? true : false;
}

// function to redirect to URL for checking (Associated Documents)
function tweek_url_check()
{
	var url = document.lamodify.url.value;
	tweek_popup(url, 'elastic', 500, 400);
}

// function to redirect to File for checking (Associated Documents)
function tweek_file_check(file)
{
	var url = cfgurlpub + 'download.php?id=' + file;
	tweek_popup(url, 'elastic', 500, 400);
}

// function to close popup window and redirect opener window
function tweek_close_popup(path)
{
	window.opener.location = cfgurl + path;
	window.close();
}

// function to 'cancel' from a selected admin area page
function tweek_do_cancel(twk_t,twk_te)
{
    // declare varibale to contain path
    var path;
    // determine which path to use
    switch (twk_t)
    {
        case 1: path = 'users/active.php'; break;
        case 2: path = 'document/viewall.php'; break;
        case 3: path = 'users/email.php'; break;
        case 4: path = 'submission/menu.php'; break;
        case 5: path = 'content/view.php?id='+twk_te; break;
        case 6: path = 'library/reallocate.php'; break;
        case 7: path = 'library/update.php'; break;
        case 8: path = 'authorities/reallocate.php'; break;
        case 9: path = 'authorities/viewall.php'; break;
        case 10: path = 'divisions/viewall.php'; break;
        case 11: path = 'glossary/search.php'; break;
        case 12: path = 'faq/viewall.php'; break;
        case 13: path = 'document/add.php'; break;
        case 14: path = 'emails/viewall.php?id='+twk_te; break;
        case 15: path = 'positions/viewall.php'; break;
        case 16: path = 'fields/viewall.php'; break;
        case 17: path = 'forms/viewall.php'; break;
        case 18: path = 'om/viewall.php'; break;
        case 19: path = 'review/view.php'; break;
        case 20: path = 'om/compare.php'; break;
        default: path = 'home.php';
    }
	// redirect to required page
	document.location.href = cfgurl + path;
}

// function to display popup window
function tweek_popup(twk_url, twk_ptype, twk_width, twk_height)
{
	var twk_options = '';
	var twk_win = '';
	if (twk_ptype == 'console') twk_options = 'resizable,height='+twk_height+',width='+twk_width;
	if (twk_ptype == 'fixed') twk_options = 'height='+twk_height+',width='+twk_width;
	if (twk_ptype == 'elastic') twk_options = 'toolbar,menubar,scrollbars,resizable,location,height='+twk_height+',width='+twk_width;
	twk_options = twk_options + 'screenX=66,screenY=66,left=66,top=66'
	twk_win = window.open(twk_url, 'twkwin', twk_options);
	if (window.focus) twk_win.focus;
	return false;
}

// function to select first form element
function tweek_put_focus(twk_f_ct, twk_e_ct)
{
	if (document.forms.length > 0)
	{
		if (!(document.forms[twk_f_ct].elements[twk_e_ct].options))
		{
			document.forms[twk_f_ct].elements[twk_e_ct].focus();
			document.forms[twk_f_ct].elements[twk_e_ct].select();
		}
		else
		{
			document.forms[twk_f_ct].elements[twk_e_ct].focus();
		}
	}
}

// function to go back one page
function tweek_do_goback() { history.back(); }

// function to either select or deselect a checkbox
// @param string twk_uc_form The name of the form containing the checkbox
// @param string twk_uc_field The name of the checkbox field
// @param int twk_mode 1 | 0 - do we CHECK (1) or UNCHECK (0)
// @param int twk_array 1 | 0 - array of fields (1) or single field (0)
function tweek_check(twk_uc_form, twk_uc_field, twk_mode, twk_array)
{
	if (twk_array == 0)
	{
		// create the document.form.field string
		var twk_thisbox = eval("document." + twk_uc_form + "." + twk_uc_field);

		// which mode do we use?
		if (twk_mode == 1)
		{
			// check the box
			if (twk_thisbox.checked == false) twk_thisbox.checked = true;
		}
		else
		{
			// uncheck the box
			if (twk_thisbox.checked == true) twk_thisbox.checked = false;
		}
	}
	else
	{
		// create the document.form.field string
		var twk_thisbox = eval("document." + twk_uc_form + "[\"" + twk_uc_field + "\"]");

		for (c = 0; c < twk_thisbox.length; c++)
		{
			if (twk_mode == 1)
			{
				// check each box
				if (twk_thisbox[c].checked == false) twk_thisbox[c].checked = true;
			}
			else
			{
				// uncheck each box
				if (twk_thisbox[c].checked == true) twk_thisbox[c].checked = false;
			}
		}
	}
}

// function to either select or deselect all checkboxes
// @param string twk_uc_form The name of the form containing the checkbox
// @param string twk_uc_field The name of the checkbox field
// @param int twk_mode 1 | 0 - do we CHECK (1) or UNCHECK (0)
function tweek_check_all(twk_uc_form, twk_uc_field, twk_mode)
{
	var objCheckBoxes = document.forms[twk_uc_form].elements[twk_uc_field];
	var countCheckBoxes = objCheckBoxes.length;
	if(!countCheckBoxes) objCheckBoxes.checked = twk_mode;
	else
		// set the check value for all check boxes
		for(var i = 0; i < countCheckBoxes; i++) objCheckBoxes[i].checked = twk_mode;
}

// function to deselect a droplist
// @param int twk_array 1 | 0 - array of fields (1) or single field (0)
function tweek_unselect(twk_us_form, twk_us_field)
{
	for (var i = 1; i < tweek_unselect.arguments.length; i++)
	{
		var twk_thisselect = eval("document." + twk_us_form + "." + tweek_unselect.arguments[i]);
		if (twk_thisselect) twk_thisselect.selectedIndex = 0;
	}
}

// function to deselect a multi-select droplist
function tweek_multi_unselect(twk_mus_form, twk_mus_field)
{
	var twk_thismselect = eval("document." + twk_mus_form + "[\"" + twk_mus_field + "\"]");
	for (var zCnt = 0; zCnt < twk_thismselect.options.length; zCnt++)
	{
		// check to see if each item is selected
		if (twk_thismselect.options[zCnt].selected) twk_thismselect.options[zCnt].selected = 0;
	}
}

// function to clear a textfield
function tweek_clearfield(twk_cf_form, twk_cf_field, twk_cf_call)
{
	var twk_thistext = eval("document." + twk_cf_form + "." + twk_cf_field);
	if (twk_cf_call.checked == true) {twk_thistext.focus();}
	else {twk_thistext.value = '';}
}

// function to limit text in textarea
function tweek_limit_textarea(twk_lt_field,twk_lt_limit)
{
  	var twk_result = true;
  	if (twk_lt_field.value.length >= twk_lt_limit) twk_result = false;
  	if (window.event) window.event.returnValue = twk_result;
	return twk_result;
}

// function to submit form once only
function tweek_submitone(twk_s_form)
{
	//if IE 4+ or NS 6+
	if (document.all || $)
	{
		//screen thru every element in the form, and hunt down "submit" and "reset"
		for (i = 0; i < twk_s_form.length; i++)
		{
			var tempobj=twk_s_form.elements[i];
			if (tempobj.type && (tempobj.type.toLowerCase() == "submit" || tempobj.type.toLowerCase() == "reset" || tempobj.type.toLowerCase() == "button"))
			tempobj.disabled=true
		}
	}
}

// MENU PAGE SUBMIT
var submit_dest = '';

function tweek_do_menuSubmit(formname, pagename)
{
	var myform = $(formname);
	myform.setAttribute('action', pagename);
	return;
}

// ***** XML_HTTP_Request Code ***** //
function avail_getHTTPObject()
{
	var xmlhttp;
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
	{
		try {xmlhttp = new XMLHttpRequest();}
		catch (e) {xmlhttp = false;}
	}
    else
    {
        try {xmlhttp = new ActiveXObject("MSXML2.XMLHTTP.3.0")}
        catch (e) {xmlhttp = false;}
    }
	return xmlhttp;
}

function avail_handleHTTPResponse()
{
	if (avail_http.readyState == 4)
	{
		if (avail_http.status == 200)
		{
			var section = $('check_avail');
			if (section) section.innerHTML = avail_http.responseText;
		} else {
			alert("There was a problem retrieving the XML data:\n" + avail_http.statusText);
		}
	}
}

function avail_process()
{
	// Process
	var object = $('check_avail');
	object.innerHTML = '<em>Refreshing... Please Wait!</em>';
	avail_http.open('POST', cfgurl + 'document/add.check.php', true);
	avail_http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	avail_http.onreadystatechange = avail_handleHTTPResponse;
	var send_data = 'p_avail=1&check_id=' + $('reference').value;
	avail_http.send(send_data);
}

function avail_init_process()
{
	avail_http.open('POST', 'document/add.check.php', true);
	avail_http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	avail_http.onreadystatechange = avail_handleHTTPResponse;
	avail_http.send(null);
}

// *** Edit Policy Summary Code *** //
function show_text(id)
{
	// Reference the objects
	label = $('summary' + id);
	text  = $('summarytext' + id);
	button = $('summarybutton' + id);
	p = $('p');
	// Change the object values
	if (navigator.userAgent.indexOf("MSIE") > -1)
	{
		label.style.display='none';
		text.style.display='';
		var control = text.appendChild(document.createElement('textarea'));
			control.setAttribute('name', 'summarytext');
			control.setAttribute('id', 'summarytext');
			control.setAttribute('cols', '20');
			control.setAttribute('rows', '10');
			control.setAttribute('value', label.innerHTML);
			control.style.width = '99%';
	} else {
		text.innerHTML = '<textarea style="width:99%;" name="summarytext" cols="20" rows="10">' + label.innerHTML + '</textarea>';
		text.setAttribute('style', '');
		label.setAttribute('style', 'display: none;');
	}
	p.value = id;
	button.innerHTML = '<input style="width:80px; margin:2px;" type="submit" name="' + id + '" value="Update" /><br />' +
					   '<input style="width:80px; margin:2px;" type="button" value=" Cancel" onclick="hide_text(' + id + ');" />';
}

function hide_text(id)
{
	// Reference the objects
	label = $('summary' + id);
	text  = $('summarytext' + id);
	button = $('summarybutton' + id);

	// Change the object values
	if (navigator.userAgent.indexOf("MSIE") > -1) {label.style.display='';}
    else {label.setAttribute('style', '');}
	text.innerHTML = '';
	button.innerHTML = '<input type="button" name="edit' + id + '" value="Edit Summary" onclick="show_text(' + id + ');" />';
}

function skip_process(loc)
{
	var msg = 'You are about to skip this stage of the approval process.\n\nAre you sure you want to continue?';
	if (confirm(msg) == false) return false;
	document.location = loc;
	return true;
}

// REPORTS RELATED FUNCTION //
function run_report(type)
{
	var url = cfgurl + 'reports/display.php?t=' + type;
	if (type == 5) url += '&docid=' + $('report_docs').value;
	tweek_popup(url, 'elastic', 800, 600);
}

function tweek_check_all_pdf(twk_uc_form, twk_mode)
{
	for (i = 0; i < document.forms[twk_uc_form].elements.length; i++)
	{
		if (document.forms[twk_uc_form].elements[i].type == 'checkbox')
		{
			document.forms[twk_uc_form].elements[i].checked = (twk_mode == 1)
				 ? true : false;
		}
	}
}

// Collapse a table section
function sectionCollapse(index)
{
    var icon = $('collapse'+index);
    var section = $('section'+index);
    var heading = $('heading'+index);

    if (icon.className == "sectionCollapse")
    {
        icon.className = "sectionExpand";
        icon.alt = "[+]";
        icon.title = "Expand Section";
        section.style.display = "none";
        heading.style.color = "#aaaaaa";
    }
    else
    {
        icon.className = "sectionCollapse";
        icon.alt = "[-]";
        icon.title = "Collapse Section";
        section.style.display = "";
        heading.style.color = "#003399";
    }
    icon.src = "images/" + icon.className + ".gif";
}

// BBS/BBSALT REPORTING RELATED FUNCTIONS //
// Triggered when the "Cancel" button is clicked during the BBS Reporting
function bbsReportCancel()
{
    if (confirm("Are you sure you want to cancel this report?\n\nAll entered information will be lost.")) tweek_do_cancel();
}

// Triggered when the "Back" button is clicked during the BBS Reporting
function bbsReportBack(step)
{
    if ($('back')) $('back').value = 1;
    $('reportBBS').submit();
}

// Triggered when the user clicks on either a "Report on All Answers" or on an
// individaul answer. It's purpose is to toggle the selections on and off so
// that the user cannot select "All" and individual answers.
function bbsReportAll(event,bool)
{
    // Valid Event?
    if (!event) event = window.event;

    // Reference the Object that fired the event
    var target = (event.srcElement) ? event.srcElement : event.target;
    if (!target.parentNode) return false;
    var elems = target.parentNode.getElementsByTagName('option');
    if (!bool)
    {
        if (elems[0]) elems[0].selected = false;
    }
    else
    {
        for (var i = 1; i < elems.length; i++) elems[i].selected = false;
    }
}

// Select/Clear all children of "elem"
function bbsSelectAll(elem,bool,group)
{
    if (group)
    {
        // Option Group
        var nodes = $(elem).getElementsByTagName("optgroup");
        for (var i = 0; i < nodes.length; i++)
        {
            for (var ii = 0; ii < nodes[i].childNodes.length; ii++)
            {
                try {nodes[i].childNodes[ii].selected = (ii == 0) ? bool : 0;}
                catch (e) {}
            }
        }
    }
    else
    {
        // Option
        if (!$(elem) || !$(elem).options) return;
        var nodes = $(elem).options;
        for (var i = 0; i < nodes.length; i++) nodes[i].selected = bool;
    }
}

function bbsReportUseMethod(method)
{
    for (i = 1; i <= 3; i++)
    {
        if ($('method_'+i).parentNode)
            $('method_'+i).parentNode.className = (method == i)
                ? "useMethodSelected"
                : "useMethod";
    }
}

// function to submit form once only
// Customized for BBS Reporting page, unknown error generated in normal function
function tweek_submitone_bbs(twk_s_form)
{
    //if IE 4+ or NS 6+
    if (document.all || $)
    {
        //screen thru every element in the form and disable "submit" and "reset"
        var elems = $(twk_s_form).getElementsByTagName("input");
        for (i = 0; i < elems.length; i++)
        {
            var objRef = elems[i];
            var objType = elems[i].type.toLowerCase();
            if(objType == "submit" || objType == "reset" || objType == "button")
            objRef.disabled=true
        }
    }
}

// Create a new Form Field Response Option textbox
function addFieldResponse(parentName)
{
    var parent = $((!parentName) ? 'respOptions' : parentName);

    // Get the first div container
    var newNodes = parent.getElementsByTagName("DIV")[0];
    
    // Clone the nodes
    parent.appendChild(newNodes.cloneNode(true));

    // Clear content and set focus
    var clone = parent.getElementsByTagName("DIV");
    	clone = clone[clone.length-1];
    var elems = clone.getElementsByTagName("INPUT");
    	elems[0].value = "0";
    	elems[1].value = "";
    	elems[1].focus();
}

// Changes the caption for the form content select/edit button
function formInfoTypeChange(id)
{
	// Use the default ID of "New"
    if (id === undefined) id = "New"
    var enableInsert = true;
    var validContent = true;

	// Change the button caption and disbaled if no type is selected.
	if ($('editContent_'+id) && $('info_'+id)) {
		switch ($('info_'+id).value) {

			case "part":
				$('editContent_'+id).value = "Edit Content";
				$('editContent_'+id).disabled = "";
				if ($('part_'+id).value == "") validContent = false;
				$('layout_'+id).value = "horizontal";
				var selected = $('part_'+id).value;
				if (selected.length > 30) {
					selected = selected.substring(0,27) + "...";
				}
				if (selected) selected = '<em>"'+selected+'"</em>';
				break;

			case "field":
				$('editContent_'+id).value = "Select Field";
				$('editContent_'+id).disabled = "";
				if ($('field_'+id).value == "") validContent = false;
				var selected = "&nbsp;";
				if ($('field_'+id).value) {
					var options = $('fieldNames').getElementsByTagName("OPTION");
					for (i = 0; i < options.length; i++) {
						if (options[i].value == $('field_'+id).value) {
							selected = options[i].text;
						}
					}
				}
				break;

			default:
				$('editContent_'+id).disabled = "disabled";
				var selected = "&nbsp;";
				enableInsert = false;
		}
	}

	// Update the heading text or field name
	$('fieldSelected_'+id).innerHTML = selected;

	// Is a layout option selected?
	if ($('layout_'+id).value == "") enableInsert = false;

	// Enable or Disabled the "Insert" button?
	if (id == "New")
		$('insert_New').disabled = (enableInsert && validContent)
			? ""
			: "disabled";

	// Is the content valid?
	$('valid_'+id).src = (validContent && $('info_'+id).value != "")
		? "images/yes_white.gif"
		: "images/no_white.gif";
}

// Create a popup window to allow the user to change/edit the form content
function formEditContent(id)
{
	// Create a popup window
	var twk_win = window.open(
		(MSIE) ? 'content.php?id='+id : 'forms/content.php?id='+id,
		'twkwin',
		'resizable,height=300,width=400,screenX=66,screenY=66,left=66,top=66'
	);

	// Set focus on new window
	if (window.focus && twk_win.focus) twk_win.focus;
}

function formContentLoad()
{
	// Get the ID from the GET array
	var id = getURLParam("id");

	// Are we Selecting or Editing?
	switch (window.opener.document.getElementById('info_'+id).value) {

		case "part":
			$('part').value = window.opener.document.getElementById('part_'+id).value;
			$('field').style.display = "none";
			$('part').style.display = "block";
			$('part').focus();
			break;

		case "field":
			$('field').value = window.opener.document.getElementById('field_'+id).value;
			$('field').style.display = "block";
			$('field').style.width = "99%";
			$('part').style.display = "none";
			$('field').focus();
			break;
	}
}

// Update the form content from the data entered in the popup window
function formUpdateContent()
{
	// Get the ID from the GET array
	var id = getURLParam("id");

	// Are we Selecting or Editing?
	switch (window.opener.document.getElementById('info_'+id).value) {

		case "part":
			window.opener.document.getElementById('part_'+id).value = $('part').value;
			$('field').style.display = "none";
			$('part').style.display = "block";
			break;

		case "field":
			window.opener.document.getElementById('field_'+id).value = $('field').value;
			$('field').style.display = "block";
			$('field').style.width = "99%";
			$('part').style.display = "none";
			break;
	}

	window.opener.formInfoTypeChange(id);
	window.close();
}

// Helper function to return a GET parameter
function getURLParam(paramName)
{
	var strReturn = "";
	var strHref = window.location.href;
	if (strHref.indexOf("?") > -1 ) {
		var strQueryString = strHref.substr(strHref.indexOf("?"));
		var aQueryString = strQueryString.split("&");
		for (var iParam = 0; iParam < aQueryString.length; iParam++ ) {
			if (aQueryString[iParam].indexOf(paramName + "=") > -1 ) {
				var aParam = aQueryString[iParam].split("=");
				strReturn = aParam[1];
				break;
			}
		}
	}
	return unescape(strReturn);
}

// Add a new table row containing all the form content entered by the user
function formAddContent()
{
	// Setup
	var table = $('currentContent');
	var newNode = $('sourceRow').cloneNode(true);
		newNode.id = "";
	var newID = 0;

	table = table.getElementsByTagName("TBODY")[0];

	for (i = 0; i < table.childNodes.length; i++) {
		if (table.childNodes[i].nodeType == 1) newID++;
	}

	for (i = 0; i < newNode.childNodes.length; i++) {
		if (newNode.childNodes[i].tagName == "TD") {
			// If node is an TD element
			for (e = 0; e < newNode.childNodes[i].childNodes.length; e++) {
				if (newNode.childNodes[i].childNodes[e].nodeType == 1) {
					if (newNode.childNodes[i].childNodes[e].id.indexOf("_0") > 0) {
						// Update the new elements ID
						newNode.childNodes[i].childNodes[e].id =
							newNode.childNodes[i].childNodes[e].id.replace(/_0/g, "_"+newID);
					}
				}
			}
		}
	}

	// Append the new nodes
	table.appendChild(newNode);

	// Configure the new nodes
	$('info_'+newID).value = $('info_New').value;
	$('part_'+newID).value = $('part_New').value;
	$('field_'+newID).value = $('field_New').value;
	$('layout_'+newID).value = $('layout_New').value;

	$('p').value = 1;
	tweek_submitone($('formFields'));
	$('formFields').submit();
}

// Delete a table row and commit changes
function formDeleteRow(id)
{
	// Validate and Confirm
	if (!id || !confirm("Are you sure you want to remove this content?\n\nNote: You cannot undo this action."))
		return false;

	// Remove the Table Row
	var row = $('info_'+id).parentNode.parentNode;
	row.parentNode.removeChild(row);

	// Submit the form to commit the changes
	$('p').value = 1;
	tweek_submitone($('formFields'));
	$('formFields').submit();
}

// Move a table row elemets up or down
function formMoveRow(id, direction)
{
	// Compose the elements array
	var newID = false;
	var elems = new Array();
		elems[0] = "info_";
		elems[1] = "part_";
		elems[2] = "field_";
		elems[3] = "layout_";

	if (direction && direction == "up") {
		if (id > 1) newID = (id - 1);
	} else {
		if ($(elems[0]+(id + 1))) newID = (id + 1);
	}

	if (!newID) return false;
	for (var i = 0; i < elems.length; i++) {
		// Store
		var temp = $(elems[i]+id).value;
		// Copy
		$(elems[i]+id).value = $(elems[i]+newID).value;
		// Restore
		$(elems[i]+newID).value = temp;
	}

	formInfoTypeChange(id);
	formInfoTypeChange(newID);
}

// Open a popup window and preview the current form content
function formPreview()
{
	$('p').value = 1;
	$('preview').value = 1;
	$('formFields').submit();
}

// Submits the form and goes Back
function formGoBack()
{
	$('p').value = 1;
	$('back').value = 1;
	$('formFields').submit();
}

// Load the popup preview window
function formShowPreview()
{
	// Create a popup window
	var twk_win = window.open(
		(MSIE) ? 'preview.php' : 'forms/preview.php',
		'twkwin',
		'toolbar,menubar,scrollbars,resizable,location,height=600,width=900'
	);

	// Set focus on new window
	if (twk_win && window.focus && twk_win.focus) twk_win.focus;
}

// Add a dynamic OM Form Field element
function omAddField(event, id, useRow)
{
	// Get the event target
    if (!event) event = window.event;
    var target = (event.srcElement) ? event.srcElement : event.target;
    var table = (useRow)
    	? target.parentNode.parentNode
    	: target.parentNode.parentNode.parentNode.parentNode;
    var nextSib = table.nextSibling;

	var buttonID = id+"-Add";
	var sourceID = id+"-0";
	var sourceName = id+"[]";
	var parent = $(sourceID).parentNode;

	if (!$(sourceID)) return false;

	// Clone the field
	var useTagName = $(sourceID).tagName;
	switch (useTagName) {

		case "TABLE":
		case "TR":
			// Get the current count of children
			var children = parent.getElementsByTagName($(sourceID).tagName);
			var childCount = children.length;

			// Configure the new element
			var field = $(sourceID).cloneNode(true);
				field.id = id+"-"+childCount;

			// If this is a matrix then reset ID's
			if (useTagName == "TR") {
				// RADIO BUTTONS
				if (MSIE) {
					/**
					 * If we are in that useless browser (IE) we need to create
					 * 2 arrays. The first stored the elements that we need to
					 * remove. The second stored the new elements we need to add.
					 * We are doing this because IE can't handle adding <INPUT>
					 * elements into the DOM with a type="" value set, hence we
					 * need to create the element using the old archaic method.
					 * If we don't do this, IE will correctly display the
					 * element, but it won't be clickable!
					 */
					deleteNodeList = new Array();
					addNodeList = new Array();
				}
				var subElems = field.getElementsByTagName("INPUT");
				for (var i = 0; i < subElems.length; i++) {
					if (subElems[i].type && subElems[i].type == "radio") {
						var curID = subElems[i].id.split("-");
						var newName = curID[0]+"-"+curID[1]+"-"+curID[2]+"-"+childCount;
						var newID = newName+"-"+curID[4];

						if (MSIE) {

							/**
							 * Store the current cloned radio button and create
							 * a new element to replace it with.
							 */
							var newVal = subElems[i].value;
							var nodeParent = subElems[i].parentNode;
							var newNode = document.createElement("<input type=\"radio\" name=\""+newName+"\" id=\""+newID+"\" value=\""+newVal+"\" />");

							deleteNodeList[deleteNodeList.length] = subElems[i];
							addNodeList[addNodeList.length] = newNode;

						} else {
							// "Real" web browsers can handle this simple code
							subElems[i].id = newID;
							subElems[i].name = newName;
						}
					}
				}
				if (MSIE) {
					/**
					 * Delete the cloned radio buttons and replace them with
					 * the IE specific versions.
					 */
					for (var i = 0; i < deleteNodeList.length; i++) {
						var nodeParent = deleteNodeList[i].parentNode;
							nodeParent.removeChild(deleteNodeList[i]);
							nodeParent.appendChild(addNodeList[i]);
					}
				}
			}

			// Reset all elements
			field = omClearFields(field);

			// Add the element to the end
			parent.appendChild(field);

			// if the "add" button was not on the last table, we need to move
			// all content down so that the new table is inserted where it
			// is expected to.
			if (nextSib) {
				var thisOne = $(id+"-"+childCount);
				var nextOne = false;
				while (thisOne.previousSibling && thisOne.previousSibling.id != table.id) {
					if (thisOne.tagName == useTagName) {
						var sibTest = om_findPreviousSibling(thisOne.previousSibling);
						if (sibTest.tagName) omCopyFields(sibTest, thisOne);
					}
					thisOne = thisOne.previousSibling;
				}
				omClearFields(om_findNextSibling(thisOne));
			}

			if ($(id+"-"+childCount).focus) $(id+"-"+childCount).focus();
			break;

		default:
			alert($(sourceID).tagName);
			// Do Nothing -- Unknown Field
	}
}

function omDeleteField(event, id, useRow)
{
	// Get the event target
    if (!event) event = window.event;
    var target = (event.srcElement) ? event.srcElement : event.target;

    // Prepare the variables
	var buttonID = id+"-Add";
	var sourceID = id+"-0";
	var sourceName = id+"[]";
	var parent = $(sourceID).parentNode;
	var siblings = (useRow)
		? parent.getElementsByTagName("TR")
		: parent.getElementsByTagName("TABLE");
	var table = (useRow)
		? target.parentNode.parentNode
		: target.parentNode.parentNode.parentNode.parentNode;

	if (!$(sourceID) || !table.id) return false;

	// Is this an only child?
	if (siblings.length == 1) {

		// This is the only row, don't delete
		omClearFields(table);
		return;

	} else {

		var thisOne = table;
		var nextOne = false;
		while (thisOne.nextSibling) {
			if (thisOne.tagName == "TABLE" || (useRow && thisOne.tagName == "TR")) {
				omCopyFields(om_findNextSibling(thisOne.nextSibling), thisOne);
			}
			thisOne = thisOne.nextSibling;
		}

		// Delete the last table element
		table.parentNode.removeChild(om_findPreviousSibling(parent.lastChild));

	}
}

// Clear all input, textarea and select boxes.
function omClearFields(field)
{
	// INPUT
	var elems = field.getElementsByTagName("INPUT");
	for (var i = 0; i < elems.length; i++) {
		if (elems[i].type == "text") elems[i].value = "";
		if (elems[i].type == "radio" || elems[i].type == "checkbox")
			elems[i].checked = "";
	}

	// TEXTAREA
	var elems = field.getElementsByTagName("TEXTAREA");
	for (var i = 0; i < elems.length; i++) elems[i].value = "";

	// SELECT
	var elems = field.getElementsByTagName("SELECT");
	for (var i = 0; i < elems.length; i++) elems[i].value = 0;

	return field;
}

// Copy all values from one table to another
function omCopyFields(copyFrom, copyTo)
{
	// INPUT
	if (!copyTo.getElementsByTagName) return;
	if (!copyFrom.getElementsByTagName) return;
	var elemsTo = copyTo.getElementsByTagName("INPUT");
	var elemsFrom = copyFrom.getElementsByTagName("INPUT");
	for (var i = 0; i < elemsTo.length; i++) {
		if (elemsTo[i].type == "text") {
			elemsTo[i].value = elemsFrom[i].value;
		}
		if (elemsTo[i].type == "radio") {
			elemsTo[i].checked = elemsFrom[i].checked;
		}
	}

	// TEXTAREA
	var elemsTo = copyTo.getElementsByTagName("TEXTAREA");
	var elemsFrom = copyFrom.getElementsByTagName("TEXTAREA");
	for (var i = 0; i < elemsTo.length; i++) {
		elemsTo[i].value = elemsFrom[i].value;
	}

	// SELECT
	var elemsTo = copyTo.getElementsByTagName("SELECT");
	var elemsFrom = copyFrom.getElementsByTagName("SELECT");
	for (var i = 0; i < elemsTo.length; i++) {
		if (elemsTo[i] && elemsFrom[i] &&
			elemsTo[i].value && elemsFrom[i].value) {
			elemsTo[i].value = elemsFrom[i].value;
		}
	}
}

// Adds a new form row to the add/edit om form
function omforms_addForm(event, elem)
{
	// Get the event target
    if (!event) event = window.event;
    var target = (event.srcElement) ? event.srcElement : event.target;
    if (!elem || !$(elem)) elem = 'omForms';
	var sourceElem = $(elem).getElementsByTagName("TABLE")[0];
	var table = target.parentNode.parentNode.parentNode.parentNode;

	// Clone and configure the new element
	var newElem = sourceElem.cloneNode(true);
	
	if (elem == "omForms") {
		var newSelect = newElem.getElementsByTagName("SELECT")[0];
			if (newSelect.value) newSelect.value = 0;
	} else {
		var newSelect = newElem.getElementsByTagName("INPUT")[0];
			if (newSelect.value) newSelect.value = "";
	}

	// Add the table
	var inBefore = table;
	while (inBefore.nextSibling) {
		inBefore = inBefore.nextSibling;
		if (inBefore.tagName == "TABLE") break;
	}
	if (inBefore == table) {
	 	// Append
	 	$(elem).appendChild(newElem);
	} else {
		// Insert
		$(elem).insertBefore(newElem, inBefore);
	}

	// Focus the new element
	if (newSelect.focus) newSelect.focus();
}

// Delete an OM Form
function omforms_deleteForm(event, elem)
{
	// Get the event target
    if (!event) event = window.event;
    var target = (event.srcElement) ? event.srcElement : event.target;
    var table = target.parentNode.parentNode.parentNode.parentNode;
    var parent = table.parentNode;

    if (parent.getElementsByTagName("TABLE").length == 1) {

    	// This is the last table, clear don't delete
    	if (!elem) {
    		table.getElementsByTagName("SELECT")[0].value = 0;
		} else {
    		table.getElementsByTagName("INPUT")[0].value = "";
		}

	} else {

		// Delete table
		parent.removeChild(table);

	}
}

function omforms_moveRow(event, direction, elem)
{
	// Get the event target
	if (!elem) elem = "omForms";
    if (!event) event = window.event;
    var target = (event.srcElement) ? event.srcElement : event.target;
    var table = target.parentNode.parentNode.parentNode.parentNode;
    var parent = table.parentNode;

    // Validate direction
	if (!direction || direction != "up") direction = "down";

	// Move
	var found = false;
	var sibling = table;
	switch (direction) {

		case "up":
			// does this element have a previous sibling
			while (sibling.previousSibling) {
				sibling = sibling.previousSibling
				if (sibling.tagName == "TABLE") {
					found = true;
					break;
				}
			}
			break;

		case "down":
			// does this element have a next sibling
			while (sibling.nextSibling) {
				sibling = sibling.nextSibling
				if (sibling.tagName == "TABLE") {
					found = true;
					break;
				}
			}
			break;
	}

	if (found) {
		if (elem == "omForms") {
			var storage = table.getElementsByTagName("SELECT")[0].value;
			table.getElementsByTagName("SELECT")[0].value =
				sibling.getElementsByTagName("SELECT")[0].value;
			sibling.getElementsByTagName("SELECT")[0].value = storage;
		} else {
			var storage = table.getElementsByTagName("INPUT")[0].value;
			table.getElementsByTagName("INPUT")[0].value =
				sibling.getElementsByTagName("INPUT")[0].value;
			sibling.getElementsByTagName("INPUT")[0].value = storage;
		}
	}
}

// Display an on screen prompt informing users of a System Lock Down
function system_promptLockDown(userName)
{
	// Extract the firstname
	var fname = userName.split(" ")[0];
	alert(
		"Attention "+fname+",\n\n"+
		"A systems administrator is attempting to publish an Outcome Measure. In order to complete this process they have initiated a System Lock Down which requires all current users to log out of the administration area.\n\n"+
		"Please finalise and save anything you are currently working on and log out of the system as soon as possible by clicking the 'Logout' link in the navigation tree to the left.\n\n"+
		"You will be notified via the administration login page when the Lock Down is lifted and you can resume your work.\n\n"+
		"Thank you for your cooperation."
	);
}

// Automatically selects the appropriate Number of Responses for specific fields
// Triggered everytime a user changes the Data Entry Field Type
function fields_checkType()
{
	switch ($('type').value) {

		case "checkbox":
		case "radio":
		case "matrix":
		case "rank":
			$('numresp').value = 1;
			break;

	}
}

// Confirms the cancellation of the data entry process of an OM
function om_entryCancel()
{
	if (confirm("Are you sure you want to cancel?\n\nAny unsaved information will be lost."))
		tweek_do_cancel(18,0);
}

// Find next valid sibling node
function om_findNextSibling(node)
{
	while (!node.tagName && node.nextSibling) {
		node = node.nextSibling;
	}

	return node;
}

// Find previous valid sibling node
function om_findPreviousSibling(node)
{
	while (!node.tagName && node.previousSibling) {
		node = node.previousSibling;
	}

	return node;
}

// Executes an AJAX call to create a new Organisation
function users_addOrganisation()
{
	// Process
	var date = new Date();
	var params = "orgName="+$('newOrg').value+"&timestamp="+date.getTime();
	var AJAX = new XMLHttpRequest();
	document.getElementsByTagName('body')[0].style.cursor = "wait";
	AJAX.execute(cfgurl+"users/ajax_org.php",
		params, function(){
			if (AJAX.responseText == "exists") {
				// Organisation already exists
				alert("An Organisation by that name already exists. Please provide a unique Organisation Name.");
			} else {
				if (AJAX.responseText == false) {
					// Failed to add new Organisation
					alert ("Failed to add new Organsiation! Please try again");
				}
				else {
					// Success
					if (!$('orgs')) {
						// Create the select box
						var orgs = document.createElement("SELECT");
							orgs.name = "orgs[]";
							orgs.id = "orgs";
							orgs.multiple = "multiple";
							orgs.size = "10";
						$('orgsList').insertBefore(
							orgs,
							$('orgsList').childNodes[0]
						)
					}
					if ($('orgs')) {
						// Add option to list and select it
						var newOrg = document.createElement("OPTION");
							newOrg.value = AJAX.responseText;
							newOrg.innerHTML = $('newOrg').value;
							newOrg.selected = "selected";

						if (newOrg) $('orgs').appendChild(newOrg);
					}
					$('newOrg').value = "";
					$('newOrgAdd').disabled = "disabled";
				}
			}
		}, function (){
			alert ("Failed to add new Organsiation! Please try again");
		}, function (){
			document.getElementsByTagName('body')[0].style.cursor = "default";
		});
}

// Enables/Disables the add organisation button depending on if the form
// information is valid.
function users_validOrganisation()
{
	// Validate
	if (!$('newOrg') || !$('newOrg').value) {
		$('newOrgAdd').disabled = "disabled";
		return false;
	}

	$('newOrgAdd').disabled = "";
}
