// Utility javascript functions

/* add item to select element the less
 * elegant, but compatible way.
 */
function appendToSelect(selectFld, val, content) {
  var opt;
  opt = document.createElement("option");
  opt.value = val;
  opt.appendChild(content);
  selectFld.appendChild(opt);
}

var objCurrentRowSelected = null;
var objCurrentRowClass = null;

function selectRowObj(objRow) {
    if (objRow && (objRow != objCurrentRowSelected)) {
        if (objCurrentRowSelected) {
          objCurrentRowSelected.className = objCurrentRowClass;
        }
        if (objRow) {
          objCurrentRowSelected = objRow;
          objCurrentRowClass = objRow.className;
          objCurrentRowSelected.className = "selected";
        }
    }
    else {
      // clear any selections
      if ((objCurrentRowSelected) &&  (objCurrentRowSelected != objRow)) {
        objCurrentRowSelected.className = objCurrentRowClass;
      }
    }
}

function selectRow(rownum) {
    /* get row object */
    var objRow = document.getElementById("row"+rownum);
    return selectRowObj(objRow);
}

function selectRowId(id) {
    /* get row object */
    var objRow = document.getElementById(id);
    return selectRowObj(objRow);
}


function newwin(url, cfgStr) {
   if (navigator.appVersion=="1.0 (compatible; MSIE 3.0A; Windows 95)"){
       parent.location.href = '/';
   } 
   else {
       if (!cfgStr) {
         cfgStr = 'scrollbars=yes,status=yes,menubar=yes,resizable=yes,width=700,height=550,screenX=0,screenY=0';
       }

       // construct window name if possible
       var winName = "ETDADMIN";
       var re = /rm=(\w*);/;
       var subName;
       var hits = re.exec(url);
       if (hits && hits.length) {
         for (i = 0; i < hits.length; i++) {
          if (hits[i].match(/re=/)) {
            continue;
          }
          else {
            subName = hits[i];
          }
         }
       }
       if (subName) {
         winName += subName;
         cfgStr = 'scrollbars=yes,status=yes,menubar=yes,resizable=yes,width=600,height=500,screenX=20,screenY=20';
       }
       var window2 =window.open(url, winName, cfgStr);
       if (window2 && !window2.opener) {
         window2.opener = self;
       }
       if (window2) {
         window2.focus();
       }
       else {
         var htmltext = errors['sorrypopup'] + ' <a href="javascript:new_win(' + url + ', ' + cgfStr + ');">' + errors['clickhere'] + '</a> ' + errors['tocontinue'];
         document.write('<span>' + htmltext + '</span>');
       } 
/**
      window2.onload = function() { window.focus(); };
**/
   }
/*
try {
if(window2 && !window2.closed)
window2.focus();
} catch (ex) {
window2 = null;
} 
*/
/**
**/
  return winName;
}

function new_win(url, cfgStr) {
  newwin(url, cfgStr);
}

function smallwin(url) {
  var cfgStr = 'scrollbars=yes,status=yes,menubar=yes,resizable=yes,width=500,height=400,screenX=0,screenY=0';
  newwin(url, cfgStr);
}


function show(element) {
 if (element && element.style) {
   element.style.display = '';
 }
}

function showItem(itemName) {
 var elem = document.getElementById(itemName);
 if (elem) {
   show(elem);
 }
}

function hide(element) {
 if (element && element.style) {
   element.style.display = 'none';
 }
}

function hideItem(itemName) {
 var elem = document.getElementById(itemName);
 if (elem) {
   hide(elem);
 }
}

function showDiv ( elemID ) {
  var elem = document.getElementById ( elemID ) ;
  elem.className = '' ;
  return ( true ); //everythings ok
}

function hideDiv ( elemID ) {
  var elem = document.getElementById ( elemID ) ;
  elem.className = 'hidden' ;
  return ( true ) ; //everythings ok
}

function toggleDiv( elemID ) {
  var elem = document.getElementById ( elemID ) ;
  /*returns true if everything is ok*/
  return ( ( elem.className != 'hidden' ? hideDiv ( elemID ) : showDiv ( elemID ) ) ) ;
}

// function that checks if the value is an integer
function isInteger(inputVal) {
  var inputStr = inputVal.toString();
  for (var i = 0; i < inputStr.length; i++) {
    var oneChar = inputStr.charAt(i);
    if (!i && oneChar == "-") {
      continue;
    }
    if (oneChar == " ") {
      continue;
    }
    if (oneChar < "0" || oneChar > "9") {
      return false;
    }
  }
  return true;
}

// function that pads dates with a 0
function LZ(x) { return (x<0||x>=10?"":"0") + x; } 


/* clear specified  select list content */
function clearList(selectFld) {
  if (selectFld) {
    selectFld.value = " ";
    while (selectFld.length > 0) {
        selectFld.remove(0);
    }
/**
    for(var i=selectFld.options.length-1; i>=0; i--) {
       selectFld.remove(i);
    }
**/
  }
}

