// -- PURPOSE: to add a single item to a <select>
// -- Usage: addItemToList(list to be added to, value of item, displayed text of item)

function addItemToList(myList, myValue, myText) {
	if (myValue != "" && myValue != null) {
		// first, remove any items that have no value
		while (myList.options[0] && (myList.options[0].value == "" || myList.options[0].value == null)) {
			myList.options[0] = null;
		}
		var itemNum = myList.options.length;
		myList.options[itemNum] = new Option(myText, myValue, false, false);
		myList.options[itemNum].selected = true;
	}
}

// -- PURPOSE: to alphabetize a <select>
// -- Usage: alphabetizeListItems(list to be alphabetized)

function alphaSort(a, b) {
	// this function will provide case-insensitive alphabetizing, only used by alphabetizeListItems function
	return (a.toLowerCase() < b.toLowerCase()) ? -1 : 1;
}

function alphabetizeListItems(myList) {
	if (myList.options.length > 1) {
		var tempList = new Array();
		// create an array of all of text displayed in the <select>
		var tempSelectList = myList;
		// keep track of the currently selected item so it will be selected in the end
		var selectedText = myList.options[myList.selectedIndex].text;
		for (var i=0; i<myList.options.length; i++) {
			tempList.push(myList.options[i].text);
		}
		tempList.sort(alphaSort);
		var selectedNum = 0;
		for (var i=0; i<tempList.length; i++) {
			if (tempList[i] == selectedText) {
				selectedNum = i;
			}
			myList.options[i].text = tempList[i];
			// find the value of the current text from the temp copy we made earlier
			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;
	}
}

// -- PURPOSE: to check/uncheck all checkboxes in a form
// -- Usage: checkAll(checkbox that checks/unchecks all, string limiting checkboxes to those whose name begins with it)

function checkAll(checkallbox, beginsWith) {
	var myForm = checkallbox.form;
	for (var i=0;i<myForm.elements.length;i++) {
		var myElement = myForm.elements[i];
		if (myElement != checkallbox && myElement.type == 'checkbox') {
			if ((beginsWith && myElement.name.indexOf(beginsWith)==0) || (!beginsWith)) { 
				myElement.checked = checkallbox.checked;
			}
		}
	}
}
	
// -- PURPOSE: to validate a field to only be alphanumeric
// -- Usage: checkAlphaNumeric(field to check)

function checkAlphaNumeric(myField) {
	if (myField.value.search(/[^\w\-\_]/) != -1 && myField.value != "") {
		errorMessage("alpha-numeric");
		myField.focus();
		myField.select();
    return false;
	}
  return true;
}

// -- PURPOSE: to validate or reformat a date input to match sql standards YYYY-MM-DD
// -- Usage: checkDate(field to check)

function checkDate(myField) {
	// replace / and . with - so that we cover all ways people write dates
	myField.value = myField.value.replace(/[\/\. ]/g, "-");
	// if they have MM-DD-YYYY, then reformat it, otherwise throw an exception (unless it is already YYYY-MM-DD
	if (myField.value.search(/^\d{1,2}-\d{1,2}-\d{4}$/) != -1) {
		var parts = myField.value.split("-");
		myField.value = parts[2] + "-" + parts[0] + "-" + parts[1];
	}
	else if (myField.value.search(/^\d{4}-\d{1,2}-\d{1,2}$/) == -1 && myField.value != "") {
		errorMessage("date");
		myField.focus();
		myField.select();
	}
}
	
// -- PURPOSE: to validate a field to only contain email addresses
// -- Usage: checkEmail(field to check)

function checkEmail(myField) {
	// we only pattern match email addresses, checking a domain registrar would take too long
	if (myField.value.search(/[\w\-\.\_]+\@[\w\-\.\_]+\.[\w\-\.\_]+/) == -1 && myField.value != "") {
		errorMessage("email");
		myField.focus();
		myField.select();
    return false;
	}
  return true;
}

// -- PURPOSE: to validate a field to only contain email addresses
// -- Usage: checkFloat(field to check, string representing floating point size to check)

function checkFloat(myField, floatsize) {
	if ((myField.value.search(/[^\d\.]/) != -1 || myField.value.slice(myField.value.indexOf(".")+1).indexOf(".") != -1) && myField.value != "") {
		errorMessage("float");
		myField.focus();
		myField.select();
	}
	else {
		var digits; var decimals;
		var values = myField.value.split(".");
		if (myField.value.indexOf(".") != -1) {
			digits = values[0].length;
			decimals = values[1].length;
		}
		else {
			digits = myField.value.length;
			decimals = 0;
		}
		var sizes = floatsize.split(",");
		// if the number is too high, throw an exception, if there are too many decimal places, truncate it
		if (digits > parseInt(sizes[0])) {
			errorMessage("maxdigits", parseInt(sizes[0]));
			myField.focus();
			myField.select();
		}
		else if (decimals > parseInt(sizes[1])) {
			values[1] = values[1].slice(0,sizes[1]);
			myField.value = values[0] + "." + values[1];
		}
	}
}

// -- PURPOSE: to check the size of an image prior to upload
// -- Usage: checkImage(file input where image is being uploaded, maximum width, maximum height)

function checkImage(imgInput, xMax, yMax) {
	if (imgInput.value) {
  	if (imgInput.value.search(/(\.jpg|\.jpeg|\.gif)$/) == -1) {
    	errorMessage("image-type");
      return false;
		}
		var imgSrc = "file:///" + imgInput.value;
		imgSrc = imgSrc.replace(/ /g, '%20');
    var myImg = document.createElement("IMG");
    document.body.appendChild(myImg);
    myImg.src = imgSrc;
    var width = parseInt(myImg.width);
    var height = parseInt(myImg.height);
		//if (!(width && height)) {
    	var imageWindow = window.open("","imagechecker","width=1,height=1,menubar=no,toolbar=no,top=100,left=100");
			imageWindow.document.open();
			imageWindow.document.write("<html><head></head><body><img src=\"" + imgSrc + "\"></body></html>");
			// in Netscape 6, opening the new window causes it to calculate the height and width on the original image
			// otherwise, you can get the height and width off the image tag in the opened window as a backup
			//width = (myImg.width) ? parseInt(myImg.width) : parseInt(imageWindow.document.images[0].width);
			width = parseInt(imageWindow.document.images[0].width);
			//height = (myImg.height) ? parseInt(myImg.height) : parseInt(imageWindow.document.images[0].height);
			height = parseInt(imageWindow.document.images[0].height);
			imageWindow.close();
		//}
		document.body.removeChild(myImg);
    if ((width > xMax && xMax > 0) || (height > yMax && yMax > 0)) {
    	errorMessage("image-size", xMax + " x " + yMax + " px.");
      return false;
		}
    else {
    	return true;
		}
	}
  return true;
}

// -- PURPOSE: to validate a field to only contain integers
// -- Usage: checkInteger(field to check)

function checkInteger(myField) {
	if (myField.value.search(/\D/) != -1 && myField.value != "") {
		errorMessage("integer");
		myField.focus();
		myField.select();
	}
}

function checkPaymentForm(myForm) {
	if (myForm.paymethod_type.selectedIndex == 0) {
		myForm.required.value = myForm.cc_required.value;
	}
	else {
		myForm.required.value = myForm.check_required.value;
	}
	return checkRequired(myForm);
}

// -- PURPOSE: to validate a field to only contain integers
// -- Usage: checkPhone(field to check)

function checkPhone(myField) {
	myField.value = myField.value.replace(/\D/g, "");
	// if it isn't 7 or 10 digits, throw an exception, otherwise reformat it
	if (myField.value.length != 7 && myField.value.length != 10 && myField.value != "") {
		errorMessage("phone");
		myField.focus();
		myField.select();
	} 
	else if (myField.value.length == 7 && myField.value != "") {
		myField.value = myField.value.slice(0,3)+'-'+myField.value.slice(3);
	} 
	else if (myField.value.length == 10 && myField.value != "") {
		myField.value = '('+myField.value.slice(0,3)+') '+myField.value.slice(3,6)+'-'+myField.value.slice(6);
	}
}

// -- PURPOSE: to validate a field to only contain integers
// -- Usage: checkRequired(the form element to check)

function checkRequired(myForm) {
	var requiredFields = myForm.required.value.split(",");
	var numfields = requiredFields.length;
	var errorString = '';
	for (var i=0; i<numfields; i++) {
		var parts = requiredFields[i].split("=");
		var field = parts[0];
		var prompt = parts[1];		
		var dualFields = new Array("");
		if (field.indexOf("|") != -1) {
			dualFields = field.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 && myElement.style.display != "none") {
						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.search(/\w/) != -1) {
							isDualField = false;
						}
					}
				}
			}
			if (isDualField) {
				errorString += prompt + ", ";
			}
		}
		else {			
			for (var j=0; j<myForm.elements.length; j++) {
				var myElement = myForm.elements[j];
				if (myElement.name == field && myElement.style.display != "none") {
					if (myElement.type == "select-one" || myElement.type == "select-multiple") {
						if ((myElement.options[myElement.selectedIndex].value == null || myElement.options[myElement.selectedIndex].value == '') && errorString.indexOf(prompt) == -1) {
							errorString += prompt + ", ";
						}
					}
					else if ((myElement.value == null || myElement.value.search(/\w/) == -1) && errorString.indexOf(prompt) == -1) {
							errorString += prompt + ", ";
					}
				}
			}
		}
	}
	if (errorString != '') {
		errorString = errorString.slice(0,errorString.length-2);
		errorMessage("required", errorString);
		return false;
	}
	else {
		return true;
	}
}

