//---------------------------------------------------
// name:    utilities.js
// author:  john a. vivian, garry harstad, timothy m. eagan
// date:    03-may-2000
// purpose: javascript utility functions
//---------------------------------------------------

//----------------------------------------------------------------------------
// G.Harstad; used to sniff browser (4+) ie is true or ns is true respectively
//----------------------------------------------------------------------------
var ie = (document.all)
var ns = (document.layers)

//-------------------------------------------
// timothy m. eagan; Trim Form elements function
//-------------------------------------------
function TrimElements() {

  for (i = 0; i < document.forms[0].length; i++) {
    var WorkString = document.forms[0].elements[i].value;

    for (c = WorkString.length; c > 0; c--) {                
      char = WorkString.substr(c,1);          
      if (char != " " && char != "") { 
        break; 
      }
    }
		//alert('-' + workstring + '-');
    var NewString = WorkString.substring(0, c + 1);
		//alert('-' + newstring + '-');
    document.forms[0].elements[i].value = NewString;
  }

}

//-------------------------------------------
// timothy m. eagan; Increase Value function
//-------------------------------------------
function IncreaseValue(object) {                      
  nbr = new Number(object.value);
  nbr = nbr + 1;
  object.value = nbr;
}
   
//-------------------------------------------   
// timothy m. eagan; Decrease Value function
//-------------------------------------------
function DecreaseValue(object) {                      
  nbr = new Number(object.value);
  nbr = nbr - 1;
  object.value = nbr;
}

//-------------------------------------------
// timothy m. eagan; Validate a date
//-------------------------------------------
function CheckDate(monthObj, dayObj) { 
  month = monthObj.selectedIndex + 1;
  day = dayObj.selectedIndex + 1;
  
  if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) {
    return true;
  }
  
  if (month == 2 && day > 29) {
    return true;
  }    
  
  return false;
}

//-----------------------------------------------
// timothy m. eagan 2006 - Validate a date string
//-----------------------------------------------
function CheckDateString(dateStr) {

	//reformat single digit months, single digit days and 2 digit years 
	if (dateStr.substr(1,1) == '/' || dateStr.substr(1,1) == '-') dateStr = '0' + dateStr;
	if (dateStr.substr(4,1) == '/' || dateStr.substr(4,1) == '-') dateStr = dateStr.substr(0,3) + '0' + dateStr.substr(3,6); 
	tempYY = dateStr.substr(8,1);
	if ( tempYY == '' || tempYY == ' ') {
		tempYY = dateStr.substr(6,2);
		if (tempYY < '50') dateStr = dateStr.substr(0,6) + '20' + dateStr.substr(6,2);
		else dateStr = dateStr.substr(0,6) + '19' + dateStr.substr(6,2);
	}
	
	// extract a 2 digit month, a 2 digit day and a 4 digit year
	var mm   = dateStr.substr(0,2);
	var sep1 = dateStr.substr(2,1);
	var dd   = dateStr.substr(3,2);
	var sep2 = dateStr.substr(5,1);
	var yyyy = dateStr.substr(6,4);
	
	// vaildate the date seperators
	if (sep1 != sep2) return false;
	if (sep1 != '/' && sep1 != '-') return false;
  
	// validate the month and day
	if (mm < 1 || mm > 12 || dd < 1 || dd > 31) return false; 
  if ((mm == 4 || mm == 6 || mm == 9 || mm == 11) && dd == 31) return false;  
  if (mm == 2 && dd > 29) return false;
	
	// validate the year
  if (yyyy < '1951' || yyyy > '2099') return false;
  
	// date is valid - return rebuilt string
	dateStr = mm + '/' + dd + '/' + yyyy;
  return dateStr;
}

//------------------------------------------------
// timothy m. eagan; Delete Confirmation function
//------------------------------------------------
function ConfirmDelete(IDvalue)
{
  var agree = false;
  agree = confirm("Permanently delete this record from the database?\n");
  if (agree) {
        self.location.href="delete.cfm?RecordID=" + IDvalue;
  }
}

//------------------------------------------------
// Confirm Archive
//------------------------------------------------
function ConfirmArchive (IDvalue)
{
  var agree = false;
  agree = confirm("Archive this collection?\n");
  if (agree)
  {
    self.location.href="archive.cfm?RecordID=" + IDvalue;
  }
}