// function to handle return to previous screen
function goBack(serverEnv) {
  var histTotal = 1;
  if (navigator.appName == "Microsoft Internet Explorer") {
    histTotal = 0;
  }
  if (history.length > histTotal) {
    history.back();
  }
  else {
    if (opener) {
      window.close();
    }
    else {
      // display login form
      var url = "http://etdadmin" + serverEnv + ".cos.com/";
      this.location.href = url;
    }
  }
  return 1;
}

// function to trim leading and trailing blanks from a string
function trim(x) {
  while (x.substring(0,1) == ' ') {
      x = x.substring(1);
  }
  while (x.substring(x.length-1,x.length) == ' ')  {
      x = x.substring(0,x.length-1);
  }
  return x;
} 

// function to trim all blanks from a string
function strip(x) {
  x = x.replace(/\s/g, ""); 
  return x;
} 

function clear_selections(fldName, doSelect) {
  var fieldObj = document.getElementsByName(fldName);
  //var fieldObj = document.forms[0][fldName];
  var theChoices;

  if (fieldObj.length && (fieldObj.length > 0)) {
     for (var i = 0; i < fieldObj.length; i++) {
       var theField = fieldObj[i];
       if (theField) {
         var theType = theField.type;
         if (theType.indexOf("select") != -1) {
           // clear values in this picklist field
           if (theField.options) {
             theChoices = theField.options;
             if (theChoices && theChoices.length) {
               for (var j=0; j < theChoices.length; j++) {
                 if (theChoices[j]) {
                  try {
                   theChoices[j].selected = false;
                  } catch(e) {
                   theChoices[j].setAttribute('selected', true);
                  }
                 }
               }
               if (theChoices[0]) {
                 if (doSelect) {
                   try {
	             theChoices[0].selected = true;
                   } catch(e) {
                     theChoices[0].setAttribute('selected', true);
                   }
	           theField.selectedIndex = 0;
                 }
               }
             }
           }
           else {
             try {
               theField.selected = false;
             } catch(e) {
               theField.setAttribute('selected', true);
             }
           }
         }
         else if ((theType == "checkbox") ||
                  (theType.indexOf("radio") != -1)) {
           if (theField.options) {
             theChoices = theField.options;
             for (var k=0; k < theChoices.length; k++) {
               try {
                 theField.options[k].checked = false;
               } catch(e) {
                 theField.options[k].setAttribute('checked', false);
               }
             }
           }
           else {
             try {
               theField.checked = false;
             } catch(e) {
               theField.setAttribute('checked', false);
             }
           }
         }
       }
     }
  }
  else if (fieldObj.type && (fieldObj.type.indexOf("select") != -1)) {
     // clear values in this picklist field
     if (fieldObj.options) {
       theChoices = fieldObj.options;
       for (var n=0; n < theChoices.length; n++) {
         try {
           fieldObj.options[n].selected = false;
         } catch(e) {
           fieldObj.options[n].setAttribute('selected', false);
         }
       }
       if (doSelect) {
         try {
           fieldObj.options[0].selected = true;
         } catch(e) {
           fieldObj.options[0].setAttribute('selected', true);
         }
         fieldObj.selectedIndex = 0;
        }
      }
      else {
        try {
          fieldObj.selected = false;
        } catch(e) {
          fieldObj.setAttribute('selected', false);
        }
      }
  }
  else {
    try {
       fieldObj.selected = false;
    } catch(e) {
       fieldObj.setAttribute('selected', false);
    }
  }
}

function clearChoices(fldName) {
  clear_selections(fldName, 1);
}

function clearSelect(fldName) {
  clear_selections(fldName, 0);
}

/* check to see if form field values have changed */
function checkForFormChanges(formName) {
  var changed = false;
  var theForm = document.getElementById(formName);
  /*
  var inputs = theForm.getElementsByTagName('input');
  var numElems = inputs.length;
  */
  var numElems = theForm.elements.length;

  for (var i=0; i<numElems; i++) {
    var oElem = oForm.elements[i];

    if ("text" == oElem.type || "TEXTAREA" == oElem.tagName) {
	if (oElem.value != oElem.defaultValue) {
          changed = true;
        }
    }
    else if ("checkbox" == oElem.type || "radio" == oElem.type) {
	if (oElem.checked != oElem.defaultChecked) {
          changed = true;
        }
    }
    else if ("SELECT" == oElem.tagName) {
        var oOptions = oElem.options;
        var iNumOpts = oOptions.length;
        for (var j=0; j<iNumOpts; j++) {
	  var oOpt = oOptions[j];
	  if (oOpt.selected != oOpt.defaultSelected) {
            changed = true;
          }
	}
    }
  }
  return changed;
}

/* clear onbeforeunload event */
function clearUnload() {
  if (window.detachEvent) {
    window.detachEvent("onbeforeunload", preUnload);
  }
  else {
    window.onbeforeunload = null;    
  }
}

/***  PathValidation **/
function PathValidation(path) {
	if (path == "") {
		return false;
	}
	if (navigator.platform.indexOf("Win") != -1) {		
                if( navigator.userAgent.indexOf( "Firefox/3" ) == -1 ) {
		        if ((path.charAt(0) != "\\" && path.charAt(1) != "\\") && (path.charAt(0) != "/" && path.charAt(1) != "/")) {
			        if(!path.charAt(0).match(/^[a-zA-z]/))  {
				        return false;
			        }
			        if(path.charAt(1) == "" ||!path.charAt(1).match(/^[:]/) || !path.charAt(2).match(/^[\/\\]/)) {
				        return false;
			        } else {
				        return true;
			        }	
                        }
		}
	}
        return true;
}