// -- PURPOSE: to clear all fields in a form (differs from reset if form is prepopulated
// -- Usage: clearForm(form to be cleared)

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.selectedIndex = 0;
				break;
			default:
				break;
		} 
	} 
}

// -- PURPOSE: to empty a <select>
// -- Usage: clearLlist(list to empty, text to display afterwards)

function clearList(myList, defaultText) {
	for (var i=myList.options.length-1; i>=0; i--){
		myList.options[i] = null;
	}
	myList.options[0] = new Option(defaultText, "", false, false);
}

function deleteConfirm(delete_message) {
	delete_message = delete_message || 'delete';
	return window.confirm(errorMessages[delete_message]);
}

// -- PURPOSE: to print out an alert message to the screen
// -- Usage: errorMessage(id of message to print)
// -- NOTE: This is used in conjunction with messages.js which should be placed in each language folder and have messages translated in that language

function errorMessage(messageName) {
	var output = errorMessages[messageName];
	if (errorMessage.arguments[1]) {
		output += errorMessage.arguments[1];
	}
	window.alert(output);
}	

// -- PURPOSE: to get a delimited string from a <select>
// -- Usage: getStringFromList(list to be parsed, string of delimiter to be used)

function getStringFromList(myList, delimiter) {
	var myString = delimiter;
	for (var i=0; i<myList.options.length; i++) {
		myString += myList.options[i].value + delimiter;
	}
	return myString;
}

