/*
COMMON SCRIPT
Doc: 			Globally accessible generic functions
Use: 			See each function for a usage description
Dependencies: 	<none>
Created: 		16/March/2005
*/

var list_checkboxes_selected = 0;

var extData;
var extDataTimer;
var ratingSetAllowed = true;
var data_transport = false;
var popup_over = false;
var popup_interval = "";
var last_popup = "";
var last_sublink = "";

var TRYCOUNT = Array();
TRYCOUNT["show_toolbutton"] = 0;
TRYCOUNT["hide_toolbutton"] = 0;
TRYCOUNT["init_listboxes"] = 0;

var SUBLINK_OVER = false;
var SUBLINK_TIMEOUT = "";

function show_cv2() {
	document.getElementById("cv2").className = "show";
}
function hide_cv2() {
	document.getElementById("cv2").className = "";
}

function go_url(url) {
	if (url != "")
	location.href = url;
}

function pop(url, margin, width, height) {
	if (margin == "") margin == "0";
	if (width == "" || isNaN(width)) width == "400";
	if (height == "" || isNaN(height)) height == "500";
	
	var qs = "-/margin/" + margin + "/";
	var win_features = "width=" + width + ", height=" + height + ", resizable=no, scrollbars=auto";
	
	window.open(url + qs, "", win_features);
	return false;
}

function dataInsert(form, data, function_call) {
	//fills the global array extData with the passed data, and re-enables the 
	//active form, then calls the requested callback function
	extData = data;
	eval(function_call);
	window.clearTimeout(extDataTimer);
	removeStatusIcon("dataTransportStatus");
	enable_all_elements(document.forms[form]);
}

function create_data_transport() {
	if (!data_transport) {
		data_transport = document.createElement("iframe");
		data_transport.src = "about:blank";
		data_transport.name = "dataTransport";
		data_transport.className = "dataTransport";
		document.body.appendChild(data_transport);
		return data_transport;
	} else {
		return data_transport;
	}
}

function getExtData(form, src) {
	//loads src into the dataTransport iframe, and starts the warning timer	
	
	//create iframe
	data_transport = create_data_transport();
	
	if (data_transport) {
		disable_all_elements(document.forms[form]);
		
		//this is the status image for cross-site and external data collection. it will dissapear when the data is retreived		
		addStatusIcon("dataTransportStatus", "Loading External Data...",
						"/_icons/16_anim/loading_16.gif", "");
		
		extDataTimer = window.setTimeout("getExtDataWarning()", (30*1000));
		data_transport.src = src;
	} else {
		alert("The data transport panel was not found.");
	}
}

function getExtDataWarning() {
	//sends an alert to the user when the external data collection is taking too long
	alert("External data is required to complete this form, and is taking longer than expected to load. Please close this form and reopen. If the problem persists, check your connection.");
}

function print_list() {
	//guess what this does?
	window.focus();
	window.print();
}

function get_abstract(string, chars, use_end) {
	if (use_end) { endchar = " " + use_end; } else { endchar = ""; }
	if (string.length > chars) { string = string.substring(0, chars); string = string + "..."; } else { string = string + endchar; } 
	return string;
}

function reload_listpane() {
	//tries to find a listpane and reloads the data within it.
	//this function should be called from a popup only. otherwise it won't work, ok?
	
	//first, try to find an opener:
	if (parent_win = window.top.opener.top) {
		if (contentPane = parent_win.contentShell.contentMain) {
			contentPane.location.reload();
		} else if (contentPane = parent_win.contentMain) {
			contentPane.location.reload();		
		}
	}
}

function confirm_url(confirmation, url, frameset) {
	//navigates the FRAMESET to a URL after confirming CONFIRMATION, with the rd parameter filled in
	confirmation = confirmation.replace(/%recordname/, top.CURRENT_SELECTED_OBJ.recordname);
	confirmation = confirmation.replace(/%recordid/, top.CURRENT_SELECTED_OBJ.recordid);
	if (confirm(confirmation)) {
		if (frameset) {
			frameset.location.href = url + "&rd=" + escape(frameset.location.href);
		} else {
			location.href = url + "&rd=" + escape(location.href);
		}
	}
}

function get_url(url, frameset) {
	//navigates the FRAMESET to a URL, with the rd parameter filled in
	if (frameset) {
		frameset.location.href = url + "&rd=" + escape(frameset.location.href);
	} else {
		location.href = url + "&rd=" + escape(location.href);
	}
}

function img_swap(image_id, src) {
	/*switches an image with ID (image_id) to [src]*/
	if (image_obj = document.getElementById(image_id)) {
		if (!src || src == "") {
			image_obj.src = "/images/blank.gif";
		} else {
			image_obj.src = src;
		}
	}
}

function img_on(image_id, ext) {
	/*switches an image with ID (image_id) to [src]1.(ext)*/
	if (image_obj = document.getElementById(image_id)) {
		image_obj.src = image_obj.src.substr(0, image_obj.src.length-4) + "1." + ext;
	}
}

function img_off(image_id, ext) {
	/*switches an image with ID (image_id) to [src].(ext)
	(removing the "1")*/
	if (image_obj = document.getElementById(image_id)) {
		if (image_obj.src.lastIndexOf("1." + ext) > -1) {
			image_obj.src = image_obj.src.substr(0, image_obj.src.length-5) + "." + ext;
		}
	}
}

function obj_select(e, obj_name, class_name, record_id, record_name, section_id, link_url, tool_exclusions) {
	/*selects an object, changing the classname if specified, and setting
	the globally accessible variables for the currently selected object id,
	data id, data name and classname
	
	tool_exclusions should be defined as an associated array, for which the syntax within a function
	call is as follows:
	{ array_element_name : val, ... }
	for example:
	{ edit_client : 1 }
	this will cause the button with ID of "edit_client" to not highlight when the object is selected
	*/

	if (top.CURRENT_SELECTED_OBJ != null) {
		//old object turn off!
		top.CURRENT_SELECTED_OBJ.className = top.CURRENT_SELECTED_OLDCLASS;
		if (append_row = document.getElementById("append_" + top.CURRENT_SELECTED_OBJ.id)) {
			append_row.className = "dobjRowHidden";
		}
	}
	
	if (obj_name == "") {
		top.set_current_class("");
		top.set_current_obj("");
		return;
	}
	
	if (object = document.getElementById(obj_name)) {
		if (top.set_current_class) {
			top.set_current_class(object.className);
			object.className = class_name;
			
			if (append_row = document.getElementById("append_" + obj_name)) {
				append_row.className = "dobjRowAppend";
			}
			
			object.recordname = record_name;
			object.recordid = record_id;
			object.section_id = section_id;

			//if there's a select wizard in the top frameset, run it's function
			if (parent.parent.selectWizard) {
				if (parent.parent.selectWizard.section_based_display) {
					parent.parent.selectWizard.section_based_display(section_id)
				}
			}
			
			if (link_url) {
				object.link_url = link_url;
			}
			
			if (!tool_exclusions) {
				object.tool_exclusions = new Array(0);
			} else {
				object.tool_exclusions = tool_exclusions;
			}
			
			top.set_current_obj(object);
			
			//select the checkbox, unselect all others
			var check_box = "";
			if (check_box = document.getElementById("listChk" + record_id)) {
				clear_listboxes();
				check_box.checked = true;
				toolbar_sense_listboxes(null, 'listForm', top.contentShell.contentMain, true);
			}
			
			//clear the chksel element, if it exists
			settingsform = document.forms['settingsForm'];
			
			if (chksel = settingsform.elements['chksel']) {
				chksel.value = "";
				top.GLOBAL_LISTBOXES_CHECKED = 0;
			}
			
			//set listboxes variable to 1 (only 1 item is checked now)
			top.LISTBOXES_CHECKED = 1;
		}
	} else {
		//object being unselected
		top.set_current_class("");
		top.set_current_obj("");
	}
	
	if (!e) var e = window.event;
	if (e) {
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();
	}
}

