// grep attempts to match the functionality of grepping an array in Perl, but with added options
// USAGE: var matched = grep(pattern, array, exactmatch, returntype);
// "pattern" is the string you want to match
// "array" is the array you want to grep
// "exactmatch" is a boolean -- true if you want only those items that match your string exactly, false if it just has to include it
// "returntype" specifies what type of variable you want back.  Possible values:  
//     -- "array" - an array of all matching items, "int" - number of matching items, or "boolean" - whether it found any matching items

function grep(pattern, array, exactmatch, returntype) {
	var returnarray = new Array();
	for (var i=0; i<array.length; i++) {
		if ((exactmatch && array[i] == pattern) || (!exactmatch && array[i].indexOf(pattern) != -1)) {
			returnarray.push(array[i]);
		}
	}
	switch (returntype) {
		case "array":
			return returnarray;
			break;
		case "int":
			return returnarray.length;
			break;
		case "boolean":
			return (returnarray.length > 0) ? true : false;
			break;
		default:
			return false;
			break;
	}	
}
	
function newImage(arg) {
	if (document.images) {
		rslt = new Image();
		rslt.src = arg;
		return rslt;
	}
}

function changeImages() {
	if (document.images && (preloadFlag == true)) {
		for (var i=0; i<changeImages.arguments.length; i+=2) {
			document[changeImages.arguments[i]].src = changeImages.arguments[i+1];
		}
	}
}

function getFullYear(d) {
    var y = d.getYear();
    if (y < 1000) {y += 1900};
    return y;
}

var days = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
var months = new Array("January","February","March","April","May","June","July","August","September","October","November","December");

function format_time(t) {
	var Day = t.getDay();
	var Date = t.getDate();
	var Month = t.getMonth();
	var Year = getFullYear(t);
	var timeString = days[Day] + " " + months[Month] + " " + Date + ", " + Year;
	return timeString; 
}

function refreshstatelist(statelist, countrylist) {
	var usindex = 0;
	for (var i=0; i<countrylist.options.length; i++) {
		if (countrylist.options[i].text == "United States") {
			usindex = i;
		}
	}
	if (countrylist.selectedIndex == usindex && statelist.selectedIndex > 51) {
		statelist.selectedIndex = 0;
	}
	else {
		statelist.selectedIndex = 0;
	}
}
	
function refreshcountrylist(statelist, countrylist) {
	var usindex = 0;
	var caindex = 0;
	for (var i=0; i<countrylist.options.length; i++) {
		if (countrylist.options[i].text == "United States") {
			usindex = i;
		}
		else if (countrylist.options[i].text == "Canada") {
			caindex = i;
		}
	}
	if (statelist.selectedIndex > 51) {
		countrylist.selectedIndex = caindex;
	}
	else {
		if (statelist.selectedIndex < 52 && statelist.selectedIndex > 0) {
			countrylist.selectedIndex = usindex;
		}
	}
}

function ClearForm(myform) {
	for (var i=0; i<myform.elements.length; i++) {
		var myelement = myform.elements[i];
		switch (myelement.type) {
			case "text":
			case "textarea":
			case "password":
				myelement.value="";
				break;
			case "checkbox":
				myelement.checked = false;
				break;
			case "select-one":
			case "select-multiple":
				myelement.options[0].selected = true;
				break;
			default:
				break;
		} 
	} 
} // end ClearForm();

function DeleteItem(type,url) {
	var confirmed = window.confirm("Are you sure that you want to delete this " + type + "?");
	if (confirmed) {
		location.href = url;
	}
} // end DeleteItem(type,url)

function DeleteMultiple(type) {
	var confirmed = window.confirm("Are you sure that you want to delete these " + type + "s?");
	return confirmed;
} // end DeleteMultiple(type)
	
