// Initialize
var MINUTE=60*1000;
var HOUR=MINUTE*60;
var DAY=HOUR*24;
var DUEDAY=28*DAY;
// Define static finals
var datTodaysDate=new Date();
var datZeroDate=new Date(0);
//Declare dates
 datDateObject1=new Date(Date.parse(datZeroDate));
 datDateObject2=new Date(Date.parse(datZeroDate));

function AdjustDates(objCaller){
  //Getting the name of the object that called the function
  var objCallerStr=objCaller.name;
  if((objCallerStr=='month1')||(objCallerStr=='day1')){
  //datDateObject1 source on the form has changed
    setDateObj1();
  }
  if((objCallerStr=='month2')||(objCallerStr=='day2')){
  //datDateObject2 source on the form has changed
    setDateObj2();
  }
}
function setDateObj1(){
  // Check if either the month1 or day1 values are null.
  if(  ((gIsNumber((document.OvulationForm.month1.options[document.OvulationForm.month1.selectedIndex]).value))>0)  
    && ((gIsNumber((document.OvulationForm.day1.options[document.OvulationForm.day1.selectedIndex]).value))>0)){ 
      var strDate1 = (document.OvulationForm.month1.selectedIndex) + '/' + document.OvulationForm.day1.selectedIndex + '/' + getCorrectYear(document.OvulationForm.month1.selectedIndex) ;

    if (gIsValidDateStr(strDate1)) {
		datDateObject1.setUTCFullYear(getCorrectYear(document.OvulationForm.month1.selectedIndex));
		datDateObject1.setUTCMonth(document.OvulationForm.month1.selectedIndex-1);
		datDateObject1.setUTCDate(document.OvulationForm.day1.selectedIndex);
		//alert('Date1 is '+ datDateObject1.toUTCString());
  		return true;
	} else { alert('The first date entered is not valid'); return false;  }

  } else  datDateObject1.setTime(0);
}

function setDateObj2(){
  // Check if either the month2 or day2 values are null.
  if(  ((gIsNumber((document.OvulationForm.month2.options[document.OvulationForm.month2.selectedIndex]).value))>0)
    && ((gIsNumber((document.OvulationForm.day2.options[document.OvulationForm.day2.selectedIndex]).value))>0)){
      var strDate2 = (document.OvulationForm.month2.selectedIndex) + '/' + document.OvulationForm.day2.selectedIndex + '/' + getCorrectYear(document.OvulationForm.month2.selectedIndex) ;
	if (gIsValidDateStr(strDate2)) {
		datDateObject2.setUTCDate(document.OvulationForm.day2.selectedIndex);
		datDateObject2.setUTCMonth(document.OvulationForm.month2.selectedIndex-1);
		datDateObject2.setUTCFullYear(getCorrectYear(document.OvulationForm.month2.selectedIndex));
		//alert('Date2 is '+ datDateObject2.toUTCString());
  
         } else { alert('The second date entered is not valid'); }

   }  else  datDateObject2.setTime(0);
}

function getCorrectYear( dateToCheck ) {
  //if the monthToCheck is greater than datTodaysDate month
  //it must mean LAST year

  if ( dateToCheck > (datTodaysDate.getMonth() + 1) ) {
    return datTodaysDate.getFullYear() - 1;
  } else { 
    return datTodaysDate.getFullYear();
  }

}

function Reset(){
  datDateObject1=new Date(Date.parse(datZeroDate));
  datDateObject2=new Date(Date.parse(datZeroDate));
}