function checkFileName(uploadField, ext) {
  var newFileName = uploadField.value;
  return validFileName(uploadField, newFileName, ext);
}

function validFileName(uploadField, newFileName, ext) {
   // make sure there aren't any spaces or more
   // than one period in the filename

   var valid = true;

   // determine base file name
   var lastSlash = newFileName.lastIndexOf("\\"); 
   if (lastSlash == -1) {
     lastSlash = newFileName.lastIndexOf("/"); 
   }
   baseFileName = newFileName.substring(lastSlash+1); 
   var fname = uploadField.name;
   var suffixcnt = fname.lastIndexOf("_"); 
   var suffix;
   var msg = errors['fileerrors'] + "\n";
   if (suffixcnt != -1) {
     suffix = fname.substring(suffixcnt+1); 
     msg = labels['file'] + " # " + suffix + "-   " + baseFileName + "  - " + errors['hadfollowerrs'] + "\n\n";
   }

   if (baseFileName) {
        // no double periods 
        var firstPeriodCnt = baseFileName.indexOf("."); 
        var lastPeriodCnt = baseFileName.lastIndexOf("."); 
        if (firstPeriodCnt > 1) {
	   if (firstPeriodCnt != lastPeriodCnt) {
	      msg += "\n" + errors['basenmnopd'] + "\n" +
                     errors['plschange'] + "\n";
              valid = false;
           }
        }
        if (firstPeriodCnt == -1) {
	      msg += "\n" + errors['filenoext'] + " ";
              if (ext) {
                msg += "(ie. '." + ext + "').\n";
              }
              else {
                msg += "(ie. '.txt', '.doc').\n";
              }
              msg += errors['plsaddext'] + "\n";
              valid = false;
        }

/** not needed as spaces are stripped out before uploading
        // no spaces 
        var re = /\s/g
        if (baseFileName.search(re) != -1) {
          msg += "\nSpaces cannot be included in the filename.\n" +
                 "Please rename your file and add it again, or zip your file to retain the original filename.";
          valid = false;
        }
**/
 
        // no special characters, etc.
        var invalidChars = new Array('#', '@', '!', '~', '`', '*', '\''); 
        var badChars = "";
        var numBadChars = 0;
        for (var i = 0; i < invalidChars.length; i++){
          var theChar = invalidChars[i]; 
          if (baseFileName.indexOf(theChar) != -1) {
            if (numBadChars) { badChars += ", "; }
            badChars += "'" + theChar + "'";
            numBadChars++;
          }
        }
        if (numBadChars) {
          var charStr = "character";
          if (numBadChars > 1) { charStr += "s"; }
          msg += "\n" + errors['the'] + " " + charStr + " " + badChars + " " +
                 errors['cannotbeinc'] + "\n" + errors['renamefile'];
          valid = false;
        }

        if (!valid) {
          alert(msg);
        }
     }
     return valid;
}

/**************************************************************************
* DHTML date validation script. Courtesy of SmartWebby.com 
*   (http://www.smartwebby.com/dhtml/)
**************************************************************************/
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var dtChInt= "-";
var minYear=1900;
var maxYear=2100;

/**
function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}
**/

function stripCharsInBag(s, bag) {
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) {
          returnString += c;
        }
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;}
		if (i==2) {this[i] = 29;}
   } 
   return this;
}

/**  date validation function ***/
function isDate(dtStr) {
	var daysInMonth = new DaysArray(12);

	var pos1 = dtStr.indexOf(dtCh);
	var pos2 = dtStr.indexOf(dtCh,pos1+1);
	var strMonth = dtStr.substring(0,pos1);
	var strDay = dtStr.substring(pos1+1,pos2);
	var strYear = dtStr.substring(pos2+1);
	strYr = strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) {strDay=strDay.substring(1);}
	if (strMonth.charAt(0)=="0" && strMonth.length>1) {strMonth=strMonth.substring(1);}
	for (var i = 1; i <= 3; i++) {
	   if (strYr.charAt(0)=="0" && strYr.length>1) {strYr=strYr.substring(1);}
	}
	month = parseInt(strMonth, 10);
	day = parseInt(strDay, 10);
	year = parseInt(strYr, 10);
	if (((pos1 == -1 || pos2 == -1)) ||
            (isNaN(month) || isNaN(day) || isNaN(year))) {
	    alert(errors['enterdate']);
	    return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert(errors['enterdate'] + "\n\n" + errors['entervalidmo']);
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert(errors['enterdate'] + "\n\n" + errors['entervaliddy']);
		return false;
	}
	if (strYear.length != 4 || !year || year<minYear || year>maxYear){
		alert(errors['enterdate'] + "\n\n" + errors['entervalidyr'] + " " + minYear + " " + errors['and'] + " " + maxYear);
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || !isInteger(stripCharsInBag(dtStr, dtCh))){
		alert(errors['enterdate'] + "\n\n" + errors['entervaliddt']);
		return false;
	}

  return true;
}

