//*******************************************************************
function FormatPhone(pStrPhoneNumberToFormat)
// jtw 12/24/01 (modified by pjs 8/6/2008)
//
//   formats a phone number in a text box
//
// example:
//   <INPUT TYPE=TEXT NAME=txtTest onBlur="this.value=FormatPhone(this.value);">
//
// passed:
//   pStrPhoneNumber - string var with the phone number to be formatted
// returns:
//   FormatPhone - returns the formatted phone number
//   
{

  var strPhoneNumber = '';
  var strExtention = '';
  var intCharacterPosition = 0;
  var blnDoneExtractingPhoneNumber = false;
  var strChar = '';
  var blnIsValid = false;
  var strFormattedPhoneNumber = '';

  // start by seperating the phone number from any 
  // extention or other alpha-numeric data
  for (intCharacterPosition=0; intCharacterPosition<pStrPhoneNumberToFormat.length; intCharacterPosition++)
  {
    strChar = pStrPhoneNumberToFormat.charAt(intCharacterPosition);
    if (blnDoneExtractingPhoneNumber==false)
    {
      switch (strChar)
      {
        case "0":
        case "1":
        case "2":
        case "3":
        case "4":
        case "5":
        case "6":
        case "7":
        case "8":
        case "9":
          // numeric charaters (there has got to be a better way to do this)
          strPhoneNumber += strChar;
          if (strPhoneNumber.length>=10)
          {
            // once we have 10 numbers we've got all we need for a phone number
            blnDoneExtractingPhoneNumber = true;
          }
          break;
        case "-":
        case "(":
        case ")":
        case "/":
        case " ":
          // these are all considered valid "phone number" characters
          break;
        default:
          // alpha characters terminate the phone number formatting
          blnDoneExtractingPhoneNumber = true;
          strExtention = strChar;
      } // switch (strChar)
    } // if (blnDoneExtractingPhoneNumber==false)
    else
    {
      strExtention += strChar;
    }
  } // for (intCharacterPosition=0; intCharacterPosition<pStrPhoneNumberToFormat.length; pStrPhoneNumberToFormat++);

  // try to determine if it's a valid phone number or not
  if (strPhoneNumber.substring(0,1)=="01")
  {
    // international phone numbers start with 011 or 01
    blnIsValid = false;
  }
  else if (strPhoneNumber.length==7)
  {
    // 7 digits is only missing an area code
    strPhoneNumber = "207" + strPhoneNumber;
    blnIsValid = true;
  }
  else if (strPhoneNumber.length==10)
  {
    // 10 characters has all of the required elements (area code + 7 digit number)
    blnIsValid = true;
  } 
  else
  {
    // if the phone number is not 7 or 10 characters long, we really don't know what to do with it
    blnIsValid = false;
  }

  // if the phone number is not valid, return it as it is
  if (blnIsValid==false)
  {
    return pStrPhoneNumberToFormat;
  }
  // if the phone number is valid, format it
  else
  {
    // format the phone number
    // 8/6/2008 pjs removed "(xxx) " formatting for area code, replaced with "-"
    strFormattedPhoneNumber = strPhoneNumber.substring(0,3) + "-"
    strFormattedPhoneNumber += strPhoneNumber.substring(3,6) + "-" + strPhoneNumber.substring(6,10);
    // make sure there is a space between the phone number
    // and the extention
    if (strExtention.charAt(0)!=" ")
    {
      strFormattedPhoneNumber += " ";
    }
    // add the extention (untouched)
    strFormattedPhoneNumber += strExtention;
    // return a value to the calling procedure
    // (i don't know why but this might be important)
    return strFormattedPhoneNumber;
  } // if (blnIsValid==false)
} 
//*******************************************************************
function ChangeAvailableDays(pstrSelectID,pintSelectedDayValue,pintMonthValue,pintYearValue)
{
  // pjs 8/6/2008
  // this function builds a drop down list containing the number of days 1-x. x being the
  // maximum day for the month selected.
  // this function is called when either the month or year of the corresponding date are changed
  // the reason it's called when the corresponding month is changed is obvious
  // the reason it's called when the corresponding year is changed is for February length calculations 
  
  // parameters:
  // pstrSelectID : id of the day drop down where manipulating
  // pintSelectedDayValue: the day current selected in the day drop down
  // pintMonthValue: the month of the date
  // pintYearValue: the year of the date

	var objSelect;
  var selected;
	var days;
 
  // set local object to the appropriate drop down
	objSelect = document.getElementById(pstrSelectID);

  // remove all options form drop down
	objSelect.options.length = 0;

  // determine month length
	switch(pintMonthValue)
	{
		//28: February
		case "2": if (isLeapYear(pintYearValue))// is it a leap year?
					    {
						    days = 29;	
					    }
				      else
              {
					      days = 28;
				      }
			        break;
		//30: April,June,September,November
		case "4":
		case "6":
		case "9":
		case "11": days = 30;
			         break;
		//31: January,March,May,July,August,October,December
		case "1": 
		case "3":
		case "5":
		case "7":
		case "8":
		case "10":
		case "12": 
    //if user changes year first, before specifying a month we need this default 
    //to populates the day drop down with values, otherwise we won't have any days
    //to choose from
    default:  days = 31;
	}

  //loop threw avaiable days creating an drop down option for each available day
  objSelect.options[0]= new Option("DD",0,false,false);
	for(i=1;i<=days;i++)
	{
    // variable used to set day back to previously select value
    // where assuming the current day isn't the selected one 
    //until we figure it out later
    selected = false;

    // is the current day the previously selected day?
    // [i] has to be incremented by one since the option 
    // array is 0 based and the days of the month aren't
    if (i == pintSelectedDayValue)
    {
      // if it is set the selected variable to true
      selected = true;
    }
    // [i] has to be incremented by one for the text and value of the option
    // since the option array is 0 based and the days of the month aren't
    objSelect.options[i]= new Option(i,i,false,selected);
	}
}
//*******************************************************************
function isLeapYear(pintYear)
{
  // pjs 8/6/2008
  // function determines if passed year is a leap year

  // parameters:
  // pintYear: year to determine if it's a leap year or not

  // How to determine if a year is a leap year taken from http://support.microsoft.com/kb/214019
  // To determine whether a year is a leap year, follow these steps: 
  // 1.	If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5.
  // 2.	If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4.
  // 3.	If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5.
  // 4.	The year is a leap year (it has 366 days).
  // 5.	The year is not a leap year (it has 365 days). 

  // assume the year is not a leap year until we can determine it is
	var isLeap = false; //step 5

  
	if(pintYear % 4 == 0)//step 1
	{
		if(pintYear % 100 == 0) //step 2
		{
			if(pintYear % 400 == 0)// step 3
			{
				isLeap = true; //step 4
			}
		}
		else
		{
			isLeap=true; //step 4
		}

	}//if(pintYear % 4 == 0)

	return isLeap;
}
//*******************************************************************
function ValidateForm()
{
    var blnsaveform = true;
  
  //RANDY LINK Change:  previously, form name was "mainform"
  var objForm = document.getElementById("aspnetForm")
  var backgroundColor = "#FFFF9C"

  // set the background colors of form elements to appropriate color, it may be red
  // if previous submit was unsuccessful,I do this here so we can mark all the 
  // missing or invalid elements to yellow later in the function. I'll
  // clean up the rest of the formatting, before the 
  // ValidateFrom function is completed, see CorrectFormElementFormatting() for more info
  ResetBackgroundColors(objForm)

  //-----requestor information---------------------------------------
  // requestor first name
  if (trim(objForm.requestorfirstname.value + "") == "")
  {
    objForm.requestorfirstname.style.backgroundColor = backgroundColor;    
    blnsaveform = false;
  }

  //requestor last name
  if (trim(objForm.requestorlastname.value + "") == "")
  {
    objForm.requestorlastname.style.backgroundColor = backgroundColor;
    blnsaveform = false;
  }
  
  //requestor street address
  if (trim(objForm.requestorstreet.value + "") == "")
  {
    objForm.requestorstreet.style.backgroundColor = backgroundColor;
    blnsaveform = false;
  }
  
  //requestor city
  if (trim(objForm.requestorcity.value + "") == "")
  {
    objForm.requestorcity.style.backgroundColor = backgroundColor;
    blnsaveform = false;
  }
  
  //requestor state
  if (trim(objForm.requestorstate.value + "") == "")
  {
    objForm.requestorstate.style.backgroundColor = backgroundColor;
    blnsaveform = false;
  }
  
  //requestor zip
  if (trim(objForm.requestorzip.value + "") == "" || trim(objForm.requestorzip.value + "").length < 5 )
  {
    objForm.requestorzip.style.backgroundColor = backgroundColor;
    blnsaveform = false;
  }
  
  //requestor plus four -- if user specifed a plus four it has to be 4 characters long
  if (trim(objForm.requestorplusfour.value + "") != "")
  {
    //user has specified a plus four, is it 4 characters long?
    if (trim(objForm.requestorplusfour.value + "").length < 4)
    {
      objForm.requestorplusfour.style.backgroundColor = backgroundColor;
      blnsaveform = false;
    }
  }

  //requestor email -- if user specified an email it has to be valid
  if (trim(objForm.requestoremail.value + "") != "")
  {
    var strEmailAddress = trim(objForm.requestoremail.value)
    // is it a valid email?
    if (! IsValidEmail(strEmailAddress))
    {
      objForm.requestoremail.style.backgroundColor = backgroundColor;
      blnsaveform = false;
    }
  }
  
  //requestor day time telephone
  if (trim(objForm.requestordayphone.value + "") == "")
  {
    objForm.requestordayphone.style.backgroundColor = backgroundColor;
    blnsaveform = false;
  }

  //requestor relationship to baby
  if (trim(objForm.requestorrelationship.value + "") == "")
  {
    objForm.requestorrelationship.style.backgroundColor = backgroundColor;
    blnsaveform = false;
  }
  else
  {
    // if requestor relationship to baby is "other", the other explanation is now required
    if (objForm.requestorrelationship.value == "other")
    {
      //requestor relationship to baby other explanation
      if (trim(objForm.requestorrelationshipother.value + "") == "")
      {
        objForm.requestorrelationshipother.style.backgroundColor = backgroundColor;
        blnsaveform = false;
      }
    }
  }

/*  if(objForm.requestorhearaboutchkboxdr.checked == false && objForm.requestorhearaboutchkboxhospital.checked == false 
    && objForm.requestorhearaboutchkboxadvisor.checked == false && objForm.requestorhearaboutchkboxother.checked == false)
  {
    document.getElementById("requestorhearaboutdrtext").style.backgroundColor = backgroundColor;
    document.getElementById("requestorhearabouthospitaltext").style.backgroundColor = backgroundColor;
    document.getElementById("requestorhearaboutadvisortext").style.backgroundColor = backgroundColor;
    document.getElementById("requestorhearaboutothertext").style.backgroundColor = backgroundColor;
    blnsaveform = false;
  }
  // if other is checked we need an explanation
  else if (objForm.requestorhearaboutchkboxother.checked == true)
  {
      //requestor hear about alfond other explanation
      if (trim(objForm.requestorhearaboutother.value + "") == "")
      {
        objForm.requestorhearaboutother.style.backgroundColor = backgroundColor;
        blnsaveform = false;
      }
  }
*/
  //-----end requestor information-----------------------------------

  // ----- moms information -----------------------------------------
  //mother first name
  if (trim(objForm.momsfirstname.value + "") == "")
  {
    objForm.momsfirstname.style.backgroundColor = backgroundColor;
    blnsaveform = false;
  }

  //mother last name
  if (trim(objForm.momslastname.value + "") == "")
  {
    objForm.momslastname.style.backgroundColor = backgroundColor;
    blnsaveform = false;
  }

  //mother birth month
  if (objForm.momsmonth.value == '0')
  {
    objForm.momsmonth.style.backgroundColor = backgroundColor;
    blnsaveform = false;
  }

  //mother birth day
  if (objForm.momsday.value == '0')
  {
    objForm.momsday.style.backgroundColor = backgroundColor;
    blnsaveform = false;
  }

  //mother birth year
  if (objForm.momsyear.value == '0')
  {
    objForm.momsyear.style.backgroundColor = backgroundColor;
    blnsaveform = false;
  }
  //-----end moms information----------------------------------------

  //----- baby information-------------------------------------------
  //baby birth month
  if (objForm.babymonth.value == '0')
  {
    objForm.babymonth.style.backgroundColor = backgroundColor;
    blnsaveform = false;
  }

  //baby birth day
  if (objForm.babyday.value == '0')
  {
    objForm.babyday.style.backgroundColor = backgroundColor;
    blnsaveform = false;
  }

  //baby birth year
  if (objForm.babyyear.value == '0')
  {
    objForm.babyyear.style.backgroundColor = backgroundColor;
    blnsaveform = false;
  }

  //baby birth date type
/*  var radioChecked = false;
  var babybirthdatetypevalue = "";
  for(i=objForm.babybirthdatetype.length-1; i > -1; i--)
  {
    if (objForm.babybirthdatetype[i].checked)
    {
      radioChecked = true;
      //get the value of the checked birth date type, we use it
      //later to determine if the date makes sense
      babybirthdatetypevalue = objForm.babybirthdatetype[i].value;
    }
  }
  if(! radioChecked)
  {
    document.getElementById("babybirthdatetypeactualtext").style.backgroundColor = backgroundColor;
    document.getElementById("babybirthdatetypeexpectedtext").style.backgroundColor = backgroundColor;
    blnsaveform = false;
  }
*/

  //check if the baby birth dates make sense
  //i.e. if the baby birth date was in the past, it can't be flagged as an "Expected" birth date
  //or if the baby birth date is in the future it can't be flagged as an "Actual" birth date
  //we only want to check this if the user has submit a date and selected a type, otherwise it's a waste of time
/*  if(radioChecked && objForm.babyday.value != '0' && objForm.babymonth.value != '0' && objForm.babyyear.value != '0')
  {
    var todaysDate = new Date();
    var babyBirthDate = new Date();

    //since the setFullYear functions months are zero based we have to do a little conversion in order to 
    //to get the date right in the javascript date object
    babyBirthDate.setFullYear(parseInt(objForm.babyyear.value),(parseInt(objForm.babymonth.value) - 1),parseInt(objForm.babyday.value));

    if (babybirthdatetypevalue == 'actual')
    {
      // if the user specified that the baby's birth date is an "Actual" birth date
      // it can't be in the future, but it can be today
      if(babyBirthDate > todaysDate)
      {
        blnsaveform = false;
        objForm.babyday.style.backgroundColor = backgroundColor;
        objForm.babymonth.style.backgroundColor = backgroundColor;
        objForm.babyyear.style.backgroundColor = backgroundColor;
        document.getElementById("babybirthdatetypeactualtext").style.backgroundColor = backgroundColor;
        document.getElementById("babybirthdatetypeexpectedtext").style.backgroundColor = backgroundColor;
      }
    }
    else
    {
      // The user specified that the baby's birth date is an "Expected" birth date
      // it can't be in the past or today
      if(babyBirthDate <= todaysDate)
      {
        blnsaveform = false;
        objForm.babyday.style.backgroundColor = backgroundColor;
        objForm.babymonth.style.backgroundColor = backgroundColor;
        objForm.babyyear.style.backgroundColor = backgroundColor;
        document.getElementById("babybirthdatetypeactualtext").style.backgroundColor = backgroundColor;
        document.getElementById("babybirthdatetypeexpectedtext").style.backgroundColor = backgroundColor;
      }
    }
  }//if(radioChecked)
  */
  
  //baby hospital of delivery
  if (trim(objForm.babyhospital.value + "") == "")
  {
    objForm.babyhospital.style.backgroundColor = backgroundColor;
    blnsaveform = false;
  }
  else
  {
    // if hospital of delivery is "other" or "out-of-state facility", the explanation is now required
    // other = 00, out of state facility = 80
    if (objForm.babyhospital.value == "00" || objForm.babyhospital.value == "80")
    {
      // hospital of delivery is "other" or "out-of-state facility" explanation
      if (trim(objForm.babyhospitalother.value + "") == "")
      {
        objForm.babyhospitalother.style.backgroundColor = backgroundColor;
        blnsaveform = false;
      }
    }
  }

  //-----end baby information----------------------------------------

  // loop through all form elements and
  // correct the border,padding and height
  // I do this here because I may have screwed up the 
  //formatting by changing background colors earlier in function
  CorrectFormElementFormatting(objForm);

  if (blnsaveform)
  {
    objForm.submit();
  }
  else
  {
    document.getElementById("errormessage").innerHTML = "Required field(s) not complete or entry is invalid.";
  }
}
//*******************************************************************
function ResetBackgroundColors(pobjForm)
{
  // pjs 8/7/2008
  // function loops through all form elements and
  // sets the background color to appropriate color, it may be yellowish
  // if previous submit was unsuccessful 
  
  // parameters:
  // pobjForm: form with elements to loop through and reset background colors

  for(i=0; i<pobjForm.elements.length; i++)
  {
    //if the element is a text box or a drop down the background should be white
    if(pobjForm.elements[i].type == 'text' || pobjForm.elements[i].type == 'select-one')
    {
      pobjForm.elements[i].style.backgroundColor = "white";
    }
  }
  //reset background colors of "how did you hear about alfond" checkbox labels
  /* document.getElementById("requestorhearaboutdrtext").style.backgroundColor = 'transparent';
  document.getElementById("requestorhearabouthospitaltext").style.backgroundColor = 'transparent';
  document.getElementById("requestorhearaboutadvisortext").style.backgroundColor = 'transparent';
  document.getElementById("requestorhearaboutothertext").style.backgroundColor = 'transparent';

  //reset background colors of baby birth date type labels
  document.getElementById("babybirthdatetypeactualtext").style.backgroundColor = 'transparent';
  document.getElementById("babybirthdatetypeexpectedtext").style.backgroundColor = 'transparent'; */
}
//*******************************************************************
function CorrectFormElementFormatting(pobjForm)
{
  // pjs 8/7/2008
  // function loops through all form elements and
  // corrects the border,padding and height
  // for some reason when you change the background color
  // of a form element with javscript the browser also changes
  // the border,padding and height, and make the element 3d

  // parameters:
  // pobjForm: form with elements to loop through and correct formatting

  for(i=0; i<pobjForm.elements.length; i++)
  {
    //if the element is a text box or a drop down the border should be gray and 2d
    if(pobjForm.elements[i].type == 'text' || pobjForm.elements[i].type == 'select-one')
    {
      //fixing border to single gray 2d line
      pobjForm.elements[i].style.border = "solid 1px #aaaaaa";
      
      //the height and padding gets changed and has to be fix, but it's browser specific
      if(pobjForm.elements[i].type == 'text')
      {
        if (navigator.appName == "Microsoft Internet Explorer")
        {
          //setting height of textbox to appropriate value for IE
          pobjForm.elements[i].style.height = "19px";
        }
        else
        {
          //setting height and padding of textbox to appropriate 
          //values for non IE browsers
          pobjForm.elements[i].style.height = "21px";
          pobjForm.elements[i].style.paddingLeft = "1px";
          pobjForm.elements[i].style.paddingTop = "2px";
        }
      }      
    }
  }
}
//*******************************************************************
function trim(pstrTrim) 
{
  // pjs 8/7/2008
  // Googled "javascript trim" to find out how to do this
  // function trims leading and trailing whitespace from string

  // parameters:
  // pstrTrim: string to trim white space from

	return pstrTrim.replace(/^\s+|\s+$/g,"");
}
//*******************************************************************
function CheckForValidCharacter(key)
{
  // pjs 8/7/2008
  // function allow user to only enter numeric character,
  // hit the backspace key,the tab key, the left and right arrow keys,
  // and the delete key
  
  // paramters:
  // key: event.which(the key that was hit) if browser is not IE

  // returns:
  // blnValidKey: value indicating if the key pushed is acceptable

  //default the return value to false
  var blnValidKey = false;

  //if key exist, the browser is not IE, and we already have the key
  //no need to do anything else
  if (! key)
  {
    //we don't have the key yet
    //the browser is IE, event.which is not valid
    //we need to use the IE specific event to get the key
    key = event.keyCode
  }
  //convert key to character
  var character = String.fromCharCode(key);

  //This statements limits the acceptable characters to the following:
  // Digits from the top of the qwerty keyboard, keys(48-57)  
  // Digits from the keypad , keys(96-105)
  // Backspace, key(8)
  // Tab, key(9)
  // Left(key 37) and Right(key 39) arrow keys
  // Delete, key(46)
  if ((key >= 48 && key <=57) || (key >=96 && key <=105) || key == 8 || key == 9 || key == 37 || key == 39 || key == 46) 
  {
    //The key pushed is one we accept
    blnValidKey = true
  }
  return blnValidKey;
}
//*******************************************************************
function IsValidEmail(pstrEmail) 
{
  // Function taken from http://rosskendall.com/blog/web/javascript-function-to-check-an-email-address-conforms-to-rfc822
  // Licensed under a Creative Commons Attribution-ShareAlike 2.5 License, or the GPL
  // This licensed grant us the following freedoms:
  //  The freedom to use the work and enjoy the benefits of using it
  //  The freedom to study the work and to apply knowledge acquired from it
  //  The freedom to make and redistribute copies, in whole or in part, of the information or expression
  //  The freedom to make changes and improvements, and to distribute derivative works

  var valid = false;
  var sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
  var sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
  var sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
  var sQuotedPair = '\\x5c[\\x00-\\x7f]';
  var sDomainLiteral = '\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\x5d';
  var sQuotedString = '\\x22(' + sQtext + '|' + sQuotedPair + ')*\\x22';
  var sDomain_ref = sAtom;
  var sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')';
  var sWord = '(' + sAtom + '|' + sQuotedString + ')';
  var sDomain = sSubDomain + '(\\x2e' + sSubDomain + ')*';
  var sLocalPart = sWord + '(\\x2e' + sWord + ')*';
  var sAddrSpec = sLocalPart + '\\x40' + sDomain; // complete RFC822 email address spec
  var sValidEmail = '^' + sAddrSpec + '$'; // as whole string
  
  var reValidEmail = new RegExp(sValidEmail);
  
  if (reValidEmail.test(pstrEmail))
  {
    valid = true;
  }
  return valid;
}
//*******************************************************************
function FixBackground(objElement)
{
  // pjs 8/7/2008
  // function reset element background color
  // and other attributes when focus is put on element

  // parameters:
  // objElement:the element to fix

  //change element background color to white, it may be yellowish if submit failed
  objElement.style.backgroundColor='white';

  //fix border that gets screwed up by changing background color
  objElement.style.border = "solid 1px #aaaaaa";
  
  //the height and padding gets changed and has to be fix, but it's browser specific
  if(objElement.type == 'text')
  {
    if (navigator.appName == "Microsoft Internet Explorer")
    {
      objElement.style.height = "19px";
    }
    else
    {
      objElement.style.height = "18px";
      objElement.style.paddingLeft = "1px";
      objElement.style.paddingTop = "2px";
    }
  } 
}
//*******************************************************************
function CheckForEnter(key)
{
  // pjs 8/13/2008
  // function checks to see if user has hit enter key
  // we need this function on form that don't have
  // a submit button on the page
  
  // paramters:
  // key: event.which(the key that was hit) if browser is not IE


  //if key exist, the browser is not IE, and we already have the key
  //no need to do anything else
  if (! key)
  {
    //we don't have the key yet
    //the browser is IE, event.which is not valid
    //we need to use the IE specific event to get the key
    key = event.keyCode
  }
  //convert key to character
  var character = String.fromCharCode(key);

  // the value of the enter key is 13
  if( key == 13 ) 
  {
    ValidateForm();
  }
}
//*******************************************************************
