<!--
/*
// This function parses comma-separated name=value pairs from the
// query string of the URL.  It stores the name/value pairs in properties
// of an Object and returns this object
//
// Modifications:
// 2009/09/17 rpp: defensive coding in activateForm()
// 3/19/2005 rpp: reformatting due to erroneous missing ")" errors in IE.
// 1/13/2005 rpp: moved in visibility/platform functions and global var 
//                from mmrrcRequests.js.
*/

// alert ( "start mmrrcjs.js code");

function getArgs() {
    var query = location.search.substring(1); // except the leading "?"
    var pairs = query.split ("&");	    // split on ampersand
    var args = new Object();
    var separator = ","		// for multi valued keys
    for ( lcv = 0; lcv < pairs.length; lcv++ ) {
	var splitPos = pairs[lcv].indexOf("=");     // is it a pair
	/*  try keeping just parameters w/o a value
	if ( splitPos == -1 ) {                     // not a pair
	    continue; 
	}
	*/
	var argname = pairs[lcv].substring(0,splitPos);
	var value   = pairs[lcv].substring(splitPos + 1);
	// unencoded "+" chars are encoding for embedded space chars
	while (value.indexOf('+') > -1) {
	    // Replace each '+' in data string with a space.
	    value = value.substring(0,value.indexOf('+')) + " " + value.substring(value.indexOf('+') + 1);
	}
	value = unescape( value );
	if ( args[argname] ) {
	    args[argname] = args[argname] + separator + value;
	}
	else {
	    args[argname] = value;
	}
	/*
	alert( "argname = " + argname + "\nvalue = " + value
	       );
	*/
    }
    return args;
}


/*
// transfers values in the args associative array to the form element fields.
// Value is not repeated into multiple text type inputs with the same field name.
// 
 */
function argsToFields ( frm, args ) {
    var element, val;
    for ( var fld in args ) {
	val = args[ fld ];
	element = frm[fld];
	if ( element == null || element == 0 ) {
	    // ignore
	}
	else if ( element.length  && // a Array type object
		  element[0]["type"]  // an Input or HTMLInputElement instance
		  ) {
	    if ( element[0].type.indexOf("text") > -1  ) {
		// multiple text fields with same field name
		// , so don't stutter value to all instances of it
		setField( element[0], val );
	    }
	    else {
		for ( var i = 0; i < element.length; i++ ) {
		    setField( element[i], val );
		} 
	    }
	} // if multiple elements 
	else {
	    // process a single instance of the field
	    setField( element, val );
	}
    } // for each var in the associative array
} // function


/*
// transfers value to a form element object
//
*/
function setField ( element, val ) {
    var elementType = element.type;
    // alert(elementType);
    if ( elementType == 'select-one' ) {
	for ( var i = 0; i < element.length; i++ ) {
	    var option = element.options[i];
	    if ( option.text == val || option.value == val ) {
		option.selected = true;
		element.selectedIndex = option.index;
	    }
	    else {
		option.selected = false;
	    }
	} // check each option in the select list
    } // single select list

    else if ( elementType == 'select-many' ) {
	var values = val.split(',');
	for ( var i = 0; i < values.length; i++ ) {
	    // check each value against each select option
	    for ( j = 0; j < element.length; j++ ) {
		var option = element.options[j];
		if ( option.text == values[i] || option.value == values[i] ) {
		    option.selected = true;
		}
		else {
		    option.selected = false;
		}
	    } // for each option element
	} // check each value supplied
    } // multi-select

    else if ( elementType == "checkbox" || elementType == "radio" ) {
	if ( element.value == val ) {
	    element.checked = true;
	}
	else {
	    element.checked = false;
	}
    }
    else {
	// assume one of the simple input types
	element.value = htmlEscape( val );
    } // else

    // no return value
}  // function


function profileSelect ( mmrrc_id ) {
    var id = parseInt( mmrrc_id );
    if ( id != Number.NaN && id <= 40 ) {  // last application on old forms
	// forward to the old version of profile
	document.location="strain_profile_v1.html?MMRRC_ID=" + mmrrc_id;
    }
    else {
	document.write ( "MMRRC: " + mmrrc_id );
    }
}