/**  date validation function ***/
function isDateInt(dtStr) {
	var daysInMonth = new DaysArray(12);

	var pos1 = dtStr.indexOf(dtChInt);
	var pos2 = dtStr.indexOf(dtChInt,pos1+1);
	var strYear = dtStr.substring(0,pos1);
	var strMonth = dtStr.substring(pos1+1,pos2);
	var strDay = dtStr.substring(pos2+1);
	strYr = strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) {strDay=strDay.substring(1);}
	if (strMonth.charAt(0)=="0" && strMonth.length>1) {strMonth=strMonth.substring(1);}
	for (var i = 1; i <= 3; i++) {
	   if (strYr.charAt(0)=="0" && strYr.length>1) {strYr=strYr.substring(1);}
	}
	month = parseInt(strMonth, 10);
	day = parseInt(strDay, 10);
	year = parseInt(strYr, 10);
	if (((pos1 == -1 || pos2 == -1)) ||
            (isNaN(month) || isNaN(day) || isNaN(year))) {
	    alert(errors['enterdateint']);
	    return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert(errors['enterdateint'] + "\n\n" + errors['entervalidmo']);
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert(errors['enterdateint'] + "\n\n" + errors['entervaliddy']);
		return false;
	}
	if (strYear.length != 4 || !year || year<minYear || year>maxYear){
		alert(errors['enterdateint'] + "\n\n" + errors['entervalidyr'] + " " + minYear + " " + errors['and'] + " " + maxYear);
		return false;
	}
	if (dtStr.indexOf(dtChInt,pos2+1)!=-1 || !isInteger(stripCharsInBag(dtStr, dtChInt))){
		alert(errors['enterdateint'] + "\n\n" + errors['entervaliddt']);
		return false;
	}

  return true;
}

/**  date re-format function ***/
function reformatDate(dtStr) {
  // replace other known date separators with a '/'
  dtStr = dtStr.replace(/[\.\-\ ]/g, '/');
  return dtStr;
}


/**  future date validation function ***/
function isFutureDate(dtStr){
  var valid = false;
  if (isDate(dtStr)) {
    var arrDate = dtStr.split("/");  
    var theDate = new Date(arrDate[2], arrDate[0]-1, arrDate[1]);  
    var today = new Date();  
    valid = theDate > today;  
  }
  return valid;
}

function isFutureDateInt(dtStr){
  var valid = false;
  if ( isDateInt(dtStr)) {
	var arrDate = dtStr.split("-");
	var theDate = new Date(arrDate[0], arrDate[1]-1, arrDate[2]);
	var today = new Date();
	valid = theDate > today;
  }
  return valid;
}

// Given a tr node and row number (newid), this iterates over the row in the
// DOM tree, changing the id attribute to refer to the new row number.
function rowrenumber(newrow, newid) {

  var curnode = newrow.firstChild;      // td node

  while (curnode) {
    var curitem = curnode.firstChild;   // input node (or whatever)
    while (curitem) {
      if (curitem.id) {  // replace row number in id
        var spl = curitem.id.split('_');
        var baseid = spl[0];
        curitem.id = baseid + '_' + newid;
        if (curitem.name) {
          var n_spl = curitem.name.split('_');
          var n_baseid = n_spl[0];
          curitem.name = n_baseid + '_' + newid;
        } 
       }  

       if (curitem.hasChildNodes()) {
        var curchild = curitem.firstChild;   
        while (curchild) {
          if (curchild.id) {  // replace row number in id
            var origid = curchild.id;
            var splarray = curchild.id.split('_');
            var base_id = splarray[0];
            var newIdVal = base_id + '_' + newid;
            curchild.id = newIdVal;

            if (curchild.id.indexOf('clr_') != -1) {
              var docurl = document.URL;
              var url_arr = docurl.split('#');
              var urlbase = url_arr[0];

              var href_arr = curchild.href.split('#');
              var hreftag = href_arr[1];
              var tag_arr = hreftag.split('_');
              var tagbase = tag_arr[0];
              var newHrefVal = urlbase + '#' + tagbase + '_' + newid;
              curchild.href = newHrefVal;
            }
            if (curchild.name) {
              var n_splarr = curchild.name.split('_');
              var n_base_id = n_splarr[0];
              curchild.name = n_base_id + '_' + newid;
            }
          }
          if (curchild.tagName && (curchild.tagName == "LABEL")) {
            var forval = curchild.htmlFor; 
            var spl_array = forval.split('_');
            var baseId = spl_array[0];
            var newforval = baseId + '_' + newid;
            curchild.htmlFor = newforval;
          }

          if (curchild.className && (curchild.className.indexOf("newid") != -1)) {
            if (curchild.hasChildNodes()) {
              var theChild = curchild.firstChild;
              while (theChild) {
                if (theChild.nodeValue) {
                  theChild.nodeValue= newid + ".";
                 }
                 theChild = theChild.nextSibling;
              }
            }
            else {
              if (curchild.nodeValue) {
                curchild.nodeValue= newid + ".";
              }
            }
          }
          curchild = curchild.nextSibling;
        }
       }

      curitem = curitem.nextSibling;
    }
    curnode = curnode.nextSibling;
  }
}