function CheckRequired(requiredfields, fieldnames, myform) {
	var numfields = requiredfields.length;
	var errorstring = '';
	for (var i=0; i<numfields; i++) {
		var dualfields = new Array("");
		if (requiredfields[i].indexOf("|") != -1) {
			dualfields = requiredfields[i].split("|");
			var isdualfield = true;
			for (var k=0; k<dualfields.length; k++) {
				for (var j=0; j<myform.elements.length; j++) {
					var myelement = myform.elements[j];
					if (dualfields[k] == myelement.name) {
						if (myelement.type == "select-one" || myelement.type == "select-multiple") {
							if (myelement.options[myelement.selectedIndex].value != null && myelement.options[myelement.selectedIndex].value != '') {
								isdualfield = false;
							}
						}
						else if (myelement.value != null && myelement.value != '') {
							isdualfield = false;
						}
					}
				}
			}
			if (isdualfield) {
				errorstring += fieldnames[i] + ", ";
			}
		}
		else {
			for (var j=0; j<myform.elements.length; j++) {
				var myelement = myform.elements[j];
				if (myelement.name == requiredfields[i]) {
					if (myelement.type == "select-one" || myelement.type == "select-multiple") {
						if ((myelement.options[myelement.selectedIndex].value == null || myelement.options[myelement.selectedIndex].value == '') && errorstring.indexOf(fieldnames[i]) == -1) {
							errorstring += fieldnames[i] + ", ";
						}
					}
					else if ((myelement.value == null || myelement.value == '') && errorstring.indexOf(fieldnames[i]) == -1) {
							errorstring += fieldnames[i] + ", ";
					}
				}
			}
		}
	}
	if (errorstring != '') {
		errorstring = errorstring.slice(0,errorstring.length-2);
		window.alert("The following required fields need to be filled in: \n\n" + errorstring + ". \n\nPlease fill them in and resubmit the form.");
		return false;
	}
	else {
		return true;
	}
} // end CheckRequired(fields, names, myform)
	
function CheckAlphaNumeric(myfield,fieldname) {
	var myRegEx = new RegExp;
	myRegEx = /[^\da-z\-\_]/;
	if (myfield.value.search(myRegEx) != -1 && myfield.value != "") {
		window.alert("Only numbers, lowercase letters, underscores, or dashes are permitted in " + fieldname);
		myfield.focus();
		myfield.select();
	}
} // function CheckAlphaNumeric
	
function CheckEmail(myfield) {
	var myRegEx = new RegExp;
	myRegEx = /[\w\-\.\_]+\@[\w\-\.\_]+\.[\w\-\.\_]+/;
	if (myfield.value.search(myRegEx) == -1 && myfield.value != "") {
		window.alert("That is not a valid email address.\nPlease enter a valid email address.");
		myfield.focus();
		myfield.select();
	}
} // function CheckEmail

function FilterListWindow() {
	if ( document.getElementById || document.all ) {
		window.open("/filter/filterlist.pl", "FilterList", "height=480,width=600,status,scrollbars,resizable");
	}
	else {
		window.alert("You must use Internet Explorer 4.0 or Netscape 6.0 or newer to use this feature.");
	}
}
	
function OrderWindow(typename,arguments) {
	window.open("/filter/order.pl?type=" + typename + arguments, "Ordering", "height=480,width=600,status,scrollbars,resizable");
}
	
function AdminOrderWindow(typename,arguments) {
	window.open("/order.pl?type=" + typename + arguments, "Ordering", "height=480,width=600,status,scrollbars,resizable");
}
	
function FilterInstructions(item) {
	window.open("/filter/instructions.pl?item=" + item, "Instructions", "height=480,width=600,scrollbars,resizable");
}

function FilterListInstructions() {
	window.open("/filter/instructions.pl?filter=filter", "Instructions", "height=480,width=600,scrollbars,resizable");
}

function CloseWindow() {
	window.opener.focus();
	window.self.close();
}
	
function EditListOptions(name,oldname,id,cmd) {
	var pattern = new RegExp;
	pattern = /^list\d*/;
	for ( i=0; i<document.forms.length; i++ ) {
		var myform = document.forms[i];
		for ( j=0; j<myform.elements.length; j++ ) {
			var myelement = myform.elements[j]; 
			if ( myelement.type == "select-one" ) {
				if( myelement.name.search(pattern) != -1 ) {
					if ( cmd == "submit" ) {
   						if ( oldname == "" ) {
							myelement.options[myelement.options.length] = new Option(name, "list" + id);
   						}
   						else {
   							for ( k=0; k<myelement.options.length; k++ ) {
   								var myOption = myelement.options[k];
   								if ( myOption.text == oldname ) {
   									myOption.text = name;
   								}
   							}
   						}
					}
					else { 
						if ( cmd == "delete" ) {
							for ( k=0; k<myelement.options.length; k++ ) {
   								var myOption = myelement.options[k];
   								if ( myOption.value == "list" + id ) {
									myelement.options[k] = null;
								}
							}
						}
					}
				}
			}
		}
	}
}