function setting_set(var_name, var_value, redir, frame_obj) {
	/*redirects to the generic session settings page, which sets session variables, surprisingly
	var_name: session variable to set
	var_value: value to give the variable
	redir: page to redirect to
	frame_obj: frame to open the redirected page in*/
	frame_obj.location.href = "/pm3/setting_set.php?var=" + var_name + "&val=" + var_value + "&redir=" + redir;
}

function form_settings_change(var_name, var_value, reset_other_vals, nopost) {
	if (formobj = document.forms['settingsForm']) {
		if (element = formobj.elements[var_name]) {
			element.value = var_value;
			
			if (reset_other_vals) {
				//alert("form_settings_change(): resetting other values");
				for (a = 0; a < formobj.length; a++) {
					if (formobj.elements[a].name != var_name && 
						(formobj.elements[a].name.substr(0, 2) != "s_")) {
						//reset all values except for search fields
						formobj.elements[a].value = "";
					}
				}
			}
			
			if (!nopost) {
				formobj.submit();
			}
		} else {
			settings_field_msg = "PM3 could not find the settings field you requested to change.\n\nSetting: %setting_field\nRequested Value: %setting_val.";
			settings_field_msg = settings_field_msg.replace(/%setting_field/, var_name);
			settings_field_msg = settings_field_msg.replace(/%setting_val/, var_value);
			alert(settings_field_msg);
			return false;
		}
	} else {
		//alert("PM3 could not find the settings storage form.");
		return false
	}
}

function attach_event(obj, event_name, action) {
	//attaches an event to an HTML element.
	//e.g: attach_event(document.getElementById("obj"), "change", alert("hello"))
	if (window.attachEvent) {
		//alert("obj.attachEvent(\"on" + event_name + "\", " + action + ");")
		obj.attachEvent("on" + event_name, action);
	} else {
		//alert("obj.addEventListener(\"on" + event_name + "\", " + action + ", true);")
		obj.addEventListener(event_name, action, true);
	}
}

function get_form_setting(var_name) {
	if (formobj = document.forms['settingsForm']) {
		if (element = formobj.elements[var_name]) {
			return element.value;
		}
	} else {
		alert("PM3 could not find the settings storage form.");
		return false
	}
}

function in_array(needle, haystack_arr) {
	var return_val = false;
	var in_array_loop = 0;
	for (in_array_loop = 0; in_array_loop < haystack_arr.length; in_array_loop++) {
		if (haystack_arr[in_array_loop] == needle) {
			return_val = true;
		}
	}
	return return_val;
}

function validate_email(str) {
	var emailFilter=/^.+@.+\..{2,3}$/;
	if (!(emailFilter.test(str))) { return false; }
	
	var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/
	if (str.match(illegalChars)) { return false; }

	return true;
}

function validate_date(str) {
	var regexp = /^\d{4}\-\d{2}-\d{2} \d{2}:\d{2}:?\d{0,2}$/;
	if (!(regexp.test(str))) { return false; } else { return true; }
}

function remove_class(element, class_name) {
	if (element != "GLOBAL") {
		classArray = element.className.split(" ");
	} else {
		classArray = top.CURRENT_SELECTED_OLDCLASS.split(" ");
	}
	
	var new_class_name = "";
	for (a = 0; a < classArray.length; a++) {
		if (classArray[a] != class_name) {
			new_class_name += classArray[a] + " ";
		}
	}
	
	new_class_name = new_class_name.trim();
	
	if (element != "GLOBAL") {
		element.className = new_class_name;
		//alert(element.className)
	} else {
		top.CURRENT_SELECTED_OLDCLASS = new_class_name;
	}
}

function add_class(element, class_name) {
	//adds a classname element to an html tag <tag class="[foo bar whatsit]">
	if (element != "GLOBAL") {
		remove_class(element, class_name);
		if (element.className != "") {
			element.className = element.className + " " + class_name;
		} else {
			element.className = class_name;			
		}
	} else {
		remove_class("GLOBAL", class_name);
		top.CURRENT_SELECTED_OLDCLASS = top.CURRENT_SELECTED_OLDCLASS + " " + class_name;
	}
}

function class_exists(element, class_name) {
	//checks if an html tag has a specific classname applied to it.
	var a;
	classes = element.className.split(" ");
	for (a = 0;  a < classes.length; a++) {
		if (classes[a] == class_name) {
			return true;
		}
	}
	return false;
}

function is_valid_time(time) {
	var regex = /^\d.*?:\d\d(:\d\d)*$/;
	if (regex.test(time)) {
		return true;
	} else {
		return false;
	}
}

function hours2min(time) {
	//converts a HH:MM time into minutes
	if (is_valid_time(time)) {
		total = time.split(":");
		return (parseFloat(total[0]) * 60) + parseFloat(total[1]);
	}
}

function show_toolbutton(id) {
	if (window.top.contentShell.topMenu) {
		TRYCOUNT["show_toolbutton"] += 1;
		try {
			obj = window.top.contentShell.topMenu.document.getElementById(id);
			add_class(obj, "topToolbarShown");
			remove_class(obj, "topToolbarHidden");
		} catch(e) {
			if (TRYCOUNT["show_toolbutton"] < 3) {
				window.setTimeout("show_toolbutton('" + id + "')", 1000);
			}
		}
	}
}

function hide_toolbutton(id) {
	if (window.top.contentShell.topMenu) {
		TRYCOUNT["hide_toolbutton"] += 1;
		try {
			obj = window.top.contentShell.topMenu.document.getElementById(id);
			remove_class(obj, "topToolbarShown");
			add_class(obj, "topToolbarHidden");
		} catch(e) {
			if (TRYCOUNT["hide_toolbutton"] < 3) {
				window.setTimeout("hide_toolbutton('" + id + "')", 1000);
			}
		}
	}
}