// Appends a row to the given table, at the bottom of the table.
function appendRow(table_id, hasHeader, rownum) {

  if (!rownum) { 
    if (hasHeader) {
      rownum = 1; 
    } else {
      rownum = 0;
    }
  }

  // get specified row
  var row = document.getElementById(table_id).rows.item(rownum);

  var newid = row.parentNode.rows.length;
  if (!hasHeader) {
    // Since there is no header row, we need to add one
    newid += 1;
  }

  var newrow = row.cloneNode(true);
  rowrenumber(newrow, newid);
  row.parentNode.appendChild(newrow);      // Attach to table

  return newid;
}


/**** checkPhone ***/
function checkPhone(phoneval){
  var valid = true;

  //strip out acceptable non-numeric characters
  var stripped = phoneval.replace(/[\(\)\.\-\ ]/g, '');

  if (isNaN(parseInt(stripped, 10))) {
   alert(errors['invalidphone']);
   valid = false;
  }
  return valid;
}


/**
 * DHTML email validation script. 
 *  Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
**/
function validEmail(str) {
		var at="@";
		var dot=".";
		var lat=str.indexOf(at);
		var lstr=str.length;
		var ldot=str.indexOf(dot);

		if (str.indexOf(at) == -1){
		   return false;
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false;
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false;
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false;
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false;
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false;
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false;
		 }

                 if (/^\w+([\.\-\+]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$/.test(str)){
                    return (true);
                 }
}

function emailCheck (emailStr) {
/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
var emailPat=/^(.+)@(.+)$/;
/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address. 
   These characters include ( ) < @ , ; : \ " . [ ]    */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
/* The following string represents the range of characters allowed in a 
   username or domainname.  It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]";
/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")";
/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
/* The following string represents an atom (basically a series of
   non-special characters.) */
var atom=validChars + '+';
/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")";
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");


/* Finally, let's start trying to figure out if the supplied address is
   valid. */

/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat);
if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mold of a valid e-mail address. */
	alert(errors['incorremail']);
	return false;
}
var user=matchArray[1];
var domain=matchArray[2];

// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
    alert(errors['emailpartbefore']);
    return false;
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        alert(errors['ipinvalid']);
		return false;
	    }
    }
    return true;
}

// Domain is symbolic name
var domainArray=domain.match(domainPat);
if (domainArray==null) {
    alert(errors['emailpartafter']);
    return false;
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding 
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g");
var domArr=domain.match(atomPat);
var len=domArr.length;
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>6) {
   // the address must end in a two letter or other TLD including museum
   alert(errors['addrend']);
   return false;
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr = errors['nohostname'];
   alert(errStr);
   return false;
}

// If we've got this far, everything's valid!
return true;
}


/*  validate password */
function checkPassword(pwfld) {
  var valid = true;
  var pwvalue = trim(pwfld.value);

  if (pwvalue) {
    /*  check for valid length */
    var pwlen = pwvalue.length;
    if ((pwlen < 4) || (pwlen > 255)) {
      valid = false;
      if (pwlen < 4) {
        alert(errors['pwtooshort']);
       }
      else {
        alert(errors['pwtoolong']);
       }
    }
    else {
      /*  check for valid chars */
      var last = pwlen-1;
      if ((pwvalue.charAt(0) == '@') || (pwvalue.charAt(last) == '%')) {
        valid = false;
        if (pwvalue.charAt(0) == '@') {
          alert(errors['pwnobegin']);
        }
        if (pwvalue.charAt(last) == '%') {
          alert(errors['pwnoend']);
        }
      }
    } 
  } 

  if (!valid) {
     pwfld.value = "";
     pwfld.focus();
  }

  return valid;
}


/*  validate username */
function checkUsername(usrnmfld) {
  var valid = true;
  var usrnmvalue = trim(usrnmfld.value);

  if (usrnmvalue) {
    /*  check for valid length */
    var ulen = usrnmvalue.length;
    if ((ulen < 4) || (ulen > 255)) {
      valid = false;
      if (ulen < 4) {
        alert(errors['untooshort']);
       }
      else {
        alert(errors['untoolong']);
       }
    }
    else {
      /*  check for valid chars */
      var last = ulen-1;
      if ((usrnmvalue.charAt(0) == '@') || (usrnmvalue.charAt(last) == '%')) {
        valid = false;
        if (usrnmvalue.charAt(0) == '@') {
          alert(errors['unnobegin']);
        }
        if (usrnmvalue.charAt(last) == '%') {
          alert(errors['unnoend']);
        }
      }
      if (valid) {
        /*  check for spaces in username - not allowed */
        var re = /\s/g;
        if (usrnmvalue.search(re) != -1) {
          alert(errors['unnospaces']);
          valid = false;
        }
      } 
    } 
  } 

  if (!valid) {
     usrnmfld.value = "";
     usrnmfld.focus();
  }

  return valid;
}

function submitenter(myfield, e) {
  var keycode;
  if (window.event) {keycode = window.event.keyCode;}
  else if (e) {keycode = e.which;}
  else { return true; }
  if (keycode == 13) {
   myfield.form.submit();
   return false;
  }
  else {
   return true;
  }
}


