
// set up browser detect vars
var isNS4 = (navigator.appName.indexOf("Netscape") != -1 && navigator.appVersion.charAt(0) == "4");
var isMOZ = (navigator.appName.indexOf("Netscape") != -1 && parseInt(navigator.appVersion.charAt(0)) >= 5);
var isIE = (navigator.appName.indexOf("Microsoft") != -1);

/**
 * Fills in a drop down with values set in a multi-dimensional array (example on Source Contacts)
 * @name	populateDropDown
 * @param	targetDrop -- the object of the target drop down
 * @param	optionListArray -- array of list for populating the target drop down
 * @param	optionListID -- the array index of the list to populate
 * @param	optionText -- optional string; the text of the selected option, used to set 'select a State' vs 'select a Province'
 * @param	targetValue -- optional value of the item to be selected in the list after population
 * @param       prompt -- optional value, displayed in the first no-value row. has priority over optionText logic.
 */
function populateDropDown(  targetDrop, 
                            optionListArray, 
                            optionListID, 
                            optionText, 
                            targetValue,
                            prompt) {
	var opts = targetDrop.options;
	// delete all options but first
	opts.length = 1;
	if (optionListID != "") {
		if (optionListArray[optionListID]) {
			// get array to populate list with
			var selectArray = optionListArray[optionListID];
			opts.length = selectArray.length +1;

                        if (prompt) {
                            opts[0].text = prompt;
                            opts[0].value = '';
                        } else if (optionText) {
                                // if we have been passed the text of the option selected, set the correct 'select a XXXX'
				if (optionText == 'USA' || optionText.toUpperCase() == 'UNITED STATES') {
					opts[0].text = 'Select State';
					opts[0].value = '';
				}
				else if (optionText.toUpperCase() == 'CANADA') {
					opts[0].text = 'Select Province';
					opts[0].value = '';
				}
				else {
					opts[0].text = 'Select Region';
					opts[0].value = '';
				}
			}
			for (var i=0; i<selectArray.length; i++) {
				// split value:name pair
				var itemArray = selectArray[i].split(":")
				opts[i+1].value = itemArray[0];
				opts[i+1].text = itemArray[1];
				if (targetValue && targetValue == itemArray[0]) {
                                    opts[i+1].selected = true;
                                }
                        }
		}
		else {
			opts.length = 1;
			opts[0].text = "Other";
			opts[0].value = "";
		}
	}
	// necessary for NS
	if (opts.length > 0 && opts.selectedIndex < 1) {
		opts[0].selected = true;
	}
}


function refreshForm(elem) {

	elem.form["refresh"].value = "true";
	elem.form.submit();
}

function resetForm(f) {

	for (var i = 0; i < f.length; i++) {
	
		if (f[i].type.indexOf('select') != -1) {
			f[i].selectedIndex = 0;
		}
		else if (f[i].type.indexOf('hidden') != -1) {
			// do nothing to hidden fields
		}
		else {
			f[i].value = "";
		}
	}
}

function saveValues(elemFrom, elemTo) {

    var toValue = "";
    
    for (var i = 0; i < elemFrom.options.length; i++) {
    
        if (i != 0) toValue += ",";
        
        toValue += elemFrom.options[i].value;
    }
    
    elemTo.value = toValue;
}

function setHiddenVal(elem, val) {
	elem.value = val;
}

function addItem(elemFrom, elemTo) {

    if (elemFrom.selectedIndex != -1 && elemFrom.options[elemFrom.selectedIndex].value != "") {
	
		// if this is a multiselect, loop through all options, checking for .selected
		if (elemFrom.type.indexOf("select-multiple") != -1) {
		
			for (var i = 0; i < elemFrom.options.length; i++) {
			
				if (elemFrom.options[i].selected) {
					
					var addValue = elemFrom.options[i].value;
			        var addText = elemFrom.options[i].text;
			
					// uniqueness check
			        for (var j = 0; j < elemTo.options.length; j++) {
			        
			            if (elemTo.options[j].value == addValue) {
			            
			                alert("The item \"" + addText + "\" has already been added.");
			                return;
			            }
			        }
					
					// add a new option to the target
			        elemTo.options[elemTo.options.length] = new Option(addText, addValue, false, false);
				}
			}		
		
		} else {
    
	        var addValue = elemFrom.options[elemFrom.selectedIndex].value;
	        var addText = elemFrom.options[elemFrom.selectedIndex].text;
	        
	        // uniqueness check
	        for (var i = 0; i < elemTo.options.length; i++) {
	        
	            if (elemTo.options[i].value == addValue) {
	            
	                alert("The item you have selected has already been added.");
	                return;
	            }
	        }
	        
	        // add a new option to the target
	        elemTo.options[elemTo.options.length] = new Option(addText, addValue, false, false);
		}
        
    } else {
    
        alert("You must select an item to add.");    
    }
}