// -- PURPOSE: to get a delimited string from a <select>, but only from the selected items
// -- Usage: getStringFromSelected(list to be parsed, string of delimiter to be used)

function getStringFromSelected(myList, delimiter) {
	var mystring = "";
	for (var i=0; i<myList.options.length; i++) {
		if (myList.options[i].selected) {
			mystring += myList.options[i].value + delimiter;
		}
	}
	var myRegEx = new RegExp(delimiter + "$");
	mystring = mystring.replace(myRegEx,"");
	return mystring;
}

// -- PURPOSE: to move an item down in a <select>
// -- Usage: moveListItemUp(list to be altered, index of item to be moved)

function moveListItemDown(myList, itemNum) {
	if (itemNum >= 0 && myList.options.length > itemNum + 1) {
		var replacedNum = itemNum + 1;
		switchListItems(myList.options[itemNum], myList.options[replacedNum]);
		myList.options[replacedNum].selected = true;
		myList.selectedIndex = replacedNum;
	}
}

// -- PURPOSE: to move an item up in a <select>
// -- Usage: moveListItemUp(list to be altered, index of item to be moved)

function moveListItemUp(myList, itemNum) {
	if (itemNum > 0) {
		var replacedNum = itemNum - 1;
		switchListItems(myList.options[itemNum], myList.options[replacedNum]);
		myList.options[replacedNum].selected = true;
		myList.selectedIndex = replacedNum;
	}
}

// -- PURPOSE: To launch print options
// -- Usage: 

function myprint() 
		{
			window.parent.main.focus();
			window.print();
		}

// -- PURPOSE: to transfer selected items from a multiple <select> to another <select>
// -- Usage: multiSelectTransfer(element to be transferre from, element to be transferred to, boolean whether to remove from original list)