/*
// This function resets the form's recipient field to devteam@mmrrc.org
// and the subject to supplied string when not-production web instance.
//
*/
function formReroute ( frm, subj )  {
    // if URL's domain is not from production, then reroute msg
    // if not mmrrc.org/documents/*, then assume it's development!

    // the domain test is unreliable and
    // inconsistent between browsers!

    // disable this code on production; 
    // var redirectRe = /www\.mmrrc\.org:[0-9]+/;

  
  /*  frm.recipient.value="devteam@mmrrc.org";
    return true; */
    return false;
}


/*
// This function clears the values for any of the non-required
// citation fields when they are left set to "none".
*/
function clear_citations( frm )  {   
    if (frm.refURL1.value == 'none')    {
	frm.refURL1.value = '' ;
    }
    if (frm.refURL2.value == 'none')    {
	frm.refURL2.value = '' ;
    }
    if (frm.refURL3.value == 'none')    {
	frm.refURL3.value = '' ;
    }
    if (frm.citation2.value == 'none')    {
	frm.citation2.value = '' ;
    }
    if (frm.citation3.value == 'none')    {
	frm.citation3.value = '' ;
    }
}

// verify that all form fields listed in rlist have values
// frm is a DOM Form object; rlist is a comma-delimited string
function verify_req(frm,rlist)  {
    var e;			// the input element object
    var reqlist;		// list of required input elements
    var empty_fields = "";
    var elName = "";		// each required field name

    // is the required list an input element or array of them
    if ( (typeof rlist.value) == "string" ) {
	reqlist = rlist.value.split (',');
    }
    else {
	// an array of input elements
	// then concatenate the values into a single list

	var s = ",";
	for ( i=0; i<rlist.length; i++ ) {
	    s = s + rlist[i].value + ",";
	}
	// remove leading and trailing ","
	s = s.slice(1,-1);
	// split into each token
	reqlist = s.split (',');
    }

    for ( i in reqlist )   {
	// use subscript to get the field name string
	elName = reqlist[i];

	// strip off any spaces (assume leading and trailing)
	elName = elName.replace(/^\s+|\s+$/, "");

	// use field name to get the form element
	var e = frm[ elName ];
	if ( e == null ) {  // debugging aid -- shouldn't happen in prod.
	    alert ("Form element is null:" + elName);
	}
	else if (isElementEmpty(e) ) {
	    empty_fields += "\n      " + elName;
	}
    } // for each required field
    
    if (empty_fields != "")    {
	alert(
	      "The form was not submitted because of the following error(s).\n" +
	      "-The following required field(s) are empty:\n" + empty_fields + 
	      "\n\n Please fill in these fields before submitting.\n " + 
	      "Use unknown, not applicable (n/a), or none as necessary. \n "
	      );
	return false;
    }
    return true;
}

// given a form input element, checks whether it has some input
// Example for a set of checkboxes:
//     return !isElementEmpty( form['nameOfCheckboxes'] );
// the JS interpreter will create a collection of form elements matching
// the name of the element; the code processes the collection recursively.
function isElementEmpty ( e ) {
    var isEmpty = false;

    if ( e == null ) {
	isEmpty = true;
    }

    else if ( e.type == "radio" || e.type == "checkbox" ) {
	// alert ( e.name + " ." + e.value + ". " + e.checked);
	isEmpty = ! e.checked || isblank (e.value);
    }

    else if ( (e.type == "text") || (e.type=="textarea") || (e.type == "hidden") )   {
	// alert ( e.name + " " + e.value );
	if((e.value == null) || (e.value == "") || isblank(e.value)) {
	    isEmpty = true;
	} 
    }

    else if (e.type == "select-one" || e.type == "select-multiple") {
	if ( e.selectedIndex == -1 || getSelection(e) == "")   {
	    isEmpty = true;
	}
    }

    else if ( (e != null) && (typeof e.length == "number") ) { 
	// element group; the object SHOULD be an array of input elements
	for ( j=0; j<e.length; j++ ) {
	    var grpEmpty = true;
	    // an array is the sum of its elements
	    // if any is not empty then the element group is not empty
	    /* 
	    alert( e[j].type + " " + e[j].name + " >" + e[j].value + "< " + e[j].checked );
	    */
	    if ( ! isElementEmpty (e[j]) ) {
		grpEmpty = false;
		break;
	    }
	} // for each element in the array
	isEmpty = grpEmpty;
    }

    return isEmpty;
}