function limitText(limitField, limitCount, limitNum) {
  if (limitField.value.length > limitNum) {
    limitField.value = limitField.value.substring(0, limitNum);
  } 
  else {
    if (limitCount) {
     limitCount.value = limitNum - limitField.value.length;
    }
  }
}

/* from Javascript Bible */
function format(expr, decplaces) {

  // raise incoming value by power of 10 times the number
  // of decimal places; round to an integer; convert to string
  var str = "" + Math.round(eval(expr) * Math.pow(10,decplaces));

  // pad small value string with zeros to the left of round number
  while (str.length <= decplaces) {
    str = "0" + str;
  }

  // establish location of decimal point
  var decpoint = str.length - decplaces;

  // assemble final results from: 
  //  a) the string up to the position of the decimal point;
  //  b) the decimal point; and
  //  c) the balance of the string. Return finished product
  return str.substring(0, decpoint) + "." + str.substring(decpoint, str.length);
}

function dollarize(expr, theLang) {
  if (!theLang) {
    theLang = "en";
  }
  var dollarVal = "";
  if (theLang.indexOf("fr") == -1) {
    dollarVal += "$";
  }
  dollarVal += format(expr,2);
  return dollarVal;
}

function printPage() {
  var errMsg;
  errMsg = errors['sysnosupp'] + "\\n";
  errMsg += errors['useprintbtn'];

  if (window.print) {
    window.print();
  }
  else if (navigator.appVersion.indexOf("Mac") != -1) {
    alert(errMsg);
  }
  else {
    alert(errMsg);
  }
}

/********************  Date Utility functions *****************************/

/** checkYear **/
function checkYear(yearVal) {
  var valid = true;
  if ((yearVal == null) || (yearVal == "")) {
    valid = false;
  }
  if (yearVal != null && yearVal != "") {
    if (!isInteger(yearVal)) {
      valid = false;
    }
    if (yearVal.length != 4) {
      valid = false;
    }
  }
  return valid;
}

/** buildDate - builds the date form the individual date fields **/
function buildDate(fieldName) {
  // first, get all date values
  var monthField = "month_" + fieldName;
  var dayField = "day_" + fieldName;
  var yearField = "year_" + fieldName;

  var theForm = document.forms[0];
  var month = theForm[monthField];
  var day = theForm[dayField];
  var year = theForm[yearField];
  var monthVal;
  var dayVal;
  var yearVal;

  if (month != null) {
    monthVal = month.options[month.selectedIndex].text;
  }
  if (day != null) {
    dayVal = day.options[day.selectedIndex].value;
    if (dayVal) {
      dayVal = LZ(dayVal);
    }
  }
  if (year != null) {
    if (year.type.indexOf("select") != -1) {
      indx = year.selectedIndex;
      if (indx < 0) { indx = 0; }
      yearVal = year.options[indx].value;
    }
    else {
      yearVal = year.value;
    }
  }
  var msg = "";
  var valid = true;

  var dateStr = "";
  if ( (monthVal != null && monthVal != "") &&
       (dayVal != null && dayVal != "") &&
       (yearVal != null && yearVal != "")) {

    if (year.type.indexOf("select") == -1) {
      if (checkYear(yearVal) == false) {
        valid = false;
        msg += errors['yrmustbe4'] + "\\n";
        year.value = "";
       }
    }
    //dateStr = monthVal + " " + dayVal + " " + yearVal;
    dateStr = dayVal + " " + monthVal + " " + yearVal;
  }

  if (!valid) {
    alert(msg);
  }
  else {
    if (theForm[fieldName]) {
      theForm[fieldName].value = dateStr;
    }
  }
  return valid;
}


/** setDate **/
function setDate(theForm, fldName, dateObj) {
  var month = LZ(dateObj.getMonth() + 1);
  var day = LZ(dateObj.getDate());
  var year = dateObj.getFullYear();

  // date pick list field - clear each field appropriately
  var monthFld = "month_" + fldName;
  var dayFld = "day_" + fldName;
  var yearFld = "year_" + fldName;
  theForm[monthFld].value = month;
  theForm[dayFld].value = day;
  theForm[yearFld].value = year;

  buildDate(fldName);
  return(1);
}

function isValidUSZip(value) {
   var re = /^\d{5}([\-]\d{4})?$/;
   return (re.test(value));
}