function multiSelectTransfer(fromElement, toElement, remove) {
	for (var i=0; i<fromElement.options.length; i++) {
		if (fromElement.options[i].selected) {
			addItemToList(toElement, fromElement.options[i].value, fromElement.options[i].text);
			if (remove) {
				fromElement.options[i] = null;
				i--;
			}
		}
	}
}

// -- PURPOSE: to open a new window or focus on it if it is opened
// -- Usage: openWindow(url to open, name of window object, width of window - number of pixels or "max" for maximum available, height of window - number of pixels or "max" for maximum available)

var myWindows = new Array();
function openWindow(windowURL, windowName, width, height, startX, startY) {
	var change = false;
	if (myWindows[windowName]){
		if (myWindows[windowName].closed) {
			change = true;
		}
		else if (myWindows[windowName].document.location.href.indexOf(windowURL) == -1) {
			change = true;
		}
	}
	else {
		change = true;
	}
	
	if (change) {
		if (width == "max") {
			width = screen.availWidth;
		}
		if (height == "max") {
			height = screen.availHeight - 50;
		}
		if (!startX) {
			startX = 0;
		}
		if (!startY) {
			startY = 0;
		}
		var args = "scrollbars=yes,toolbar=no,directories=no,menubar=no,resizable=yes,status=yes,width=" + width + ",height=" + height + ",top=" + startY + ",left=" + startX;
		myWindows[windowName] = window.open(windowURL, windowName, args);
	}
	myWindows[windowName].focus();
}

// -- PURPOSE: to refresh the country based on a change in the state
// -- Usage: removeCountryList(state list, country list)

function refreshCountryList(stateList, countryList) {
	// the number 51 is based on there being a 'Select A State' option followed by the 50 United States.  if this changes, these will need to be updated
	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;
		}
	}
}

// -- PURPOSE: to refresh the state based on a change in the country
// -- Usage: removeStateList(state list, country list)

function refreshStateList(stateList, countryList) {
	// the number 51 is based on there being a 'Select A State' option followed by the 50 United States.  if this changes, these will need to be updated
	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;
	}
}

// -- PURPOSE: to remove all selected items from a list
// -- Usage: removeSelectedFromList(list to be removed from, default text to appear if list is emptied)

function removeSelectedFromList(myList, defaultText) {
	var itemNum = -1;
	for (var i=myList.options.length-1; i>=0; i--) {
		if (myList.options[i].selected) {
			itemNum = i;
			myList.options[itemNum] = null;
		}
	}
	if (myList.options.length == 0) {
		myList.options[0] = new Option(defaultText, "", false, false);
	}
	if (itemNum >= 0) {
		var selectedItem = (itemNum < myList.options.length) ? itemNum : myList.length-1;
		myList.options[selectedItem].selected = true;
	}
	else {
		errorMessage("remove-select");
	}
}

// -- PURPOSE:
// -- Usage:

function replaceMessage(newMessage) {
	if (win_ie_ver >= 5.5) {
		objname = 'text';
		var editor_obj  = document.all["_" +objname+  "_editor"];       // html editor object
		var editdoc = editor_obj.contentWindow.document;
		editdoc.body.innerHTML = newMessage;
	}
	else { document.forms['editorForm'].text.value = newMessage; }
}

// -- PURPOSE: to select all items in a multi-select
// -- Usage: selectAll(multi-select)

function selectAll(mySelect) {
	for (var i=0; i<mySelect.options.length; i++) {
		mySelect.options[i].selected = true;
	}
}

// -- PURPOSE: to select no items in a multi-select
// -- Usage: selectNone(multi-select)

function selectNone(mySelect) {
	for (var i=0; i<mySelect.options.length; i++) {
		mySelect.options[i].selected = false;
	}
}

// -- PURPOSE: to swap items in a list
// -- Usage: switchListItems(first item, second item) -- this is used by other functions and shouldn't ever need to be called directly

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;
}

// -- PURPOSE: to update an item in a list
// -- Usage: clearLlist(list to update, index of item to update, value to be used, text to be used)

function updateItemInList(myList, itemNum, myValue, myText) {
	myList.options[itemNum].value = myValue;
	myList.options[itemNum].text = myText;
}
//Rollover	
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];
		}
	}
}