function CalculateAnswer(){
  var intNumberOfDatesSelected=intDividend=intDivisor=intQuotient=0;

  if(Date.parse(datDateObject1)!=0) intNumberOfDatesSelected++;
  if(Date.parse(datDateObject2)!=0) intNumberOfDatesSelected++;

  if (intNumberOfDatesSelected<1){
    alert('Please select a date.');
    return;
  }

  //if they've only entered one date, guess the others
  if (intNumberOfDatesSelected==1)
  {    
      if(Date.parse(datDateObject1)!=0){
          datDateObject2=new Date(datDateObject1.valueOf() - (28*24*60*60*1000));
          //alert('Date2 is date1-28 days' + datDateObject2.toUTCString());
          document.OvulationForm.month2.selectedIndex = datDateObject2.getUTCMonth()+1;
          document.OvulationForm.day2.selectedIndex = datDateObject2.getUTCDate();

					document.getElementById("LastDateCalculation").innerHTML='<i>Above date is based on the average menstrual cycle of 28 days. If this is incorrect, and you know the date feel free to change the date calculated above.</i>'
      }
      else if(Date.parse(datDateObject2)!=0){
          datDateObject1=new Date(datDateObject2.valueOf()+ DUEDAY);
          document.OvulationForm.month1.selectedIndex = datDateObject1.getUTCMonth()+1;
          document.OvulationForm.day1.selectedIndex = datDateObject1.getUTCDate();
      }
  } else
	{
					document.getElementById("LastDateCalculation").innerHTML=''
	}

  //adjust second year off first
  if ( ( Date.parse( datDateObject1 ) != 0 ) 
       && ( Date.parse( datDateObject2 ) != 0 ) ) { //if one and two have been changed.
    if ( Date.parse( datDateObject1 ) < Date.parse( datDateObject2 ) ) {
      while ( Date.parse( datDateObject1 ) < Date.parse( datDateObject2 ) ) {
        datDateObject2.setYear( datDateObject2.getYear() - 1 );
      }
    }
    var intDateObject1N2Deviation=(Date.parse(datDateObject1)-Date.parse(datDateObject2));
    intDivisor++;
  }else{
    var intDateObject1N2Deviation=0;
  }

  intDividend=(intDateObject1N2Deviation/DAY);
  if ( intDivisor != 0 ) {
    intQuotient = intDividend / intDivisor;
  }
  
  if((intQuotient<21)||(intQuotient>35)){
      alert("Women who do not have cycles between 21 days and 35 days may not be ovulating. See your doctor for further advice.");
    return;
  }
  Cycle=Math.round(intQuotient);

  var datNextPeriod=new Date(0);
  if(Date.parse(datDateObject1)!=0){
    datNextPeriod=new Date(Date.parse(datDateObject1)+((intQuotient+1)*DAY));
  }else if(Date.parse(datDateObject2)!=0){
    datNextPeriod=new Date(Date.parse(datDateObject2)+(((intQuotient+1)*DAY)*2));
  }else{
    return;
  }

  if(Date.parse(datNextPeriod)!=0){
    Nextperiod=datNextPeriod.getDate()+'/'+(datNextPeriod.getMonth()+1)+'/'+gReturnY2KDate(datNextPeriod);
    var datEndFertitlity=new Date(Date.parse(datNextPeriod)-(DAY*14));
    Fertile2=datEndFertitlity.getDate()+'/'+(datEndFertitlity.getMonth()+1)+'/'+gReturnY2KDate(datEndFertitlity);
    var datStartFertitlity=new Date(Date.parse(datEndFertitlity)-(DAY*5));
    Fertile1=datStartFertitlity.getDate()+'/'+(datStartFertitlity.getMonth()+1)+'/'+gReturnY2KDate(datStartFertitlity);
  }

	document.getElementById("s").innerHTML='<div class="symcheck"> <div class="symlabel" style="width:60%">Your menstrual cycle is approximately: </div> <div class="symoptions" style="width:40%">' + Cycle + ' days long </div></div>'
	document.getElementById("s").innerHTML+='<div class="symcheck"> <div class="symlabel" style="width:60%">Date of next period should be: </div> <div class="symoptions" style="width:40%">' + Nextperiod + '</div></div>'
	document.getElementById("s").innerHTML+='<div class="symcheck"> <div class="symlabel" style="width:60%">Begin date for significant fertility </div> <div class="symoptions" style="width:40%">' + Fertile1 + '</div></div>'
	document.getElementById("s").innerHTML+='<div class="symcheck"> <div class="symlabel" style="width:60%">End date for significant fertility </div> <div class="symoptions" style="width:40%">' + Fertile2 + '</div></div>'
}

//
var strCaller="";
function gRegister(strFunctionCall){
  strCaller=strFunctionCall;
  return true;
}
function gUnregister(){
  strCaller="";
  return true;
}

var objPage=new Object();

var datExpiration=new Date();
datExpiration=new Date(Date.parse(datExpiration)+(1000*60*60*24*30));   //add one month
objPage.userdata=new CookieObject(document,"safehealthinfo",datExpiration);
var strErrorValue=objPage.userdata.read();


