// return a value up to the delimiter, or the original value if the delimiter isn't there
// - this is used most often when parsing an argstring to set button states

	function crop(value, delimiter) {
		result = (value.indexOf(delimiter) != -1) ? value.substring(0, value.indexOf(delimiter)) : value ;
		return result;
	}
	

// open a popup window, specifying source, width, and height, and optionally a name; if no name, choose a random one

	function popup(source, width, height, window_name) {
		if (! window_name) { 
			now = new Date();
			window_name = now.getTime();
		} else {
			window_name = window_name.replace(/ /g, "_");
		}
		popup_window = window.open(source, window_name, "width=" + String(width) + ",height=" + String(height) + ",location=no,menubar=no,directories=no,toolbar=no,scrollbars=yes,resizable=yes,status=yes");
		popup_window.focus();
	}


// open an item edit window with a consistent size

	function popup_item(ID) {
		if ((ID == "new")&&(document.URL.indexOf("items.php") != -1)) {
			// pre-set the current list if we're viewing a list
			list = (document.filters.elements["filter_list[]"].selectedIndex > -1) ? document.filters.elements["filter_list[]"].options[document.filters.elements["filter_list[]"].selectedIndex].value : 0 ;
			list_argument = "&list=" + list;
		} else {
			list_argument = "";
		}
		width = 335;
		height = ((navigator.platform.indexOf("Win") != -1)||(navigator.appVersion.indexOf("Safari") != -1)) ? 440 : 400 ; // Windows and Safari space out the lines more, so open a taller window
		popup("../pages/item_edit.php?ID=" + ID + list_argument, width, height);
	}


// generate a random string of the specified length

	function random_string(strlen) {
		// chars contains no vowels to avoid accidentally generating a bad word
		chars = "123456789bcdfghjklmnpqrstvwxyz";
		str = "";
		for (var i=0; i<strlen; i++) {
			random = Math.floor(Math.random() * chars.length);
			str += chars.substr(random, 1);
		}
		return str;
	}


// the simplest possible rollover function

	function swap(name, state) {
		eval('document.images.' + name + '.src = ' + name + '_' + String(state) + '.src');
	}
	

// write a block of code that preloads a list of graphics
// - this version makes on and off states and is most often used for button rollovers

// names - a comma-delimited list of button names (e.g. "home,about,contact")
// path - the path to the graphics; defaults to "../graphics" if not set (e.g. "../graphics/menus/home")
// extension - the file extension of the graphics files; defaults to "gif" if not set (e.g. "jpg")

	function preload_buttons(names, path, extension) {
		names = names.split(",");
		path = (path) ? path : "../graphics" ;
		extension = (extension) ? extension : "gif" ;
		for (n=0; n < names.length; n++) {
			this_name = names[n];
			this_path = path + "/" + this_name;
			eval(this_name + "_0 = new Image()");
			eval(this_name + "_0.src = '" + this_path + "_0." + extension + "'");
			eval(this_name + "_1 = new Image()");
			eval(this_name + "_1.src = '" + this_path + "_1." + extension + "'");
		}
	}
	

// ajax functions
// 2009-01-30 - added support for synchronous connections (by setting asynchronous to false)
// 2009-04-16 - tweaked handling of synchronous connections for Firefox
// 2009-08-23 - added an ID to each request so multiple requests don't interfere with each other, and got rid of the "passthrough" variables for the same reason
// 2009-11-27 - added the Ajax-Request header to all requests in case we need to handle those differently somewhere

	function ajax_initialize(ID) {
		if (!isset("ajax", "object")) {
			ajax = new Object;
		}
		ajax[ID] = "";
		if (typeof(XMLHttpRequest) != "undefined") {
			ajax[ID] = new XMLHttpRequest();
		} else {
			// need to check for additional versions here?
			ajax[ID] = new ActiveXObject("Microsoft.XMLHTTP");
		}
		//return ajax[ID];
	}
	
	function ajax_request(ID, URL, success_code, failure_code, method, mode, data, wait) {
		// method: GET or POST
		// mode: text or XML
		// data: query string
		// wait: 1=asynchronous, 0=synchronous
	
		// in IE, we have to initialize before every request or subsequent request don't call the monitor
		ajax_initialize(ID);
		
		// set some defaults
		if (!failure_code) { failure_code = "alert('There was a problem processing your request.');"; }
		if (!method) { method = "GET"; }
		if (!mode) { mode = "text"; }
		asynchronous = (wait) ? false : true ;
		
		// if we're using the GET method but passing in data, add it to the URL
		if ((method == "GET")&&(data)) {
			delimiter = (URL.indexOf("?") != -1) ? "&" : "?" ;
			URL += delimiter + data;
		}
		
		// perform the request
		if (asynchronous) { // listen for a response action
			ajax[ID].onreadystatechange = function() { ajax_monitor(ID, mode, success_code, failure_code); } ;
		}
		ajax[ID].open(method, URL, asynchronous);
		ajax[ID].setRequestHeader("Ajax-Request", "1");
		if (method == "POST") {
			ajax[ID].setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        	ajax[ID].send(data);
		} else {
        	ajax[ID].send(null);
        }
		if (!asynchronous) { // just run the response action now; Firefox doesn't change the ready state
			ajax_monitor(ID);
		}
	}
	
	function ajax_monitor(ID, mode, success_code, failure_code) {
		if (ajax[ID].readyState == 4) {
			if (ajax[ID].getResponseHeader("Ajax-Redirect")) {
				top.location = "index.php?page=" + ajax[ID].getResponseHeader("Ajax-Redirect");
			} else {
				if (ajax[ID].status == 200) {
					if (mode == "XML") {
						// don't forget to set a Content-Type: text/xml header in the script that generates this!
						ajax_response = ajax[ID].responseXML;
					} else {
						ajax_response = ajax[ID].responseText;
					}
					eval(success_code);
				} else {
					ajax_response = ajax[ID].statusText;
					eval(failure_code);
				}
			}
		}
	}
	