function deleteItem(elem) {

    if (elem.selectedIndex != -1) {
	
		// if this is a multiselect, loop through all options, checking for .selected
		if (elem.type.indexOf("select-multiple") != -1) {
		
			for (var i = elem.options.length-1; i >= 0; i--) {
			
				if (elem.options[i].selected) {
					if (isIE) elem.options.remove(i);
		    	    else elem.options[i] = null;
				}
			}
		
		} else {
    
	        if (isIE) elem.options.remove(elem.selectedIndex);
    	    else elem.options[elem.selectedIndex] = null;
		}
    
    } else {
    
        alert("You must select an item to delete.");
    }
}

function setSelectVal(elem, val) {

    for (var i = 0; i < elem.options.length; i++) {
    
        if (elem.options[i].value == val) {
        
            elem.selectedIndex = i;
            break;
        }    
    }
}

function getSelectText(elem, val) {

    for (var i = 0; i < elem.options.length; i++) {
    
        if (elem.options[i].value == val) {
        
            return elem.options[i].text;
        }
    }
	return '';
}


function checkTextAreaLen(elem, maxLen) {

	var len = 0;
	// get length of elem's value
	len = elem.value.length;
	
	// if it is greater than the maxlength specified, alert the user and chop it to the correct length
	if (len > maxLen) {
		alert("This text area cannot be longer than " + maxLen + " characters.");
		elem.value = elem.value.substring(0, maxLen -1);
	}
}

// this function loops through all forms, checking multiselects for an option like: 
// <option value="-delete-"> - - - - - - - - - - - - - </option> and removes it
function fixMultiselects() {
	// loop through all forms
	for (var f = 0; f < document.forms.length; f++) {
		// loop through all elements
		for (var e = 0; e < document.forms[f].length; e++) {
			// check for a multiselect
			if (document.forms[f].elements[e].type == "select-multiple") {
				// check the first element
				if (document.forms[f].elements[e].options[0].value == "-delete-") {
					if (isIE) document.forms[f].elements[e].remove(0);
    	    		else document.forms[f].elements[e].options[0] = null;		
				}
			}
		}
	}
}

/**
 * Focus on the first element of the first form
 * @name	focusFirst
 */
function focusFirst(f) {
	var frm = document.forms[0];
	if (f) frm = f;
	if (frm) {
		for (i=0; i<frm.length; i++) {
			var elem = frm[i];
			if (elem) {
				// If text field or select box, focus on it
				if (elem.type.indexOf("text") != -1
					|| elem.type.indexOf("select") != -1
					|| elem.type.indexOf("password") != -1) {
					elem.focus();
					// If not a drop-down, select field
					// if (elem.type.indexOf("text") != -1) { elem.select(); }
					break;
				}
			}
			else { break; }
		}
	}
}

/**
 * Returns selected value from the given radio button.
 * @radioGroup An array of radio buttons grouped by name
 */
function getRadioValue(radioGroup) {
    var retVal;
    for ( var i = 0; i < radioGroup.length; i++ ) {
        if( radioGroup[i].checked ) {
            retVal = radioGroup[i].value;
            break;
        }
    }

    return retVal;
}

/**
 * Open a new window.
 *
 * @param	mypage --	URL to be loaded into the new window
 * @param	myname -- 	name of the window, for the window's title bar
 * @param	w -- 	width of the new window, in pixels
 * @param	h -- 	height of the new window, in pixels
 * @param	scroll -- 	whether new window has scrollbars; values are "yes" or "no"
 * @param	mainwindow --	Boolean.  If true, new window is not a popup, and is centered horizontally, and placed at the top of the screen.  If false, window is a popup, and is centered vertically and horizontally
 * @param   isModeless --	Boolean.  If true, window is not modal.  Allows default (empty) to create a modal window.
 */
function NewWindow(mypage, myname, w, h, scroll, mainwindow, isModeless) {
	var myname = myname.replace(/\./g, "_");
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;

	if (mainwindow) {
	 var wint = 0;
	}

	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll;

	if (isModeless) {
		win = window.open(mypage, myname, winprops);
	}
	else {
		// If browser is Netscape...
		if (isNS4) {
			winprops +=',alwaysRaised=yes';
			//Netscape requires additional priveleges to make modal windows.
			//This allows digitally-signed JavaScript to request those priveleges
			//This means the first time NewWindow() is called a Netscape user will get a popup confirming the granting of the additional privelege
			// We are keeping this line commented until we have a singed JAR file
			// to work with.
			// netscape.security.PrivelegeManager.enablePrivelege("UniversalBrowserwrite");
			win = window.open(mypage, myname, winprops);
		}
		// Else if browser is IE...
		else if (isIE) {
			//Adjustment to deal with IE's apparent different sizing of modaldialog windows
			w = parseInt(w) + 5;
			h = parseInt(h) + 25;
			winprops = 'status:no;scroll:'+scroll+';dialogHeight:'+h+'px;dialogWidth:'+w+'px;dialogTop:'+wint+'px;dialogLeft:'+winl+';px';
			win = window.showModalDialog(mypage, this, winprops);
		}
	}

	if (mainwindow && win) { win.focus(); }
	return win;
}