function AddItemToList(mylist, myvalue, mytext) {
	if (myvalue != "" && myvalue != null) {
		if (!mylist.options[0].value) {
			mylist.options[0] = null;
		}
		var itemnum = mylist.options.length;
		mylist.options[itemnum] = new Option(mytext, myvalue, false, false);
		mylist.options[itemnum].selected = true;
	}
}

function RemoveItemFromList(mylist, itemnum, defaulttext) {
	if (itemnum >= 0) {
		mylist.options[itemnum] = null;
		if (mylist.options.length == 0) {
			mylist.options[0] = new Option(defaulttext, "", false, false);
		}
		var selecteditem = (itemnum < mylist.options.length) ? itemnum : mylist.length-1;
		mylist.options[selecteditem].selected = true;
	}
	else {
		window.alert("You must select an item in order to remove it.");
	}
}

function UpdateItemInList(mylist, itemnum, myvalue, mytext) {
	mylist.options[itemnum].value = myvalue;
	mylist.options[itemnum].text = mytext;
}

function MoveListItemUp(mylist, itemnum) {
	if (itemnum > 0) {
		var replacednum = itemnum - 1;
		SwitchListItems(mylist.options[itemnum], mylist.options[replacednum]);
		mylist.options[replacednum].selected = true;
	}
}

function MoveListItemDown(mylist, itemnum) {
	if (mylist.options.length > itemnum+1) {
		var replacednum = itemnum + 1;
		SwitchListItems(mylist.options[itemnum], mylist.options[replacednum]);
		mylist.options[replacednum].selected = true;
	}
}

function SwitchListItems(currentitem, replaceditem) {
		var currentitemtext = currentitem.text;
		var currentitemvalue = currentitem.value;
		currentitem.value = replaceditem.value;
		currentitem.text = replaceditem.text;
		replaceditem.value = currentitemvalue;
		replaceditem.text = currentitemtext;
}

function SubmitListAsArgument(mylist, valuename, useindexnums, baseurl) {
	for (var i=0; i<mylist.options.length; i++) {
		baseurl += (baseurl.indexOf("?") != -1) ? "&" + valuename : "?" + valuename;
		if (useindexnums) {
			baseurl += i+1;
		}
		baseurl += "=" + mylist.options[i].value;
	}
	document.location.href = baseurl;
}

function GetStringFromList(mylist, delimiter) {
	var mystring = delimiter;
	for (var i=0; i<mylist.options.length; i++) {
		mystring += mylist.options[i].value + delimiter;
	}
	return mystring;
}

function AlphabetizeListItems(mylist) {
	if (mylist.options.length > 1) {
		var templist = new Array();
		var tempselectlist = mylist;
		var selectedtext = mylist.options[mylist.selectedIndex].text;
		for (var i=0; i<mylist.options.length; i++) {
			templist.push(mylist.options[i].text);
		}
		templist.sort();
		var selectednum = 0;
		for (var i=0; i<templist.length; i++) {
			if (templist[i] == selectedtext) {
				selectednum = i;
			}
			mylist.options[i].text = templist[i];
			for (var j=0; j<tempselectlist.length; j++) {
				if (tempselectlist.options[j].text == templist[i]) {
					mylist.options[i].value = tempselectlist.options[j].value;
					break;
				}
			}
		}
		mylist.options[selectednum].selected = true;
	}
}

function expand() {
	for (var i=0; i<expand.arguments.length; i++) {
		var name = expand.arguments[i];
		var element;
		if (document.getElementById) {
			element = document.getElementById(name);
		} else if (document.all) {
			element = eval("document.all."+name);
		}
		element.style.display = (element.style.display == "none") ? "block" : "none";
	}
}