function toolbar_sense_listboxes(e, form, frame, no_multipage) {
	/*checks whether a checkbox is checked, and then stores the number of selected checkboxes*/
	if (!e) var e = window.event;
	var sortgrid = top.contentShell.contentSortGrid;
	var chksel;
	
	if (form = frame.document.forms[form]) {		
		list_checkboxes_selected = 0;
		settingsform = frame.document.forms['settingsForm'];

		//for each checkbox on the form, see if it's checked
		for (var a = 0; a < form.length; a++) {
			if (form.elements[a].checked) {
				//element is checked - add 1 to the count, and add to the chksel element
				list_checkboxes_selected += 1;
				if (!no_multipage) add_slistbox(form.elements[a], settingsform);
			} else {
				//element is not checked - remove it from the chksel element
				if (!no_multipage) remove_slistbox(form.elements[a], settingsform);
			}
		}
		
		top.LISTBOXES_CHECKED = list_checkboxes_selected;
		
		//set the global checkbox counter depending on how many items are 
		//in the settingsForm chksel element
		if (chksel = settingsform.elements['chksel']) {
			if (chksel.value != "") {
				//if the value isn't blank, then do array stuff
				chk_array = chksel.value.split(",");
				top.GLOBAL_LISTBOXES_CHECKED = chk_array.length;
			} else {
				//or, just set 0 (because an empty array has a length of 1 according
				//to JS... *sigh*
				top.GLOBAL_LISTBOXES_CHECKED = 0;
			}
		}
		
		//update the toolbars
		top.contentShell.topMenu.update_toolbars();

		if (e) {
			e.cancelBubble = true;
			if (e.stopPropagation) e.stopPropagation();
		}
		
		//check/uncheck the sortgrid checkbox
		if (sg_checker = sortgrid.document.forms['sortGridForm'].elements['sgSelect']) {
			sg_checker.checked = (top.TOTAL_LISTBOXES == top.LISTBOXES_CHECKED);
		}
	}
	
	return false;
}

function init_listboxes() {
	//initialises the global listbox counts, pre-checks any checkboxes
	//that were selected using the chksel element, and checks or unchecks the
	//sortgrid checkbox if needed
	TRYCOUNT["init_listboxes"] += 1;
	
	try {	
		//pre-check all listboxes that are already checked via the 
		//chksel element in the settingsForm form
		top.GLOBAL_LISTBOXES_CHECKED = 0;
		top.LISTBOXES_CHECKED = 0;
		top.TOTAL_LISTBOXES = 0;
		
		var settingsform = document.forms['settingsForm'];
		var listform = document.forms['listForm'];
		var a;
		var sortgrid = top.contentShell.contentSortGrid;
		
		//count the total number of listboxes, regardless of state
		for (a = 0; a < listform.length; a++) {
			if (listform.elements[a].type == "checkbox")
				top.TOTAL_LISTBOXES ++;
		}
		
		//parse the ckhsel element
		if (chksel = settingsform.elements['chksel']) {
			//element exists
			if (chksel.value != "") {
				//chksel has stuff in it, let's keep going...
				chkarray = chksel.value.split(",");
				var element, element_id;
				
				for (a = 0; a < chkarray.length; a++) {
					//each chksel specified item should now be checked
					element_id = chkarray[a].substring(0, chkarray[a].indexOf(":"));
					
					if (element = document.getElementById(element_id)) {
						element.checked = true;
						top.LISTBOXES_CHECKED ++;
					}
				}
				
				//set the global multipage checked variable to the length of the chksel array
				top.GLOBAL_LISTBOXES_CHECKED = chkarray.length;
			}
		}
		
		if (top.GLOBAL_LISTBOXES_CHECKED == 0) {
			top.LISTBOXES_CHECKED = 0;
		}
		
		//check/uncheck the sortgrid checkbox
		if (sg_checker = sortgrid.document.forms['sortGridForm'].elements['sgSelect']) {
			sg_checker.checked = (top.TOTAL_LISTBOXES == top.LISTBOXES_CHECKED);
		}
		
		top.contentShell.topMenu.update_toolbars();
		
		return false;
	} catch(e) {
		if (TRYCOUNT["init_listboxes"] < 3) {
			window.setTimeout("init_listboxes()", 1000);
		}
	}
}

function clear_listboxes() {
	//attempts to clear all the checkboxes on a listform
	var form = document.forms['listForm'];
	for (a = 0; a < form.length; a++) {
		form.elements[a].checked = false;
	}
}

function add_slistbox(checkbox, settingsform) {
	//"remembers" a listbox is selected by adding it to a persistant
	//settingsForm element. quite fun. oh also it won't add it more than
	//once, hehe.
	var chksel = "";
	var id_str = checkbox.id + ":" + checkbox.value;
	
	if (chksel = settingsform.elements['chksel']) {
		//element exists, let's make some magic
		chksel.value = add_csv_item(chksel.value, id_str);
	}
}

function remove_slistbox(checkbox, settingsform) {
	//removes a listbox ID from the chksel element, so it's not
	//there anymore, which would cause it to no longer exist
	var chksel = "";
	var id_str = checkbox.id + ":" + checkbox.value;
	
	if (chksel = settingsform.elements['chksel']) {
		chksel.value = remove_csv_item(chksel.value, id_str);
	}
}

function add_csv_item(csv, str, allow_multiples) {
	//adds a csv item (comma seperated) to str, assuming
	//the str is a csv already, or blank
	if (csv.indexOf(str) == -1 || allow_multiples) {
		if (csv != "") csv += ",";
		csv += str;
	}
	
	return csv;
}

function remove_csv_item(csv, str) {
	//removes an item (str) from a csv (csv)
	/*str_index = chksel.value.indexOf(str);
	
	if (str_index != -1) {
		old_val = csv.toString();
		
		start_char = old_val.indexOf(str)-1;
		element_context = old_val.substring(start_char, start_char+(str.length+2));
		
		if (element_context.indexOf(",") == 0) {
			//comma on the beginning!
			csv = old_val.substring(0, str_index-1);
			csv += old_val.substring((str_index + str.length), old_val.length);
		} else if (element_context.lastIndexOf(",") == element_context.length-1) {
			//comma on the end!
			csv = old_val.substring(0, str_index);
			csv += old_val.substring((str_index + (str.length+1)), old_val.length);
		} else {
			//no commas either side. wtf?
			csv = old_val.substring(0, str_index);
			csv += old_val.substring((str_index + str.length), old_val.length);
		}
	}*/

	myregexp = new RegExp("(^)"+str+"($|,)", "i");
	myregexp2 = new RegExp("(,)"+str+"($|,)", "i");
	
	csv = csv.replace(myregexp, "");
	csv = csv.replace(myregexp2, "$2");
	
	return csv;
}

function popup_show(popup_id) {
	if (last_popup != "") {
		document.getElementById(last_popup).style.visibility = "hidden";
		window.clearInterval(popup_interval);
	}
	
	popup_over = true;	
	document.getElementById(popup_id).style.visibility = "visible";
	last_popup = popup_id;
	popup_interval = window.setInterval("popup_hide('" + popup_id + "')", 500);
}

function popup_hide(popup_id) {
	if (!popup_over) {
		document.getElementById(popup_id).style.visibility = "hidden";
		window.clearInterval(popup_interval);
	}
}