function isblank(s)  {
  if (s != null) { 
    for (var i = 0; i < s.length; i++)  {
       var c = s.charAt(i);
       if ((c != '') && (c != '\n') && (c != '\t')) {
	    return false;
       }
    }
  }
  return true;
}


// returns the currently selected option's value for a Select element
// if value is not explicitly set, uses the text attribute of the 
// selected option
function getSelection(selectObject)  {
    
    var val=selectObject.options[selectObject.selectedIndex].value;
    if ((val==null)||(val==""))  {
	return selectObject.options[selectObject.selectedIndex].text;
    }
    
    return val;
}



// add the appropriate instructions and the print/submit button
// for the platform/browser.
function addPrint ()  {
  if (window.print)   {	      // supports method
    document.writeln (
	"Please use the print button to " +
	"print out a copy of this Application-Agreement;<br>" +
	"then use the button again to submit the application.<p>" );
    btnLabel = " Print ";
    os = navigator.platform.substring(0,3);
    if ( os.toUpperCase() == "MAC")
    {
      btnLabel = "Print/Submit";
    }
  }
  else  {			       // does not support method
    document.writeln ( "Please use your browser's Print button to " +
	"print out a copy of this Application-Agreement.<p>" 
	);
    btnLabel = "Submit";
  }
  // button is a print or submit button 
  // depending on existence of window.print
  
  htmltxt = "<input type='button' value='" + btnLabel + "' onClick='doPrintSubmit(0)'><p>";
  document.write ( htmltxt );
  document.close();
}


// print if can do on platform-browser; submit if user confirms printed

function doPrintSubmit( formIdx ) {
  // if can print and not printed, then print and convert to
  // "submit" and reset the flag.

  thisForm = document.forms[formIdx];
  lastElement = thisForm.length - 1;
  btn = thisForm[lastElement];
  os = navigator.platform.substring(0,3).toUpperCase();

  if ( window.print &&  btn.value.indexOf("Print") >= 0 ) {
      window.print();
      btn.value = "Submit";
      // since invoked print dialog don't submit yet.
      return 0;
  }

  // are we really ready to submit (did we print it)?
  msg = 'Click "Okay" if you have printed a copy of the Application-Agreement form;\n' + 
        'click "Cancel" if you still need to print the form for signature.';
  reply = confirm ( msg );
  if ( reply ) {
    // call any validation here...
    clear_citations( thisForm );
    if ( thisForm.submit ) {
	if ( verify_req ( thisForm, thisForm.required ) ) {
	    thisForm.submit();
	}
	else if ( os != "MAC" )    {
	    btn.value = "Print";
	}
    }
    else {
       alert ("Does not support call to submit.");
    }
  }
  else if ( window.print && os != "MAC") {
      btn.value = "Print";
  }
  return reply;
}

// these two wrapper functions can be used by form input elements to 
// limit input to valid integers; both provide immediate alert notification
// suitable for use in field level validation.
// checkInt() allows blanks; 
function checkInt( element ) {
    // sVal = sVal.trim();
    if ( element == null ) {  // should never happen in prod.
	alert( "Form element is null." );
    }
    else { 
	// strip spaces
	var val = element.value;
	// eliminate any leading/trailing spaces
	if ( val != null && val.length > 0 ) {
	    val = val.replace( /^\s+/, "" );
	    val = val.replace( /\s+$/, "" );
	}
	if ( val.length == 0 || isInt(val) ) {
	    return true;
	}
	else {
	    alert( "If supplied, " + element.name + 
		   " value must be an integer." );
	}
    }
    // no good: element.focus();	// for NS 4.x; keep focus here
    return false;
}