function checkZip(zipfld, countryfld) {
  var valid = true;
  var countryval;
  if (document.forms[0][countryfld]) {
    var selectedIndex = document.forms[0][countryfld].selectedIndex;
    if (selectedIndex >= 0) {
      countryval = document.forms[0][countryfld].options[selectedIndex].text;
    }
  }

  // only validate US zip codes
  if (countryval && (countryval.indexOf("United States") != -1)) {
    if (document.forms[0][zipfld]) {
      var zipcode = strip(document.forms[0][zipfld].value);
      if (zipcode) {
        valid = isValidUSZip(zipcode);
        if (valid) {
          if (document.forms[0].section.value == "myprofile") {
            proftrackChange();
          }
        }
        else {
         alert(errors['zipinvalid'] + "\n" + errors['zipreenter']);
         document.forms[0][zipfld].value = "";
         setTimeout("document.getElementById('" + zipfld + "').focus();",1);
         setTimeout("document.getElementById('" + zipfld + "').select();",1);
        }
      }
    }
  }
  return valid;
}
/** check email fields   **/
function emailValidate(theForm) {
  var valid = true;
  var email_1;
  var email_2;

  if (theForm.email) {
    email_1 = trim(theForm.email.value);
  }
  if (theForm.email2) {
    email_2 = trim(theForm.email2.value);
    if (!email_1 || email_1 == "") {
      alert(errors['mustenteremail']);
      theForm.email.focus();
      theForm.email.select();
      valid = false;
    }
    else if (!email_2 || email_2 == "") {
      alert(errors['retypeemail']);
      theForm.email2.focus();
      theForm.email2.select();
      valid = false;
    }
    else if (email_1 && (email_1.toLowerCase() != email_2.toLowerCase())) {
      theForm.email.value = "";
      theForm.email2.value = "";
      alert(errors['emailnomatch']);
      theForm.email.focus();
      theForm.email.select();
      valid = false;
    }
  }
  return valid;
}

function setInnerText(elementId, text) {
  var element;
  if (document.getElementById) {
    element = document.getElementById(elementId);
  }
  else if (document.all) {
    element = document.all[elementId];
  }
  if (element) {
    if (typeof element.textContent != 'undefined') {
      element.textContent = text;
    }
    else if (typeof element.innerText != 'undefined') {
      element.innerText = text;
    }
    else if (typeof element.removeChild != 'undefined') {
      while (element.hasChildNodes()) {
        element.removeChild(element.lastChild);
      }
      element.appendChild(document.createTextNode(text)) ;
    }
  }
}

/**  obj is the element where we want to insert something
**   text is the string which will be inserted
**/ 
function insertAtCaret(obj, text) {

  if (document.selection) {    // Go the IE way 
      /* first, focus the object we want to work with */
      obj.focus();

      /* create a TextRange based on the document.selection */ 
      var range = document.selection.createRange();

      /* if the range is not part of our obj, stop processing here */ 
      if (range.parentElement() != obj) {
	  return false;
      }

      /* save the current value */
      var orig = obj.value.replace(/\r\n/g, "\n");

      /* replace the text */ 
      range.text = text;

      /* now get the new content and save it into a temporary variable */ 
      var actual = tmp = obj.value.replace(/\r\n/g, "\n");

      /* find the first occurance where the original differs
       * from the actual content.
       */ 
      for (var diff = 0; diff < orig.length; diff++) {
	  if (orig.charAt(diff) != actual.charAt(diff)) break;
      }

      /* to get the real start position, iterate through
       * the string searching for the whole replacement
       * text - "abc", as long as the first difference is not reached.
       */ 
      for (var index = 0, start = 0; tmp.match(text) && (tmp = tmp.replace(text, "")) && index <= diff; index = start + text.length) {
	  start = actual.indexOf(text, index);
      }
  }
  else if (obj.selectionStart) {    // Go the Gecko way
      /* find the start and end Position */ 
      var start = obj.selectionStart;
      var end   = obj.selectionEnd;

      /* obj is a textarea or input field */ 
      obj.value = obj.value.substr(0, start) 
                  + text 
		  + obj.value.substr(end, obj.value.length);
  }
		
   if (start != null) {
       setCaretTo(obj, start + text.length);
   }
   else {
       obj.value += text;
   }
}
	

function setCaretTo(obj, pos) {
  /* create a TextRange, set the internal pointer to
   * a specified position and show the cursor at this position
   */ 
  if (obj.createTextRange) {
      var range = obj.createTextRange();
      range.move('character', pos);
      range.select();
  }
  else if (obj.selectionStart) {
    /* Gecko is a little bit shorter on that. Simply
     * focus the element and set the selection to a specified position
     */ 
    obj.focus();
    obj.setSelectionRange(pos, pos);
  }
}

function setFormLang(langCode) {
  var thisURL = window.location.href;
  var idx = thisURL.indexOf('formLang=');
  if (idx != -1) {
    thisURL = thisURL.substring(0, idx);
  }
  else {
    thisURL += ";";
  }
  thisURL += "formLang=" + langCode;
  window.location.href = thisURL;
}


function setLang(cookieName, langCode, thisURL) {
  set_cookie( cookieName, langCode, 7, '/', 'etdadmin.com', '');
  if (!thisURL) {
    thisURL = window.location.href;
  }
  var hashtag;
  var idx = thisURL.indexOf('#');
  if (idx != -1) {
    hashtag = thisURL.substring(idx+1);
    thisURL = thisURL.substring(0, idx);
  }

  var u_idx = thisURL.indexOf('uploaded=');
  if (u_idx != -1) {
    thisURL = thisURL.substring(0, u_idx-1);
  }

  var x_idx = thisURL.indexOf('x=');
  if (x_idx != -1) {
    thisURL = thisURL.substring(0, x_idx-1);
  }

  window.location.href = thisURL;
  if (hashtag && hashtag !== "page_1") {
    window.location.hash = hashtag;
  }
}