function sublinks(sublink) {
	if (last_sublink != "" && document.getElementById(last_sublink)) {
		document.getElementById(last_sublink).style.display = "none";
	}
	
	if (sublink != "" && document.getElementById(sublink)) {
		document.getElementById(sublink).style.display = "block";
	}
	
	//SUBLINK_TIMEOUT = window.setInterval("side_sublink('" + sublink + "')", 100);
	
	last_sublink = sublink;
}

function inline_edit_desc() {
	alert("These buttons allow administrators to edit pages outside of the CMS. For speed of loading, it doesn't check whether you're able to edit the page first. When saving, it will also not push the page live (unless you check 'Automatically Push this Edit').\n\nIf you require permissions to edit a specific page, please speak to your administrator.");
}

function start_fade_element(element_id, wait) {
	//starts the fading of an element, after the specified wait in milliseconds
	window.setTimeout("fade_element('" + element_id + "')", wait);
}

function fade_element(element_id, opacity) {	
	if (opacity) {
		opacity --;
		var element = document.getElementById(element_id);
		if (opacity == 0 || document.all) {
			element.style.display = "none";
			return;
		} else {
			element_opacity(element, opacity);
		}
		
	} else {
		var opacity = 100;
	}
	
	window.setTimeout("fade_element('" + element_id + "', '" + opacity + "')", 10);
}

function element_opacity(element, opacity) {
	//i did have code for this to work in i.e. but it didn't work, i don't know why
	element.style.MozOpacity = (opacity / 100);
}

function select_docloc(select) {
	url = select.options[select.selectedIndex].value;
	if (url != "") {
		location.href = url;
	}
}

function get_source(event) {
	if (event.srcElement) {
		return event.srcElement;
	} else if (event.target) {
		return event.target;
	} else {
		return false;
	}
}

function get_conf_price(xmldoc, response, conf_id, org_type) {
	//show the domain creator form
	if (document.getElementById("priceContainer") == null) return false;
	
	if (xmldoc != null) {
		if(xmldoc.childNodes[0].childNodes[0]==null)
		{
			if(org_type == null)
				var price = null;
			else
			{	
				var price = '0.00';
			}
		}
		else	
			var price = xmldoc.childNodes[0].childNodes[0].nodeValue;
		document.getElementById("priceContainer").display = "table-row";
		if(price != null && price != '')
			price = "Price: <b>&pound;" + price + "</b> (inc. VAT)";
		else
			price = "Price: ";
		document.getElementById("priceLabel").innerHTML = price;		
	} else {
		var post_data = "id=" + conf_id + "&org=" + org_type;
		ajax_send(get_conf_price, arguments, "/content/org_price.php", post_data);
		return false;
	}
}

function email_friend() {
	var url = location.href;
	url = url.replace(/\//g, "%1F");
	window.open("/email_friend/-/url/" + url + "/", "emailfriend", "width=250, height=310");
	return false;
}

//prototype functions
String.prototype.trim = function() {
	//removes whitespace from either side of a string
	return this.replace(/^\s+|\s+$/, "");
}


String.prototype.zerofill = function(length) {
	//fills zeros from the left in a string up to the required length specified
	var str = this;
	while (str.length < length) {
		str = "0" + str;
	}
	return str;
}

function in_array(theArray, theItem)
{
	for (var i = 0; i < theArray.length; i++)
	{
	    if (theArray[i] == theItem)
	    {
		  return i;
		}
	}
	return false;	
}

var extra_files_added = new Array();

function save_extra_file()
{
	addedfile = document.getElementById("extra_file");
	
	for (var i = 0; i < addedfile.options.length; i++)
	{
	    if (addedfile.options[i].selected && addedfile.options[i].value != 0)
		{
			if ((in_array(extra_files_added, addedfile.options[i].value)))
			{
				alert('That file has already been added to the list.');	
			}
			else
			{
				name =document.getElementById('extra_file_name').value;
				
				extra_files_added[extra_files_added.length] =addedfile.options[i].value;			
				objListElement = document.createElement('li'); 
				objCheckElement = document.createElement("input");
				objHiddenElement = document.createElement("input");
				objTextElement = document.createElement('label'); 
				objCheckElement.type = "checkbox";
				objCheckElement.id = "extra_file_"+addedfile.options[i].value;
				objCheckElement.value = addedfile.options[i].value;
				objCheckElement.name = "extra_files[]";
				objHiddenElement.type = "hidden";
				objHiddenElement.value = addedfile.options[i].value+"|"+name;
				objHiddenElement.name = "extra_file_name[]";
				
				objTextElement.htmlFor =  "extra_file_"+addedfile.options[i].value;
				objTextElement.style.paddingLeft='10px';
				objTextElement.innerHTML = "'"+name+"' ("+addedfile.options[i].text+
					')<span style="margin-left: 5px;" class="delete_extra_file"><a href="#" onclick="remove_added_files('+
					addedfile.options[i].value+')">Remove</a></span>';
				
				objListElement.appendChild(objCheckElement);
				objListElement.appendChild(objTextElement);
				objListElement.appendChild(objHiddenElement);
				objListElement.value = name;
				objListElement.id = "list_extra_file_"+addedfile.options[i].value;
								
				document.getElementById('list_extra_files').appendChild(objListElement);
				objCheckElement.checked = document.getElementById('members_only').checked;
			}
			return true; //end loop since only 1 selection allowed.
		}
	}
}

function remove_added_files(id)
{
	hidden = document.getElementById("list_extra_file_"+id);
	document.getElementById('list_extra_files').removeChild(hidden);
	for (var i = 0; i < extra_files_added.length; i++)
	{
		if(extra_files_added[i] = id)
		{
			extra_files_added.splice(i, 1);
			i--;
			return;
		}	
	}
}

var list_extra_options = new Array();
var option_count = 0;

function add_extra_option(from, to)
{

		from = document.getElementById(from);
		name = from.value;
		from.value='';
		if(name=='')
		{
			alert('You can not add a blank name.');			
		}
		else if ((in_array(list_extra_options, name)))
		{
			alert('That option has already been added to the list.');	
		}
		else
		{
			list_extra_options[list_extra_options.length] = name;
			
			objListElement = document.createElement('li'); 
			objCheckElement = document.createElement("input");
			objTextElement = document.createElement('label'); 
			objCheckElement.type = "checkbox";
			objCheckElement.id = "checktoadd_"+option_count;
			objCheckElement.value = name;
			objCheckElement.name = "add[]";
			
			objTextElement.htmlFor =  "checktoadd_"+option_count;
			objTextElement.style.paddingLeft='10px';
			objTextElement.innerHTML = name;
			
			objListElement.appendChild(objCheckElement);
			objListElement.appendChild(objTextElement)
			objListElement.id = "toadd_"+option_count;
			option_count++;							
			document.getElementById(to).appendChild(objListElement);
		}
}

function remove_added_files(formName, elementName)
{
	for(var i = 0; i< option_count; i++)
	{
		if(objCheckBox=document.getElementById("checktoadd_"+i))
			if(objCheckBox.checked)
			{
				name = objCheckBox.value;
				li=document.getElementById("toadd_"+i);			
				li.parentNode.removeChild(li);
				list_extra_options.splice(in_array(list_extra_options, name),1);
			}
	}
}

function onSearch(textBox)
{
	clear_me(textBox, 'Search');
}

function offSearch(textBox)
{
	unclear_me(textBox, 'Search');	
}

function clear_me(textBox, text)
{
	if(textBox.value == text)
	{
		textBox.value = '';	
	} 	
}

function unclear_me(textBox, text)
{
	if(textBox.value == '')
	{
		textBox.value = text;	
	} 
}

function submit_newsletter()
{
	name = document.getElementById("sp_newletter_name").value;
	email = document.getElementById("sp_newletter_email").value;
	ajaxFunction("/signup.php?", "name=" + name + "&email=" + email);	
	return false;
}/*
COMMON SCRIPT
Doc: 			Querystring functions
Use: 			See each function for a usage description
Dependencies: 	<none>
Created: 		16/March/2005
*/


function in_query(url, element, val) {
	//parses url to look for element in a querystring
	var url_arr = url.split("?");
	var a;
	if (url_arr.length > 1) {
		//only if there is a querystring		
		regex = new RegExp(element + "=", "i");
		element_found = regex.test(url_arr[1]);
		
		regex = new RegExp(element + "=" + val);
		val_found = regex.test(url_arr[1]);
		
		if (element_found && val_found || (element_found && val == null)) {
			//alert("found " + element + " and " + val);
			return true;
		}
	}
	
	return false;	
}

function alter_query(url, element, newval) {
	/*alters a query by replacing element with newval if found, or
	adding them to the query if not found. if you specify newval as "" or
	don't specify it at all, then it will remove the elemnt from the query*/
	var new_url;
	
	//alert("before:"+url);
	if (newval != null && newval != "") {
		if (in_query(url, element)) {
			//element is in the query already - replace with newval
			//alert("replacing existing element with new value");
			var regex = new RegExp("(" + element + "=.*?)(&|$)");
			new_url = url.replace(regex, element + "=" + newval + "$2");
		} else {
			//element is not in the query
			if (has_query(url)) {
				//alert("new element on existing query");
				//there is a query in the url
				new_url = url + "&" + element + "=" + newval;
			} else {
				//alert("new element on new query");
				//url has no query - start a new one
				new_url = url + "?" + element + "=" + newval;
			}
		}
	} else {
		//alert("removing element on existing query");
		//if newval is blank or null, get rid
		var regex = new RegExp("(&*)" + element + "=.*?(&|$)");
		new_url = url.replace(regex, "");
	}
	
	//alert("after:"+new_url);
	//this is the real meat of this function (haha, i kid)
	return new_url;
}

function has_query(url) {
	var regex = new RegExp(/\?/);
	return regex.test(url);
}/*
COMMON SCRIPT
Doc: 			Opens windows
Use: 			See each function for a usage description
Dependencies: 	<none>
Created: 		16/March/2005
*/


var PM3_WINDOW_PREFIX = "PM3";
var SESSION_COUNT = 1;

//this prefix only really needs to be used with pages that can be
//edited on the front end
var URL_PREFIX = "http://admin.map-uk.org";

//********************************
//Editing Pages
//********************************
function edit_user(id) {
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "userEdit" + id, "/users/edit_user.php?id=" + id, 
			550, 490, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "userAdd", "/users/edit_user.php", 
			550, 490, "yes", "no", "yes");
	}
}