//checks for only positive integers
function checkPositiveInt( element ) {   
	var val = element.value;	
  if ( val != null  && val.length > 0 ) 
  {
     var value = parseInt(element.value);
  }
  if ( checkInt( element ) )
  {
     if (val.length == 0 || value >= 0) 
     {	
	      return true;
	   }
	   else {
	      alert( "If supplied, " + element.name + 
		    " value must be a positive integer." );
	   }  
  }
  // no good: element.focus();	// for NS 4.x; keep focus here
  return false;
}

// requireInt() does not allow empty value
function requireInt ( element ) {
    if ( element == null ) {   // should never happen in prod.
	alert( "Form element is null." );
    }
    else {
	var val = element.value;
	// eliminate any leading/trailing spaces
	if ( val != null  && val.length > 0 ) {
	     val = val.replace( /^\s+/, "" );
	     val = val.replace( /\s+$/, "" );
	}
	if ( val.length > 0 && isInt(val) ) {
	    return true;
	}
	else {
	    alert( "Integer value required in " + element.name );
	}
    }
    // no good: element.focus();	// for NS 4.x; keep focus here
    return false;
}

// requirePositiveInt() does not allow empty value, 
//allows only positive integers
function requirePositiveInt ( element ) {    
   var val = parseInt(element.value);	
   if ( requireInt(element) ) {
     if (val >= 0)  {
       return true;
     }
     else {
       alert( "Positive integer value required in " + element.name );
     }
   }  
  return false;
}

// string pattern that accepts neg or pos integer 
function isInt(sValue) {
    re = /^-?\d+$/;
    return re.test(sValue);
}

function isPositiveInt(sValue) {   
    var newLength = sValue.length;

    for (var i = 0; i != newLength; i++)    {
	aChar = sValue.substring(i,i+1);
	
	if (aChar < "0" || aChar > "9")     {      
	    return false;
	}
    }
    return true;

}

// Tests if a string fits a generic pattern of an email address
function isEmailAddress ( e ) {
    // /^[^\s@]+@[^\s@.]+\.[^\s@.]+$/
    var at_pos = e.indexOf ("@");
    var dot_pos = e.lastIndexOf (".");
    if ( at_pos > 0 &&	    // must contain & cannot start with @
	 dot_pos > 0 &&	   // must contain & cannot start with .
	 at_pos < dot_pos-1 &&      // @ must appear before last "."
	 dot_pos < e.length-1) {  // address cannot end in "."
	return true;
    }
    return false;
}

// Tests if a comma-delimited list of fieldnames are all valid email formats
function verify_emails ( frm, emailList ) {
    var eList = emailList.split (",");
    var allOK = true;
    for ( var i=0; i < eList.length; i++ ) {
	var e = eList[i];
	if (e.length == 0) {}
	else if (! frm[e] ) {
	    alert ("Invalid fieldname: " + e);
	}
	// allow blanks -- let required fields address empty values
	else if ( ! isEmailAddress (frm[e].value) && ! isElementEmpty (frm[e]) ) {
	    alert ("Invalid email address format in input field: " + e );
	    allOK = false;
	}
    }
    return allOK;
}