//----------------------------------------------------------------------------
// Validate an email address by checking for bla@bla.bla
//----------------------------------------------------------------------------
function validateemail(mail)
 {
  invalidChars = " /:,;"
  if (mail == "") { return false; }
  for (i = 0; i < invalidChars.length; i++)
  {
   badChar = invalidChars.charAt(i)
   if (mail.indexOf(badChar,0) != -1) { return false; }
  }
  atPos = mail.indexOf("@",1)
  if (atPos == -1) { return false; }
  if (mail.indexOf("@",atPos+1) != -1) { return false; }
  periodPos = mail.indexOf(".",atPos)
  if (periodPos == -1) { return false; }
  if (periodPos+4 > mail.length) { return false; }
  return true;
}

 //----------------------------------------------------------------------------
 // Function that pre-selects a select-box option by searching for the optvalue
 // passed to it, finding the indexOf number and preselecting that option.
 // [requires the formname, selectbox name, and option value as string arguments]
 // defaults at option 'one' if something goes wrong
 //
 // 13-02-2001 timothy m. eagan - changed to accomodate multiple selections
 //----------------------------------------------------------------------------
 function preselect(formname, selectname, myoptvalue)
 {
   var myindexnum = 0;  // default index option number to 0 in case myoptvalue not matched
   
   //alert('formname='+formname+'\nselectbox name='+selectname+'\nmyoptvalue='+myoptvalue)
   
   var optlen = "document."+formname+"."+selectname+".options.length"
   optionslength = eval(optlen)
   for (optnum = 1; optnum < optionslength; optnum++)
   {
     var optval = "document."+formname+"."+selectname+".options["+optnum+"].value"
     optionvalue = eval(optval)
     //alert('optval='+optval+'\noptionvalue='+optionvalue)
     if (optionvalue == myoptvalue)
     {
       myindexnum = optnum
     }
   }

   //var preselectit = "document."+formname+"."+selectname+".selectedIndex="+myindexnum
   var preselectit = formname + "." + selectname + ".options[" + myindexnum + "].selected = true";
   
   //alert(preselectit)
   eval(preselectit)
 }


 //------------------------------------------------------------------
 // Function that selects all options for the select-box passed to it
 // Timothy M. Eagan
 //------------------------------------------------------------------
 function selectAll(formname, selectname) {   
   optionslength = eval("document."+formname+"."+selectname+".options.length");
   
   for (i=0; i < optionslength; i++) {
     eval(formname+"."+selectname+".options[i].selected=true")
   }
 }



 //------------------------------------------------------------------
 // Function that deselects all options for the select-box passed to it
 // Timothy M. Eagan
 //------------------------------------------------------------------
 function selectNone(formname, selectname) {      
   optionslength = eval("document."+formname+"."+selectname+".options.length");
   
   for (i=0; i < optionslength; i++) {
     eval(formname+"."+selectname+".options[i].selected=false")
   }
 }

  
//----------------------------------------------------------------------------
// Create a JavaScript array of months of the year
// G.Harstad 2000
//----------------------------------------------------------------------------  
var monthsofyear = new Array(12)
  monthsofyear[1]  = "Jan"
  monthsofyear[2]  = "Feb"
  monthsofyear[3]  = "Mar"
  monthsofyear[4]  = "Apr"
  monthsofyear[5]  = "May"
  monthsofyear[6]  = "Jun"
  monthsofyear[7]  = "Jul"
  monthsofyear[8]  = "Aug"
  monthsofyear[9]  = "Sep"
  monthsofyear[10] = "Oct"
  monthsofyear[11] = "Nov"
  monthsofyear[12] = "Dec"

//----------------------------------------------------------------------------
// Function that writes a select box named mm.
// creates a pull down for Month
// G.Harstad 2000
// 07-05-2000; timothy m. eagan; added selectname parameter
//----------------------------------------------------------------------------
function makemonth(selectname)
{
  var selectstart = "<select name='" + selectname + "mm'>\n"
  var selectend   = "</select>\n"
  var mmoptions  = ""
  for (mm=01; mm<=12; mm++)
  {
    mmoptions += "<option value='"+mm+"'>" + monthsofyear[mm] + "</option>\n"
  }
  var allofit = selectstart+mmoptions+selectend
  //alert(allofit)
  document.writeln(allofit)
}
  