function gIsNumber(strNumber,strMin,strMax){
/**
 *gIsNumber(strNumber,strMin,strMax)
 *strMin and strMax may be null.
 *if strMin and/or strMax are not null, all are verified as numbers,
 *and strMin<=strNumber and/or strNumber<=strMax
 */
  gRegister("gIsNumber");
  var strTempNumber=strNumber;  //make a copy
  strTempNumber=""+strTempNumber; //make sure copy is string
  if(strTempNumber.length==0) return false;
  for(i=0;i<strTempNumber.length;i++){
    if(!((strTempNumber.charAt(i)=="0")||
      (strTempNumber.charAt(i)=="1")||
      (strTempNumber.charAt(i)=="2")||
      (strTempNumber.charAt(i)=="3")||
      (strTempNumber.charAt(i)=="4")||
      (strTempNumber.charAt(i)=="5")||
      (strTempNumber.charAt(i)=="6")||
      (strTempNumber.charAt(i)=="7")||
      (strTempNumber.charAt(i)=="8")||
      (strTempNumber.charAt(i)=="9")||
      (strTempNumber.charAt(i)=="-")||
      (strTempNumber.charAt(i)=="."))){
      return false;
    }
  }
  if(strTempNumber.indexOf(".")!=-1){
    var strDecident=strTempNumber.substr(strTempNumber.indexOf("."));
    var blnBadDecident=false;
    if(strDecident==".") blnBadDecident=true;
    for(i=1;i<strDecident.length;i++){
      if((strDecident.charAt(i)==".")||
        (strDecident.charAt(i)=="-")){
        blnBadDecident=true;
      }
    }
    if(blnBadDecident){
      return false;
    }
  }

  if ( strTempNumber.indexOf("-") != -1 ) {  //if it includes a - test:
    if ( strTempNumber.length == 1 ) return false;        //bad if - is the only character
    if ( strTempNumber.indexOf("-") != 0 ) return false;  //bad if - is not the first character
  }

  if(strMin){
    var strTempMin=strMin;
    strTempMin=""+strTempMin;
    if(strTempMin.length==0) return false;
    for(i=0;i<strTempMin.length;i++){
      if(!((strTempMin.charAt(i)=="0")||
        (strTempMin.charAt(i)=="1")||
        (strTempMin.charAt(i)=="2")||
        (strTempMin.charAt(i)=="3")||
        (strTempMin.charAt(i)=="4")||
        (strTempMin.charAt(i)=="5")||
        (strTempMin.charAt(i)=="6")||
        (strTempMin.charAt(i)=="7")||
        (strTempMin.charAt(i)=="8")||
        (strTempMin.charAt(i)=="9")||
        (strTempMin.charAt(i)=="-")||
        (strTempMin.charAt(i)=="."))){
        return false;
      }
    }
    if(strNumber<parseFloat(strMin)) return false;
  }
  if(strMax){
    var strTempMax=strMax;
    strTempMax=""+strTempMax;
    if(strTempMax.length==0) return false;
    for(i=0;i<strTempMax.length;i++){
      if(!((strTempMax.charAt(i)=="0")||
        (strTempMax.charAt(i)=="1")||
        (strTempMax.charAt(i)=="2")||
        (strTempMax.charAt(i)=="3")||
        (strTempMax.charAt(i)=="4")||
        (strTempMax.charAt(i)=="5")||
        (strTempMax.charAt(i)=="6")||
        (strTempMax.charAt(i)=="7")||
        (strTempMax.charAt(i)=="8")||
        (strTempMax.charAt(i)=="9")||
        (strTempMax.charAt(i)=="-")||
        (strTempMax.charAt(i)=="."))){
        return false;
      }
    }
    if(strNumber>parseFloat(strMax)) return false;
  }
  gUnregister();
  return true;
}