// returns the index of an array element, something that ought to be built into JavaScript but isn't!
// returns -1 if not present

	function get_position(string, array) {
		for (n=0; n < array.length; n++) {
			if (array[n] == string) {
				return n;
				break;
			}
		}
		return -1;
	}


// sets a menu to a given text or value

	function set_menu(form_name, field_name, text_or_value, key) {
		eval("these_options = document." + form_name + "." + field_name + ".options");
		for (n=0; n < these_options.length; n++) {
			eval("this_text_or_value = these_options[n]." + text_or_value);
			if (this_text_or_value == key) {
				eval("document." + form_name + "." + field_name + ".selectedIndex = " + n);
				break;
			}
		}
		return "";
	}


// set date menus to a new SQL-standard date
// leave date blank to select today's date
// set to -1 to clear the menu

	function select_date(form_and_menu, new_date) {
		if (new_date != "-1") {
			if (new_date == "") {
				date = new Date();
				
				day = date.getDate();
				month = date.getMonth() + 1;
				year = date.getFullYear();
				
			} else {
				date = new_date;
				
				year = date.substring(0, date.indexOf("-"));
				month = date.substring(date.indexOf("-") + 1, date.lastIndexOf("-"));
				day = date.substring(date.lastIndexOf("-") + 1);
				
			}
					
			eval("document." + form_and_menu + "_month.selectedIndex = month");
			eval("document." + form_and_menu + "_day.selectedIndex = day");
			eval("document." + form_and_menu + "_year.selectedIndex = year - document." + form_and_menu + "_year.options[1].value + 1");
		} else {
			eval("document." + form_and_menu + "_month.selectedIndex = 0");
			eval("document." + form_and_menu + "_day.selectedIndex = 0");
			eval("document." + form_and_menu + "_year.selectedIndex = 0");
		}
	}


// set a cookie
	
	function set_cookie(name, value) {
		// specify a default key-name prefix for this project
		name_prefix = "";
		
		// the following are cookie parameters are optional ... change values to null if you don't need them
		hours = 43800;
		path = "/";						
		domain = ".mgtsuite.com";
		
		key = name_prefix + name;		
		(hours) ? expiration_date = new Date((new Date()).getTime() + hours*3600000).toGMTString() : expiration_date = false;
		cookie_string = key + '=' + escape(value) + ((expiration_date)?(';expires=' +expiration_date):'') + ((path)?(';path='+path):'') + ((domain)?(';domain='+domain):'');
		document.cookie = cookie_string;
	}
	

// get values from a cookie

	function get_cookie(name) {
		var output_value;
		if (document.cookie != "") {
			// specify a default key-name prefix for this project
			name_prefix = "";
			cookie_array = document.cookie.split("; ");
			for (i = 0; i < cookie_array.length; i++) {
				cookie_pair = cookie_array[i].split("=");
				key = cookie_pair[0];
				value = cookie_pair[1];
						
				if (key == (name_prefix + name)) {
					output_value = unescape(value);
					break;
				} else {
					output_value = "";
				}
			}
		} else {
			output_value = "";
		}
		return output_value;
	}
	
	
// figure out whether a variable has been set or not without generating an undefined error if it hasn't
// possible types are "undefined", "object", "boolean", "number", "string" or "function", with everything else being "object"
// this does not work on function arguments inside a function; even if the argument is set, this still returns false
// but in that case we can just check for a value without getting an error

	function isset(variable, type) {
		if (type) {
			eval("result = (typeof(" + variable + ") == type)");
		} else {
			eval("result = (typeof(" + variable + ") != 'undefined')");
		}
		return result;
	}