//----------------------------------------------------------------------------
// Function that writes a select box named dd.
// creates a pull down for DayOfMonth
// G.Harstad 2000
// 07-05-2000; timothy m. eagan; added selectname parameter
//----------------------------------------------------------------------------
function makeday(selectname)
{
  var selectstart = "<select name='" + selectname + "dd'>\n"
  var selectend   = "</select>\n"
  var ddoptions  = ""
  for (dd=01; dd<=31; dd++)
  {
    ddoptions += "<option value='"+dd+"'>"+dd+"</option>\n"
  }
  var allofit = selectstart+ddoptions+selectend
  //alert(allofit)
  document.writeln(allofit)
}

//----------------------------------------------------------------------------
// Function that writes a select box named yyyy.
// creates a pull down for Year
// G.Harstad 2000
// 07-05-2000; timothy m. eagan; added selectname parameter
// 12-05-2000; timothy m. eagan; added startvalue parameter
//----------------------------------------------------------------------------
function makeyear(selectname, startvalue) {
  var todaysdate = new Date()
  var thisyear   = todaysdate.getYear()

  if (startvalue > 0 && startvalue < thisyear) {
    var startyear = startvalue - 1
  } else {
    var startyear    = (thisyear - 1)
  }

  var endyear      = (thisyear + 5)
  var selectedyear = (thisyear)
  var selectstart  = "<select name='" + selectname + "yyyy'>\n"
  var selectend    = "</select>\n"
  var yyyyoptions  = ""
  for (yyyy=startyear; yyyy<=endyear; yyyy++) {
    if (yyyy==selectedyear)
      { yyyyoptions += "<option value='"+yyyy+"' selected>"+yyyy+"</option>\n" }
    else
      { yyyyoptions += "<option value='"+yyyy+"'>"+yyyy+"</option>\n" }
  }
  var allofit = selectstart+yyyyoptions+selectend
  
  //alert(allofit)
  document.writeln(allofit)
}
//----------------------------------------------------------------------------
// function that replaces problematic characters in all form elements.
// Timothy M. Eagan BX.COM 2001
//----------------------------------------------------------------------------

    function RemoveChar() {
      
        for (var i=0; i < document.forms[0].length; i++) {
          elementString = document.forms[0].elements[i].value;
    
          // replace forward slashes with a backward slash
          re = /\\/gi;
          newstr = elementString.replace(re, "/");
          elementString = newstr;
    
          // replace less than with a left bracket
          re = new RegExp("<", "gi");
          newstr = elementString.replace(re, "[");
          elementString = newstr;
    
          // replace greater than with a right bracket
          re = new RegExp(">", "gi");
          newstr = elementString.replace(re, "]");
          elementString = newstr;
    
          // replace single quotes with an accent
          //re = new RegExp("'", "gi");
          //newstr = elementString.replace(re, "`");
          //elementString = newstr;
    
          // replace double quotes with two accents
          re = new RegExp('"', 'gi');
          newstr = elementString.replace(re, "``");      
          document.forms[0].elements[i].value = newstr;      
        }
    } 
     
//----------------------------------------------------------------------------
// function that validates a text field value as an Integer.
// (e.g. the residential street num).  If not an integer it focuses back to the
// formfield in question and selects it.
// Requires the formname and fieldname to validate.
// G.Harstad 2000
//----------------------------------------------------------------------------
function checknum(whichform, whichfield)
{
  var dompath = "document."+whichform+"."
  var fieldvalue = eval (dompath+whichfield+".value")
  //alert(fieldvalue)
  if (parseInt(fieldvalue))
  {
    //alert("OK, is an integre")
    eval (dompath+whichfield+".value="+parseInt(fieldvalue))
  }
  else
  {
    var clickedit = confirm("Sorry!\n'Street Number' must be a whole number\nClick cancel to go on, or ok to ammend\n\t\t-Administrator-")
    if (clickedit)
    {
      eval (dompath+whichfield+".focus()")
      eval (dompath+whichfield+".select()")
    }
    else
    {
      eval (dompath+whichfield+".value=''");
      eval (dompath+whichfield+".blur()");
    }
  }
}