function gIsValidDateStr(strDate) {
/* Accepts date in the mm/dd/yyyy format only.
*/
  gRegister("gIsValidDateStr");

  var monthdays=0;
  var i = strDate.indexOf('/');
  var month = strDate.substring(0, i);
  var j = strDate.indexOf('/', i+1);
  var day = strDate.substring(i+1,j);
  var year = strDate.substring(j+1, strDate.length);

  if (isNaN(day) || day < 0 || isNaN(month) || month < 0 || isNaN(year) || year < 0 ) { return false; }

  if ((month == '1') || (month == '3') || (month == '5') || (month == '7') || 
      (month == '8') || (month == '10') || (month == '12') ){
        if (day >31) {
            return false; 
        } else {
            return true;
        } 
  } else if ((month == '4') || (month == '6') || (month == '9') || (month == '11')) {
     if (day > 30)  { 
      return false;  
     } else { return true; }
  } else if (month == 2) {
              if (day <=28) {
                 return true;
              } else if (year % 4 != 0)  {  return false; }
                 //{use 28 for days in February}
              else if ( (year % 400 == 0) && (day == 29) ) {  return true; }
                 //{use 29 for days in February}
              else if (day >29) {  return false; }
                 //{use 29 for days in February}
  }

}

function gIsDate(strDate,strMin,strMax){
/**
 *gIsDate(strDate,strMin,strMax)
 *strMin and strMax may be null.
 *if strMin and/or strMax are not null, all are converted to milliseconds since 1/1/1970,
 *and strMin<=strDate and/or strDate<=strMax
 */
  gRegister("gIsDate");
  if(!Date.parse(strDate))  { alert('returning false because parse failed' ); return false; }
  if(strMin){
    if(!Date.parse(strMin)) return false;
    if(Date.parse(strDate)<Date.parse(strMin)) return false;
  }
  if(strMax){
    if(!Date.parse(strMax)) return false;
    if(Date.parse(strDate)>Date.parse(strMax)) return false;
  }
  gUnregister();
  return true;
}

function gIsValidDate(strIncomingDateString){
/**
 *gIsValidDate(strIncomingDateString)
 *strIncomingDateString is a string literal to validate
 *
 *VALID FORMATS:
 *MM dd, yyyy** February 29, 2000
 *mm/dd/yyyy** 2/29/2000
 *dd MM yyyy** 29 February 2000
 *yyyy MM dd** 2000 February 29
 *yyyy/mm/dd** 2000/2/29
 *yyyy dd MM** 2000 29 February
 *MM yyyy dd** February 2000 29
 *dd yyyy MM** 29 2000 February
 *
 *dd/mm/yyyy NOT VALID**
 *yyyy/dd/mm NOT VALID**
 */
    //if JavaScript cannot convert it, toss it out
    if(gIsDate(strIncomingDateString)){
        var datConvertedDate=new Date(strIncomingDateString);    
    }else{
        return false;
    }

    //common strings to search for
    var strMonthAbbrevs=new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
    var blnContainsMonthAbbrev=false;
    for(x=0;x<strMonthAbbrevs.length;x++){
        if(strIncomingDateString.indexOf(strMonthAbbrevs[x])!=-1){
        //if string is found
            blnContainsMonthAbbrev=true;

            if(datConvertedDate.getMonth()!=x){
            //if converted month is not same as string month
                return false;
            }else{
                return true;
            }
        }
    }

    //this is not robust, but tries to grab numerical dates
    if(!blnContainsMonthAbbrev){
        var intMonthPos=strIncomingDateString.length;
        //where to start searching from in the loop
        var intCurrentPointerPos=strIncomingDateString.length;
        //the current pointer in the string
        var intLastMonthFoundPos=strIncomingDateString.length;
        //where the last month was found
        var intLastMonthFound=0;
        //what the last month was found was
        var blnBreakBefore=false;
        //is there a break point before
        var blnBreakAfter=false;
        //is there a break point after
        for(x=1;x<13;){
            blnBreakBefore=false;
            blnBreakAfter=false;
            if(strIncomingDateString.lastIndexOf(x,intMonthPos)!=-1){
            //if a number between 1 and 12 exists before intMonthPos
                intCurrentPointerPos=strIncomingDateString.lastIndexOf(x,intMonthPos);
                //set intCurrentPointerPos = loc of number
                if(intCurrentPointerPos<intLastMonthFoundPos){
                //if closer to front than last month
                    if(intCurrentPointerPos-1>=0){
                    //if there's something before it
                        //if the character before the pointer is not a digit
                        if(!((strIncomingDateString.charAt(intCurrentPointerPos-1)=='1')||
                            (strIncomingDateString.charAt(intCurrentPointerPos-1)=='2')||
                            (strIncomingDateString.charAt(intCurrentPointerPos-1)=='3')||
                            (strIncomingDateString.charAt(intCurrentPointerPos-1)=='4')||
                            (strIncomingDateString.charAt(intCurrentPointerPos-1)=='5')||
                            (strIncomingDateString.charAt(intCurrentPointerPos-1)=='6')||
                            (strIncomingDateString.charAt(intCurrentPointerPos-1)=='7')||
                            (strIncomingDateString.charAt(intCurrentPointerPos-1)=='8')||
                            (strIncomingDateString.charAt(intCurrentPointerPos-1)=='9'))){
                            blnBreakBefore=true;
                        }else{
                            blnBreakBefore=false;
                        }
                    }else{
                    //if there's nothing before it
                        blnBreakBefore=true;
                    }
                    if(intCurrentPointerPos+(x.toString().length)<strIncomingDateString.length){
                    //if there's something after it
                        if(!((strIncomingDateString.charAt(intCurrentPointerPos+(x.toString().length))=='1')||
                            (strIncomingDateString.charAt(intCurrentPointerPos+(x.toString().length))=='2')||
                            (strIncomingDateString.charAt(intCurrentPointerPos+(x.toString().length))=='3')||
                            (strIncomingDateString.charAt(intCurrentPointerPos+(x.toString().length))=='4')||
                            (strIncomingDateString.charAt(intCurrentPointerPos+(x.toString().length))=='5')||
                            (strIncomingDateString.charAt(intCurrentPointerPos+(x.toString().length))=='6')||
                            (strIncomingDateString.charAt(intCurrentPointerPos+(x.toString().length))=='7')||
                            (strIncomingDateString.charAt(intCurrentPointerPos+(x.toString().length))=='8')||
                            (strIncomingDateString.charAt(intCurrentPointerPos+(x.toString().length))=='9')||
                            (strIncomingDateString.charAt(intCurrentPointerPos+(x.toString().length))=='0'))){
                            blnBreakAfter=true;
                        }else{
                            blnBreakAfter=false;
                        }
                    }else{
                    //if there's nothing after it
                        blnBreakAfter=true;
                    }
                    if((blnBreakBefore)&&(blnBreakAfter)){
                    //if there's breakpoints before and after
                        intLastMonthFound=x;
                        //set x as new best month
                        intLastMonthFoundPos=intCurrentPointerPos;
                        //set pointer as new best month pointer
                    }
                }
                if(intCurrentPointerPos-1>=0){
                //if there could be more
                    intMonthPos=intCurrentPointerPos-1;
                    //set new starting point
                }else{
                //advance to next number
                    intMonthPos=strIncomingDateString.length;
                    intCurrentPointerPos=strIncomingDateString.length;
                    x++;
                }
            }else{
            //advance to next number
                intMonthPos=strIncomingDateString.length;
                intCurrentPointerPos=strIncomingDateString.length;
                x++;
            }
        }
        if(datConvertedDate.getMonth()!=intLastMonthFound-1){
        //if converted month is not same as string month
            return false;
        }else{
            return true;
        }
    }
}