function edit_dept(id) {
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "deptEdit" + id, "/users/depts/edit_dept.php?id=" + id, 
			550, 600, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "deptAdd", "/users/depts/edit_dept.php", 
			550, 600, "yes", "no", "yes");
	}
}

function edit_group(id) {
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "groupEdit" + id, "/users/groups/edit_group.php?id=" + id, 
			430, 300, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "groupAdd", "/users/groups/edit_group.php", 
			430, 300, "yes", "no", "yes");
	}
}

function edit_settings(pretab) {
	if (!pretab || pretab == null) {
		open_window(PM3_WINDOW_PREFIX + "settings", "/settings/edit_settings.php", 
			470, 515, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "settings", "/settings/edit_settings.php?pretab=" + pretab, 
			470, 515, "yes", "no", "yes");
		
	}
}

function edit_site_settings(pretab) {
	open_window(PM3_WINDOW_PREFIX + "siteSettings", "/site_settings/edit_settings.php", 
		470, 515, "yes", "no", "yes");
}

function edit_file(id, parentid) {
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "fileEdit" + id, "/files/edit_file.php?id=" + id, 
			430, 315, "yes");
	} else if (parentid != "" || parentid == 0) {
		open_window(PM3_WINDOW_PREFIX + "fileAdd", "/files/edit_file.php?parentid=" + parentid, 
			430, 315, "yes");
	} else {
		alert("Not enough/Invalid parameters specified.");
	}
}

function edit_directory(id, parentid) {
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "directoryEdit" + id, "/files/edit_directory.php?id=" + id + "&parentid=" + parentid, 
			360, 100, "yes");
	} else if (parentid != "" || parentid == 0) {
		open_window(PM3_WINDOW_PREFIX + "directoryAdd", "/files/edit_directory.php?parentid=" + parentid, 
			360, 100, "yes");
	} else {
		alert("Not enough/Invalid parameters specified.");
	}
}

function edit_projects(id, rev_id) {
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "projectsEdit" + id, URL_PREFIX + "/projects/edit.php?id=" + id, 
			720, 536, "yes", "no", "yes");
	} else if (rev_id != "") {
		open_window(PM3_WINDOW_PREFIX + "projectsEdit", URL_PREFIX + "/projects/edit.php?prid=" + rev_id, 
			720, 536, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "projectsAdd", URL_PREFIX + "/projects/edit.php", 
			720, 536, "yes", "no", "yes");
	}
}

function edit_news(id, rev_id) {
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "newsEdit" + id, URL_PREFIX + "/news/edit.php?id=" + id, 
			720, 536, "yes", "no", "yes");
	} else if (rev_id != "") {
		open_window(PM3_WINDOW_PREFIX + "newsEdit", URL_PREFIX + "/news/edit.php?nrid=" + rev_id, 
			720, 536, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "newsAdd", URL_PREFIX + "/news/edit.php", 
			720, 536, "yes", "no", "yes");
	}
}

function edit_makedifference(id, rev_id) {
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "edit_makedifferenceEdit" + id, URL_PREFIX + "/make_a_difference/edit.php?id=" + id, 
			720, 536, "yes", "no", "yes");
	} else if (rev_id != "") {
		open_window(PM3_WINDOW_PREFIX + "edit_makedifferenceEdit", URL_PREFIX + "/make_a_difference/edit.php?nrid=" + rev_id, 
			720, 536, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "edit_makedifferenceAdd", URL_PREFIX + "/make_a_difference/edit.php", 
			720, 536, "yes", "no", "yes");
	}
}