/*************************************************************************
* get_cookie('cookie_name'); 
* replace cookie_name with the real cookie name, '' are required
*************************************************************************/
function get_cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	var i = '';
	
	for ( i = 0; i < a_all_cookies.length; i++ ) {
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ) 
	{
		return null;
	}
}

/*************************************************************************
* set_cookie   - only the first 2 parameters are required, 
* the cookie name, the cookie value. Cookie time is in milliseconds, 
* so the below expires will make the number you pass in the set_cookie 
* function call the number of days the cookie lasts, if you want it to 
* be hours or minutes, just get rid of 24 and 60.
* 
* Generally you don't need to worry about domain, path or secure for most 
* applications so unless you need that, leave those parameters blank in 
* the function call.
****************************************************************************/
function set_cookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	// if the expires variable is set, make the correct expires time, the
	// current script below will set it for x number of days, to make it
	// for hours, delete * 24, for minutes, delete * 60 * 24
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	//alert( 'today ' + today.toGMTString() );// this is for testing purpose only
	var expires_date = new Date( today.getTime() + (expires) );
	//alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

/*************************************************************************
* delete_cookie   - this deletes the cookie when called
*************************************************************************/
function delete_cookie( name, path, domain ) {
	if ( get_cookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function getFlashVersion(){
  // ie
  try {
    try {
      // avoid fp6 minor version lookup issues
      // see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
      var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
      try { axo.AllowScriptAccess = 'always'; }
      catch(e) { return '6,0,0'; }
    } catch(e) {}

    return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
  // other browsers
  } catch(e) {
    try {
      if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
        return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
      }
    } catch(e) {}
  }
  return '0,0,0';
}
/** ------------- These functions are added by Uday Desai in Match 2011 ---- **/
/** ------------- To convert all front end dates to local and display as YYYY-MM-DD HH:MM:SS format) --- **/
function isValidDate(d) {
	if ( Object.prototype.toString.call(d) === "[object Date]" ) {
		return true;
		if ( isNaN( d.getTime() ) ) {  // d.valueOf() could also work
			return false; // date is not valid
		}
		else {
			return true; // date is valid
		}
	}
	else {
		return false;// not a date
	}
}
function correctDate (DateStr) {
        DateStr = DateStr.replace( /AM/i, " AM");
        DateStr = DateStr.replace( /PM/i, " PM");
        DateStr = DateStr.replace( /EST\s*$/, " EST");
        DateStr = DateStr.replace( /EDT\s*$/, " EDT");
	DateStr = DateStr.replace( / at /, " ");
        return DateStr;
        }
function pad(n){return n<10 ? '0'+n : n}
function getOffsetHrMin(mins) {
	var Hrs = Math.floor(mins / 60);
	var minutes = '00' + mins % 60;
	return Hrs + ':' + pad(mins % 60);
//	return Hrs + ':' +  minutes.substr(minutes.length - 2);
}
/* use a function for the exact format desired... */
function ISODateString(d){
if (isValidDate(d)) {
 return d.getUTCFullYear()+'-'
      + pad(d.getUTCMonth()+1)+'-'
      + pad(d.getUTCDate())+'T'
      + pad(d.getUTCHours())+':'
      + pad(d.getUTCMinutes())+':'
      + pad(d.getUTCSeconds())+'Z';
 }
else return "";
}
function OLDDateTimeFormat(d){
 return d.getFullYear()+'-'
      + pad(d.getMonth()+1)+'-'
      + pad(d.getDate())+' '
      + pad(d.getHours())+':'
      + pad(d.getMinutes())
}
function ETDDateFormat(d){
if (isValidDate(d)) {
 return d.getFullYear()+'-'
      + pad(d.getMonth()+1)+'-'
      + pad(d.getDate());
 }
else return "";
}
function ETDDateTimeFormat(d) {
  if (isValidDate(d)) {
	var TZO = d.getTimezoneOffset();
	if ( TZO > 0) {
		return OLDDateTimeFormat(d)+' (UTC' + '-' + getOffsetHrMin(TZO) + ')';
	}
	else {
		TZO = 0 - TZO;
		return OLDDateTimeFormat(d)+' (UTC' + '+' + getOffsetHrMin(TZO) + ')';
	}
  }
  else return "";
}

/** Following code modifies the Date object to include "format" as a new method **/
Date.prototype.format = function (mask) {
        if (( mask == 'ETDDateTimeFormat')&& ! isNaN(this))
                return ETDDateTimeFormat(this);
        else if ( (mask == 'ETDDateFormat') && ! isNaN(this)) {
                return ETDDateFormat(this);
        }
	return "";
};
/*** ------------------------------------------------------------------------------------- ***/
 
function isValidYear(elem){
	var numericExpression = /^[0-9]+$/;
	if(((elem.value.length === 4) && (elem.value.match(numericExpression))) || (elem.value.length === 0)){
	  if (document.forms[0].changed) {
	    document.forms[0].changed.value = 1;
	    needToConfirm = true;
	  }
	  return true;
	}else  {
		alert(errors['validYear']);
		elem.focus();
		return false;
	}
}