function gReturnY2KDate(Y2KDateObject){
/**
 *gReturnY2KDate(Y2KDateObject)
 *Y2KDateObject is a Date object.
 *Returns a four-digit integer for year.
 *EXAMPLE:
 * var someDate=new Date();
 * alert((someDate.getMonth()+1)+'/'+someDate.getDate()+'/'+gReturnY2KDate(someDate));
 * RETURNS "mm/dd/yyyy" in all browsers 3.0+
 */
  gRegister("gReturnY2KDate");
  currYearIndex=Y2KDateObject.getYear();
  var yearln=(currYearIndex+"").length;
  if(yearln<4)currYearIndex+=1900; //Fix Y2K
  gUnregister();
  return currYearIndex;
}

// strQuery is a string that contains the window.location.search portion of the URL
// i.e. ?Age=25&Submit=begin
// strToGet is the variable to find in the strQuery and return the corresponding value.

function strGetQueryValue(strQuery, strToGet) {

  var i = 0;
  var l = strQuery.length;
  var value = '';
  var name = '';
  for (i=1; i<l; i++) {
      j = strQuery.indexOf('=', i);
      k = strQuery.indexOf('&', i);
      name = strQuery.substring(i,j); 
      if (name == strToGet) {
         if (k>0) {
             value = strQuery.substring(j+1, k);
         } else {
             value = strQuery.substring(j+1, l);
         }
         return value;
      } else if (k < 1 ) { 
                return '';
             } 
  }
  return '';
}