function edit_gaza_map_locations(id, rev_id) {
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "edit_gaza_map_locationsEdit" + id, URL_PREFIX + "/map_locations/edit.php?id=" + id, 
			680, 620, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "edit_gaza_map_locationsAdd", URL_PREFIX + "/map_locations/edit.php", 
			680, 620, "yes", "no", "yes");
	}
}


function edit_expert(id, rev_id) {
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "expertEdit" + id, URL_PREFIX + "/experts/edit.php?id=" + id, 
			720, 536, "yes", "no", "yes");
	} else if (rev_id != "") {
		open_window(PM3_WINDOW_PREFIX + "expertEdit", URL_PREFIX + "/experts/edit.php?nrid=" + rev_id, 
			720, 536, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "expertAdd", URL_PREFIX + "/experts/edit.php", 
			720, 536, "yes", "no", "yes");
	}
}

function edit_media(id, rev_id, front_end, parent_id) {
	var query = "";
	if (front_end != null && front_end != false) { query += "&fe=1"; }
	if (parent_id != null && parent_id != false) { query += "&parentid=" + parent_id; }
	
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "mediaEdit" + id, URL_PREFIX + "/media/edit.php?id=" + id + query, 
			720, 540, "yes", "no", "yes");
	} else if (rev_id != "") {
		open_window(PM3_WINDOW_PREFIX + "mediaEdit", URL_PREFIX + "/media/edit.php?revid=" + rev_id + query, 
			720, 540, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "mediaAdd", URL_PREFIX + "/media/edit.php?nq=1" + query, 
			720, 540, "yes", "no", "yes");
	}
}

function preview_cc(id) {
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "CentralColumnPreview" + id, "http://www.map-uk.org/cp_preview.php?id=" + id, 
			520, 580, "yes", "no", "yes");
	} 
}

function edit_cc(id) {
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "CentralColumnEdit" + id, "/central_column/edit.php?id=" + id, 
			440, 630, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "CentralColumnAdd", "/central_column/edit.php", 
			440, 630, "yes", "no", "yes");
	}
}

function edit_content(id, rev_id, front_end, parent_id) {
	var query = "";
	if (front_end != null && front_end != false) { query += "&fe=1"; }
	if (parent_id != null && parent_id != false) { query += "&parentid=" + parent_id; }
	
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "contentEdit" + id, URL_PREFIX + "/content/edit.php?id=" + id + query, 
			720, 540, "yes", "no", "yes");
	} else if (rev_id != "") {
		open_window(PM3_WINDOW_PREFIX + "contentEdit", URL_PREFIX + "/content/edit.php?revid=" + rev_id + query, 
			720, 540, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "contentAdd", URL_PREFIX + "/content/edit.php?nq=1" + query, 
			720, 540, "yes", "no", "yes");
	}
}

function edit_member(id) {
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "memberEdit" + id, "/members/edit.php?id=" + id, 
			720, 630, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "memberAdd", "/members/edit.php", 
			720, 630, "yes", "no", "yes");
	}
}

function edit_member_sub(id, member_id) {
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "memberSubEdit" + id, "/members/subscriptions/edit.php?id=" + id, 
			460, 242, "yes", "no", "yes");
	} else if (member_id != "") {
		open_window(PM3_WINDOW_PREFIX + "memberSubAdd", "/members/subscriptions/edit.php?memberid=" + member_id, 
			460, 242, "yes", "no", "yes");
	} else {
		alert("Not enough/Invalid parameters specified.");
	}
}

function edit_member_type(id) {
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "memberTypeEdit" + id, "/members/member_types/edit.php?id=" + id, 
			450, 300, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "memberTypeAdd", "/members/member_types/edit.php", 
			450, 300, "yes", "no", "yes");
	}
}

function edit_contact(id) {
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "contactEdit" + id, "/contacts/edit.php?id=" + id, 
			420, 165, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "contactAdd", "/contacts/edit.php", 
			420, 165, "yes", "no", "yes");
	}
}

function edit_twt_password(id) {
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "twtPassEdit" + id, "/twt_passwords/edit.php?id=" + id, 
			420, 165, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "twtPassAdd", "/twt_passwords/edit.php", 
			420, 165, "yes", "no", "yes");
	}
}

function edit_library_item(id, rev_id, front_end) {
	var query = "";
	if (front_end) query = "&fe=1";
	
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "libEdit" + id, URL_PREFIX + "/library/edit.php?id=" + id + query,
			720, 557, "yes", "no", "yes");
	} else if (rev_id != "") {
		open_window(PM3_WINDOW_PREFIX + "libEdit", URL_PREFIX + "/library/edit.php?revid=" + rev_id + query,
			720, 557, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "libAdd", URL_PREFIX + "/library/edit.php",
			720, 557, "yes", "no", "yes");
	}
}

function edit_ia_item(id, rev_id, front_end) {
	var query = "";
	if (front_end) query = "&fe=1";
	
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "iaEdit" + id, URL_PREFIX + "/intaffairs/edit.php?id=" + id + query,
			720, 557, "yes", "no", "yes");
	} else if (rev_id != "") {
		open_window(PM3_WINDOW_PREFIX + "iaEdit", URL_PREFIX + "/intaffairs/edit.php?revid=" + rev_id + query,
			720, 557, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "iaAdd", URL_PREFIX + "/intaffairs/edit.php",
			720, 557, "yes", "no", "yes");
	}
}

function edit_twt_item(id, rev_id, front_end) {
	var query = "";
	if (front_end) query = "&fe=1";
	
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "twtEdit" + id, URL_PREFIX + "/twt/edit.php?id=" + id + query,
			720, 557, "yes", "no", "yes");
	} else if (rev_id != "") {
		open_window(PM3_WINDOW_PREFIX + "twtEdit", URL_PREFIX + "/twt/edit.php?revid=" + rev_id + query,
			720, 557, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "twtAdd", URL_PREFIX + "/twt/edit.php",
			720, 557, "yes", "no", "yes");
	}
}

function edit_paper(id, rev_id, front_end) {
	var query = "";
	if (front_end) query = "&fe=1";
	
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "paperEdit" + id, URL_PREFIX + "/papers/edit.php?id=" + id + query,
			720, 557, "yes", "no", "yes");
	} else if (rev_id != "") {
		open_window(PM3_WINDOW_PREFIX + "paperEdit", URL_PREFIX + "/papers/edit.php?revid=" + rev_id + query,
			720, 557, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "paperAdd", URL_PREFIX + "/papers/edit.php",
			720, 557, "yes", "no", "yes");
	}
}

function edit_rss(id) {
	var query = "?nq=1";
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "rssEdit" + id, URL_PREFIX + "/rss/edit.php" + query + "&id=" + id, 
			550, 550, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "rssAdd", URL_PREFIX + "/rss/edit.php" + query, 
			550, 550, "yes", "no", "yes");
	}
}