function goToLoc(docWindow, target) {
  var found = false;
  var doc = docWindow.document;
  // alert ("Debug: location.hash: " + docWindow.location.hash );
  for ( i=0; i < doc.anchors.length; i++ ) {
    if ( doc.anchors[i].name == target ) {
      found = true;
      break;
    }
    // if ( !confirm( doc.anchors[i].name ) ) { break; }
  }
  if (! found){
    alert ( "No target location found for " + target + "." );
  }
  else {
    /*
      alert ( "Debug: (CodeName - " + navigator.appCodeName +
              ")\n appName: " + navigator.appName +
              " V.: " + navigator.appVersion + "\n" +
	      "href: " + doc.location.href);
    */
    // Netscape 4.78 and earlier inserted it's own # character
    if ( navigator.appName == "Netscape" && navigator.appVersion < "5" ) {
      docWindow.location.hash = target;
    }
    else if ( navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion < "5" )  {
      var pos = docWindow.location.href.indexOf("#");
      if ( pos < 0 ) {
        docWindow.location.href = docWindow.location.href + "#" + target;
      } 
      else {
        docWindow.location.href = docWindow.location.href.substr(0,pos+1) + target;
      }
    } 
    else {
      docWindow.location.hash = '#' + target;
    }
    // alert( "After: " + docWindow.location.href );
  }
}

// records which method should work for the setVisibility()
var platformMethod = null;

function setPlatformMethod() {
  // isolates the determination of which method to use from the code 
  // calling the method; apparently IE's JS implementation causes
  // a null document.getElementByID to be created by testing for it.
  // multiple references then cause the code to throw a null 
  // object exception.
  if ( document.getElementById ) {
    platformMethod = "W3C";
  }
  else if ( document.layers ) {
    platformMethod = "NsN";
  }
  else if ( document.all ) {
    platformMethod = "IE";
  }
  else {
    platformMethod = "";
  }
}


function setVisibility( id, state ) {
  // set visibility to desired state (using W3C/IE value-convention)
  if ( platformMethod == null ) { setPlatformMethod(); }
  if ( platformMethod == "W3C" ) {
    var element = document.getElementById(id);
    if ( element ) { element.style.visibility = state; }
    else { alert ("No such element for id, " + id); }
  } 
  else if ( platformMethod == "NsN" ) {
    // Netscape uses a different convention for visible
    if ( state == "visible" ) { state = "show"; }
    document.layers[id].visibility = state;
  } 
  else if ( platformMethod == "IE" ) {
    document.all[id].style.visibility = state;
  }
}


function activateForm( frm, isActive ) {
    var disable = ( ( isActive == null ) ? false : !isActive );
    // alert ( frm.name + " set " + isActive );
    if ( frm != null && typeof frm == "object" ) {
    	frm.disabled = disable;
    	disableElements( frm.elements, disable );
    }
    return null;
}

function disableElements( elList, disable ) {
    for ( var i = 0; i < elList.length; i++ ) {
	  elList[i].disabled = disable;
    }
    return null;
}

function disableElement( id, disable ) {
  if ( platformMethod == null ) { setPlatformMethod(); }
  if ( platformMethod == "W3C" ) {
      // alert('disableElement() id: ' + id );
    var element = document.getElementById(id);
    if ( element ) { element.disabled = disable; }
    else { alert ("No such element for id, " + id); }
  } 
  else if ( platformMethod == "NsN" ) {
    // Netscape uses a different convention for visible
   document.layers[id].disabled = disable;
  } 
  else if ( platformMethod == "IE" ) {
    document.all[id].disabled = disable;
  }
  return null;
}

function htmlEscape( s ) {
    var sEscd = s;
    sEscd = sEscd.replace( /&/g, "&amp;");
    sEscd = sEscd.replace( /</g, "&lt;");
    sEscd = sEscd.replace( />/g, "&gt;");
    sEscd = sEscd.replace( /\"/g, "&quot;");
    sEscd = sEscd.replace( /\'/g, "&#39;");
    return sEscd;
}

/*
Function to show/hide object with contentId depend on the value of 
checkedImputElement. "checkedImputElement" can be checkbox or radio button.
*/
function showHideContent(checkedImputElement, contentId) {
	var isChecked=checkedImputElement.checked;
	var hiddenPart=document.getElementById(contentId);

	if(hiddenPart == null) {
		// for catching development time error
		alert("contentId(" + contentId + ") does not exist.");
	}
	else {
		if (!isChecked) {
			hiddenPart.style.display="none";
		}
		else {
			hiddenPart.style.display="";
		}
	}
}
//-->