function edit_event(id, rev_id, default_date, front_end) {
	var query = "?nq=1";
	if (default_date) { query += "&date=" + default_date; }
	if (front_end) { query += "&fe=1"; }
	
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "eventEdit" + id, URL_PREFIX + "/calendar/edit.php" + query + "&id=" + id, 
			700, 700, "yes", "no", "yes");
	} else if (rev_id != "") {
		open_window(PM3_WINDOW_PREFIX + "eventEdit", URL_PREFIX + "/calendar/edit.php" + query + "&revid=" + rev_id, 
			700, 700, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "eventAdd", URL_PREFIX + "/calendar/edit.php" + query, 
			700, 700, "yes", "no", "yes");
	}
}

function edit_conf(id, rev_id, default_date, front_end) {
	var query = "?nq=1";
	if (default_date) { query += "&date=" + default_date; }
	if (front_end) { query += "&fe=1"; }
	
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "confEdit" + id, URL_PREFIX + "/conferences/edit.php" + query + "&id=" + id, 
			700, 700, "yes", "no", "yes");
	} else if (rev_id != "") {
		open_window(PM3_WINDOW_PREFIX + "confEdit", URL_PREFIX + "/conferences/edit.php" + query + "&revid=" + rev_id, 
			700, 700, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "confAdd", URL_PREFIX + "/conferences/edit.php" + query, 
			700, 700, "yes", "no", "yes");
	}
}

function edit_poll(id) {
	if (id != "") {
		open_window(PM3_WINDOW_PREFIX + "pollEdit" + id, "/polls/edit.php?id=" + id, 
			720, 540, "yes", "no", "yes");
	} else {
		open_window(PM3_WINDOW_PREFIX + "pollAdd", "/polls/edit.php", 
			720, 540, "yes", "no", "yes");
	}
}

function panel_configurator(id, section_id, record_id, element_name, form_name) {
	//the section id is cusomisable because events can be created from different sections for specific purposes
	if (id != "" && section_id != "") {
		open_window(PM3_WINDOW_PREFIX + "panelConfig" + id, "/side_panels/edit.php?id=" + id + 
			"&sectionid=" + section_id + "&recordid=" + record_id + "&element=" + element_name + 
			"&form=" + form_name, 
			500, 430, "yes", "no", "yes");
	}
}

function quick_edit(id, url) {
	window.top.contentShell.quickEdit.location.href = url + id;
}
//********************************
//Editing Pages
//********************************


//********************************
//Viewing Pages
//********************************
function viewhelp(help_page) {
	open_window(PM3_WINDOW_PREFIX + "help", "/_helpres/index.php?hsn=" + help_page, 
				750, 550, "yes", "no", "yes");
}

function viewlog(log_id) {
	open_window(PM3_WINDOW_PREFIX + "log" + log_id, "/logs/view_log.php?id=" + log_id, 
				450, 490, "yes", "no", "yes");
}

function view_form_log(log_id) {
	open_window(PM3_WINDOW_PREFIX + "log" + log_id, "/form_logs/view_log.php?id=" + log_id, 
				450, 490, "yes", "no", "yes");
}

function view_txn_log(log_id) {
	open_window(PM3_WINDOW_PREFIX + "log" + log_id, "/transaction_logs/view_log.php?id=" + log_id, 
				450, 490, "yes", "no", "yes");
}

function gotodate(fset) {
	open_window(PM3_WINDOW_PREFIX + "gotodate", "/calendar/gotodate.php?fset=" + fset, 
				300, 70, "no", "no", "no");
}

function loadcalendar(form, element, preselect_date) {
	open_window(PM3_WINDOW_PREFIX + "gotodate", "/calendar/popup/?form=" + form + "&element=" + element + "&date=" + preselect_date,
				250, 260, "yes", "no", "no");
}

function view_task(id) {
	if (id != "") {
		open_instance("/tasks/read_task/index.php?id=" + id, PM3_WINDOW_PREFIX + "taskView" + id, "", false, 
					  700, 470)
	} else {
		alert("Not enough/Invalid parameters specified.");
	}
}

function viewlogs(log_section, log_record_id) {
	open_instance_section("21", "sectionid=" + log_section + "&id=" + log_record_id + "&trimmed=1", true, 650, 400);
}

function preview_page(page_url, id_field, id, path_query_format) {
	if (path_query_format) {
		open_window(PM3_WINDOW_PREFIX + "previewLiveDoc", "http://www.map-uk.org" + page_url + "-/" + id_field + "/" + id + "/preview/1/", 910, 600, "yes", "no", "yes", "no");
	} else {
		open_window(PM3_WINDOW_PREFIX + "previewLiveDoc", "http://www.map-uk.org" + page_url + "?" + id_field + "=" + id + "&preview=1", 910, 600, "yes", "no", "yes", "no");
	}
}

function view_file_path(file_id) {
	open_window(PM3_WINDOW_PREFIX + "gotodate", "/files/view_path.php?id=" + file_id,
				400, 200, "yes", "no", "no");
}
//********************************
//Viewing Pages
//********************************


//********************************
//Misc Pages
//********************************
function open_instance(indexpage, instance_name, query_data, resizable, width, height, menu) {
	var url_string = "/pm3/c_instance_index.php?index=" + escape(indexpage);
	if (query_data != "") {
		url_string += "&" + query_data;
	}
	if (!resizable) { resizable = "no"; } else { resizable = "yes"; }
	if (!width) { width = 725; }
	if (!height) { height = 500; }
	if (menu) { menubars = "yes"; } else { menubars = "no"; }
	
	var insSectionWindow = open_window(PM3_WINDOW_PREFIX + "_ins_" + instance_name, url_string, width, height, "yes", resizable, "no", menubars);
	return insSectionWindow;
}

function open_instance_section(section_name, query_data, resizable, width, height, menu) {
	var url_string = "/pm3/instance_index.php?sn=" + escape(section_name);
	if (query_data != "") {
		url_string += "&" + query_data;
	}
	if (!resizable) { resizable = "no"; } else { resizable = "yes"; }
	if (!width) { width = 800; }
	if (!height) { height = 500; }
	if (menu) { menubars = "yes"; } else { menubars = "no"; }
	
	var insSectionWindow = open_window(PM3_WINDOW_PREFIX + "_ins_" + section_name, url_string, width, height, "yes", resizable, "no", menubars);
	return insSectionWindow;
}

function open_session(query_data) {
	//opens another PM3 window
	SESSION_COUNT ++;
	var url_string = "/pm3/index.php?iw=1";
	
	if (query_data != "") {
		url_string += "&" + query_data;
	}
	
	var sessionWindow = open_window("session_" + SESSION_COUNT, url_string, 750, 580, "yes", "yes", "no", "no");
	return sessionWindow;
}

function report_bug(id) {
	open_window(PM3_WINDOW_PREFIX + "bugReport", "/_helpres/bug_report.php", 
				450, 500, "yes");
}
//********************************
//Misc Pages
//********************************

function open_window(windowname, windowurl, width, height, status, resizable, scrollbars, menubars) {
	
	var left = getCenteredLeft(width);
	var top = getCenteredTop(height);
	
	//safari is such a card, lol
	var ua = navigator.userAgent.toLowerCase();
	if (ua.indexOf("safari") != -1) {
		status = "no";
		height = height + 7;
	}
	
	windobj = window.open(windowurl, windowname, "width=" + width + ", height=" + height + ", status=" + status +", resizable=" + resizable + ", scrollbars=" + scrollbars + ", left=" + left + ", top=" + top + ", menubar=" + menubars);
	//windobj.document.onunload = window_unload();
	return windobj;
}

function window_unload() {
	alert("Hello!");
}

function close_window(check_changed) {
	if (check_changed) {
		if (form_element_changed) {
			if (confirm("Are you sure you want to close this window?\nYour changes will not be saved.")) {
				window.top.close();
			}
		} else {
			window.top.close();
		}
	} else {
		window.top.close();
	}
}

function getCenteredLeft(width) {

	var WindowWidth = new Number();
	var WindowLeft = new Number();

	if (window.outerWidth) {
		WindowWidth = window.outerWidth;
	} else {
		WindowWidth = screen.width;
	}
	
	if (window.screenX) {
		WindowLeft = window.screenX;
	} else {
		WindowLeft = 0;
	}

	return Math.ceil(((WindowWidth - width) / 2) + WindowLeft);

}

function getCenteredTop(height) {

	var WindowHeight = new Number();
	var WindowTop = new Number();

	if (window.outerHeight) {
		WindowHeight = window.outerHeight;
	} else {
		WindowHeight = screen.height;
	}

	if (window.screenY) {
		WindowTop = window.screenY;
	} else {
		WindowTop = 0;
	}

	return Math.ceil(((WindowHeight - height) / 2) + (WindowTop-30));

}/*
XML Library Functions
*/

function create_request_obj(callback) {
	/*creates an XML request object with the specified callback*/
	var xml_obj;
	
	if (window.XMLHttpRequest) {
		//w3 compliant browsers...
		xml_obj = new XMLHttpRequest();
		
		if (xml_obj.overrideMimeType)
			xml_obj.overrideMimeType('text/xml');	
	} else if (window.ActiveXObject) {
		//... and IE
		try {
			//new XMLhttp object
			xml_obj = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (error) {
			//old XMLhttp object
			try {
				xml_obj = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (error) {
				alert("create_request_obj() - Could not create an XMLHTTP instance");
				return false;
			}
		}
	}
	
	//set callback
	xml_obj.onreadystatechange = function() {		
		if (xml_obj.readyState == 4) {
			//request object has loaded			
			if (xml_obj.status == 200) {
				//document loaded correctly return everything under the root node
				//as an XML DOM object
				var xml = xml_obj.responseXML
				var root = xml.getElementsByTagName("root");
				
				if (root[0] != null) {
					callback(root[0]);
				} else {
					ajax_error(xml_obj, xml_obj.readyState);
					return false;
				}
			} else {
				//something unexpected happened
				ajax_error(xml_obj, xml_obj.readyState);
				return false;
			}
			
			//remove variable
			xml_obj = null;
		}
	}

	return xml_obj;
}

function ajax_send(callback, callback_args, request_url, request_data, request_type) {
	/*sends an ajax request. request data can be in POST format, or GET (escaped)
	callback: the function to execute once an XML response is recieved. the first two
		arguments to a callback are static: 
			xmldoc: XML Object at the <root> node
			response: a numeric value of the response from the first stage of multi-stage
				request functions, such as those that require confirmation before actually
				processing the sent data
		the remaining arguments are custom, and can be whatever you like
	callback_args: the arguments object from the calling function
	request_url: the file to send a request to
	request_data: data to send, in HTTP GET or POST format
	request_type: GET or POST.*/
	var xml_obj = create_request_obj(callback);
	var a;
	
	if (request_type == null) {
		request_type = "POST";
	} else if (request_type != "POST" || request_type != "GET") {
		alert("Invalid request type '" + request_type + "'. Use GET or POST");
		return false;
	}
	
	callback_function = callback.toString();
	callback_function = callback_function.replace(/function ([^\(]*)(.|\n)*/i, "$1");
	
	//open the connection, either GET or POST
	xml_obj.open(request_type, request_url, true);
	
	//send the headers
	xml_obj.setRequestHeader("Accept", "text/xml");
	xml_obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");	
	xml_obj.setRequestHeader("Content-length", request_data.length);
	xml_obj.setRequestHeader("Connection", "close");

	//send the GET or POST data
	xml_obj.send(request_data);
}

function ajax_error(ajax_obj) {
	/*display an ajax base error in an alert. this error should only be displayed
	when the status code wasn't 200 for an xml response.*/
	alert('An XML root node was not returned.' + 
		' Below is the response recieved:\n\n' + 
		'Content-Type: ' + ajax_obj.getResponseHeader("Content-Type") + '\n' + 
		'Date: ' + ajax_obj.getResponseHeader("Date") + '\n' + 
		'Server: ' + ajax_obj.getResponseHeader("Server") + '\n' + 
		'Connection: ' + ajax_obj.getResponseHeader("Connection") + '\n' + 
		'Object: ' + ajax_obj + ' (' + typeof(ajax_obj) + ')\n' +
		'Status: ' + ajax_obj.status + '\n' + 
		'ReadyState:' + ajax_obj.readyState + '\n\n' +
		'Response Text:\n---------------------------------\n' +
		ajax_obj.responseText);
}

function find_xml_element(response_xml, name, element_name) {
	//post_log("looking for element: " + element_name + " in a " + name + " tag");
	var elements, sub_elements;

	if (elements = response_xml.getElementsByTagName(name)) {

		for (var i = 0; i < elements.length; i++) {
			//loop through every element
			if (elements[i].getElementsByTagName(element_name).length > 0) {
				//tag has been found within the parent element
				sub_elements = elements[i].getElementsByTagName(element_name)
				if (sub_elements[0].hasChildNodes()) {
					return sub_elements[0].childNodes[0].nodeValue;
				} else {
					return "";
				}
			} else {
				return false;
			}
		}
	}
	//if the element isn't found, return false
	return false;
}

function ajaxFunction(url, vars){
	var ajaxRequest;

	try {
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer Browsers
		try {
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				// Something went wrong
				document.forms['signup'].submit();
			}
		}
	}
	
	ajaxRequest.onreadystatechange = function() {
		try {
			if (ajaxRequest.readyState == 4) {
				if (ajaxRequest.status == 400) {
					alert("Please ensure you have entered a valid name and email address.");
				}
				if (ajaxRequest.status == 200) {					
					var returnString = ajaxRequest.responseText;
					var returnArray = returnString.split(":");		
					document.getElementById('sp_newsletter_unsigned').style.display = 'none';
					document.getElementById('sp_newsletter_signed').style.display = 'block';
				} 
			}
		} catch (e) {
			document.forms['signup'].submit();
		}
	}
	
	ajaxRequest.open("POST", url, true);
	ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	ajaxRequest.setRequestHeader("Content-length", vars.length);
	ajaxRequest.setRequestHeader("Connection", "close");	
	ajaxRequest.send(vars); 
	return false;
}
