<!--
/*
  -------------------------------------------------------------------------------
 |  The content of this file constitutes Licensed Code.                          |
 |  Copyright (C) 2005-2007 Azalea Technology, LLC. All rights reserved.         |
 |-------------------------------------------------------------------------------|
 |  Unauthorized removal of this notice is considered a violation of the         |
 |  license agreement under which this Code may be used. This work is protected  |
 |  under United States copyright law and the similar law(s) of other countries  |
 |  under which such as work is afforded legal protection, and upon conviction   |
 |  of such a violation in a court of applicable jurisdiction, such person(s)    |
 |  may be subject to the maximum allowable penalty as permitted under such law. |
 |-------------------------------------------------------------------------------|
 |  You acknowledge and agree that information presented to you through this     |
 |  site (the "Web Site") is protected by all applicable copyrights, trademarks, |
 |  service marks, patents or other proprietary rights and laws, and by virtue   |
 |  of accessing the Web Site, except as expressly authorized by the Azalea      |
 |  Technology, LLC., you agree not to modify, rent, lease, loan, sell,          |
 |  distribute, store, or create derivative works based on the Web Site, in      |
 |  whole or in part.                                                            |
  -------------------------------------------------------------------------------|
 |  Decrypting or otherwise decoding the following programming language code is  |
 |  strictly prohibited except as expressly authorized by Azalea Technology,     |
 |  LLC. Upon conviction of such a violation in a court of applicable            |
 |  jurisdiction, such person(s) may be subject to the maximum allowable penalty |
 |  as permitted under such law.                                                 |
  -------------------------------------------------------------------------------
         Purpose: Date & time function library
      Programmer: Benjamin Roberts
                  Azalea Technology, LLC.
                  P.O. Box 131150
                  Tyler, TX 75713-1150
  -------------------------------------------------------------------------------
*/

function getY2KYear(d){ 
	return (d < 1000) ? d + 1900 : d;
}


function isDate(year,month,day){
	month = month - 1;  // javascript month range : 0- 11
	var tempDate = new Date(year,month,day);
	if ( (getY2KYear(tempDate.getYear()) == year) && (month == tempDate.getMonth()) && (day == tempDate.getDate()) )
		return true;
	else return false;
}


function parseDateString(string_val,part){
	var date_array;
	date_array = string_val.split("/");
	return date_array[part]; 
}


function validDate(string_val){
	var month,day,year;
	if(typeof string_val == "string"){
		month = parseDateString(string_val,0);
		day   = parseDateString(string_val,1);
		year  = parseDateString(string_val,2);
		return isDate(year,month,day);
	}
	else if( (typeof string_val == "object") && (string_val.constructor == Date) ) return true;
	else return false;
}


function getmonth(){
	var currentDate   = new Date();               //create new date object
	var month         = currentDate.getMonth();   //get the current month number	
	return (month+1);
}


function getcalendermonth(){
	var months = new Array();
        months[0]  = "empty";
        months[1]  = "January";
        months[2]  = "February";
        months[3]  = "March";
        months[4]  = "April";
        months[5]  = "May";
        months[6]  = "June";
        months[7]  = "July";
        months[8]  = "August";
        months[9]  = "September";
		months[10] = "October";
        months[11] = "November";
        months[12] = "December";
	var monthtxt = months[getmonth()];
	return monthtxt;
}


function getday(){
	var currentDate   = new Date();               //create new date object
	var day           = currentDate.getDate();    //get the current calender day
	return day;
}


function getyear(){
	var currentDate   = new Date();               //create new date object
	var year          = currentDate.getYear();    //get the current year
	if (year<2000) year+=1900;
	return year;
}


function gethour(){
	var currentDate = new Date();                //create new date object
	var hr          = currentDate.getHours();    //get current hour from date object
	if (hr>12)    {var hr2 = hr - 12;}           //checks military time and converts it to standard time
	else if (hr<=12 && hr != 0){var hr2 = hr;}   //otherwise leave time alone, no conversion needed 
	if (hr==0){hr2 = 12;}                        //checks for 0 hours in army time and converts to 12am
	return hr2;                                  //concatenate string
}


function getmilitaryhour(){
	var currentDate = new Date();                //create new date object
	var hr          = currentDate.getHours();    //get current hour from date object
	return hr;
}


function getminute(){
	var currentDate = new Date();                //create new date object
	var min         = currentDate.getMinutes();
	if (min<=9){var modmin = "0" + min}         //concatenate string with 0
	else if (min>=10){var modmin = min}         //concatenate string w/o 0
	return modmin;
}


function getsecond(){
	var currentDate = new Date();                //create new date object
	var sec         = currentDate.getSeconds();
	if (sec<=9){var modsec = "0" + sec}         //concatenate string with 0
	else if (sec>=10){var modsec = sec}         //concatenate string w/o 0
	return modsec;
}


function getAM_PM(){
	var currentDate = new Date();                //create new date object
	var hr          = currentDate.getHours();    //get current hour from date object
	if (hr>=12){var end = " PM"}                   //adds "PM" if hour is greater than or equal to 12 //concatenate string
	else if (hr<12){var end = " AM"}               //otherwise "AM" is added //concatenate string
	return end;
}


function printdate(){
	var datetxt = getcalendermonth() + " " + getday() + ", " + getyear(); 
	document.write(datetxt);
}   


function printtime(){
	var time = gethour() + ":" + getminute() + ":" + getsecond() + getAM_PM();
	document.write(time);
}


function printgreeting(){
	if (getmilitaryhour()>=0 && getmilitaryhour()<=10){document.write("Good Morning!")}
	else if (getmilitaryhour()>=11 && getmilitaryhour()<=13){document.write("Good Day!")}
	else if (getmilitaryhour()>=14 && getmilitaryhour()<=17){document.write("Good Afternoon!")}
	else if (getmilitaryhour()>=18 && getmilitaryhour()<=24){document.write("Good Evening!")}
}


function printall(){
	printgreeting();document.write("<br>");printdate();document.write("<br>");printtime();
}


function is_year(year){ 
	var status;           // return value, 0 or 1
	var min_year = 0;     // minimum year value
	var max_year = 10000; // maximum year value
	if(year<min_year || year>max_year)
		status=false;   // assign 0 to status because year is not a vaild year
	else
		status=true;   // assign 1 to status because year is a valid year;
	return status;	// return 0 or 1 to caller				    
}


function is_leap_year(year){
	var status;            // return value, 0 or 1
	if(is_year(year))  // test to make sure year is a valid year
	{
		if((year%4==0 && year%100!=0) || (year%400==0)) status=true; // assign 1 to status because year is a leap year         
		else status=false;     // assign 0 to status because year is not a leap year
	}
	return status;         // return 0 or 1 to caller
}


function get_day_code(year){
	return (parseInt(year)+parseInt(Math.floor((year-1)/4))-parseInt(Math.floor((year-1)/100))+parseInt(Math.floor((year-1)/400)))%7; // return day_code
}


function get_days_in_month(month,year){
	var num_of_days = new Array(31,28,31,30,31,30,31,31,30,31,30,31); // array of # of days                                                             // in each month
	if(is_leap_year(year)) num_of_days[1] = 29;
	else num_of_days[1] = 28;
	return num_of_days[month-1]; // return the number of days given month
}


function get_weekday(day){
	var weekday = new Array("Sun.","Mon.","Tue.","Wed.","Thu.","Fri.","Sat.","-");
	if(day>6)day=7;
	return weekday[day];
}


function get_month_name(month){
	var month_names = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
	return month_names[month-1];
}


function find_weekday(month,day,year){
	var i;                                   // local loop counter
	var day_tmp=1;                             // day number
	var weekday;
	var days_in_month;                       // number of days in month
	var day_code = get_day_code(year);       // calculate day_code for JAN 1 of year
	for(i=2;i<=month;i++)                    // calculate day_code for the given month
	{
		days_in_month = get_days_in_month((i-1), year);
		day_code      = (day_code+days_in_month)%7;
	}
	var weekday = day_code;
	while(day_tmp<day)
	{
		if(weekday>5) weekday=0;
		else weekday++;
		day_tmp++;
		//alert("weekday=" + weekday + "\nday=" + day_tmp);
	}
	return get_weekday(weekday);
}

function get_days_until(month,day,year){
	var days=0;
	if(month==getmonth() && day==getday()) days = 0;
	if(month==getmonth() && day>getday())  days = day-getday();
	if(month>getmonth())
	{
		days += get_days_in_month(getmonth(),getyear())-getday();
		for(var j=(getmonth()+1);j<month;j++) days += get_days_in_month(j,year);
		days += day;
	}
	return days;
}

function dateDiff(units,dat1,dat2,roundingMethod){
	if(!validDate(dat1)) return null;
	if(!validDate(dat2)) return null;
	if(arguments.length!=4) return null;
	dat1 = new Date(dat1);
	dat2 = new Date(dat2);
	var dat2_ms,dat1_ms,diff_ms;
	var diff = 0
	var ms_per_second = 1000;
	var ms_per_minute = ms_per_second*60;
	var ms_per_hour   = ms_per_minute*60;
	var ms_per_day    = ms_per_hour*24;
	var ms_per_month  = ms_per_day*30.4375;
	var ms_per_year   = ms_per_month*12;
	
	dat2_ms = dat2.getTime();
	dat1_ms = dat1.getTime();
	diff_ms = dat1_ms-dat2_ms;
	
	units = units.toString();
	units = units.toLowerCase();
	
	switch(units){
		case "y": diff = diff_ms/ms_per_year; break;
		case "m": diff = diff_ms/ms_per_month; break;
		case "d": diff = diff_ms/ms_per_day; break;
		case "h": diff = diff_ms/ms_per_hour; break;
		case "n": diff = diff_ms/ms_per_minute; break;
		case "s": diff = diff_ms/ms_per_second; break;
		 default: diff = diff_ms/ms_per_year; break;
	}
	
	if(!isNaN(parseInt(roundingMethod))) roundingMethod = parseInt(roundingMethod);
	else roundingMethod = 0;
	
	switch(roundingMethod){
		case 0: diff = Math.floor(diff); break;
		case 1: diff = Math.ceil(diff); break;
		default: diff = Math.floor(diff); break;
	}
	return diff;
}

// ADDS TO A DATE VARIABLE
function dateAdd(interval,number,start) {
	
    // Create 3 error messages, 1 for each argument. 
    var startMsg = "Sorry the start parameter of the dateAdd function\n"
        startMsg += "must be a valid date format.\n\n"
        startMsg += "Please try again." ;
		
    var intervalMsg = "Sorry the dateAdd function only accepts\n"
        intervalMsg += "d, h, m OR s intervals.\n\n"
        intervalMsg += "Please try again." ;

    var numberMsg = "Sorry the number parameter of the dateAdd function\n"
        numberMsg += "must be numeric.\n\n"
        numberMsg += "Please try again." ;
		
    // get the milliseconds for this Date object. 
    var buffer = Date.parse(start) ;
	
    // check that the start parameter is a valid Date. 
    if ( isNaN (buffer) ) {
        alert( startMsg ) ;
        return null ;
    }
	
    // check that an interval parameter was not numeric. 
    if ( interval.charAt == 'undefined' ) {
        // the user specified an incorrect interval, handle the error. 
        alert( intervalMsg ) ;
        return null ;
    }

    // check that the number parameter is numeric. 
    if ( isNaN ( number ) )	{
        alert( numberMsg ) ;
        return null ;
    }

    // so far, so good...
    //
    // what kind of add to do? 
    switch (interval.charAt(0))
    {
        case 'd': case 'D': 
            number *= 24 ; // days to hours
            // fall through! 
        case 'h': case 'H':
            number *= 60 ; // hours to minutes
            // fall through! 
        case 'm': case 'M':
            number *= 60 ; // minutes to seconds
            // fall through! 
        case 's': case 'S':
            number *= 1000 ; // seconds to milliseconds
            break ;
        default:
        // If we get to here then the interval parameter
        // didn't meet the d,h,m,s criteria.  Handle
        // the error. 		
        alert(intervalMsg) ;
        return null ;
    }
    return new Date( buffer + number ) ;
}

function calculateAge(yr, mon, day, unit, decimal, roundMethod){
	var one_day=1000*60*60*24;
	var one_month=1000*60*60*24*30.4375;
	var one_year=1000*60*60*24*30.4375*12;
	var today=new Date();
	var pastdate=new Date(yr, mon-1, day);
	var countunit=unit;
	var decimals=decimal;
	var rounding=roundMethod;
	var age="";
	
	finalunit=(countunit=="days")? one_day : (countunit=="months")? one_month : one_year;
	decimals=(decimals<=0)? 1 : decimals*10;
	
	if (unit!="years"){
		if (rounding=="rounddown") age = Math.floor((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals;
		else age = Math.ceil((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals;
	}
	else{
		yearspast=today.getFullYear()-yr-1;
		tail=(today.getMonth()>mon-1 || today.getMonth()==mon-1 && today.getDate()>=day)? 1 : 0;
		pastdate.setFullYear(today.getFullYear());
		pastdate2=new Date(today.getFullYear()-1, mon-1, day);
		tail=(tail==1)? tail+Math.floor((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals : Math.floor((today.getTime()-pastdate2.getTime())/(finalunit)*decimals)/decimals;
		age = yearspast+tail;
	}
	return age;
}

function displayAge(birthDate){
	if(!validDate(birthDate)) return "unknown age";
	else birthDate = new Date(birthDate);
	
	var ageString = "";
	var unit = "";
	var yr = birthDate.getFullYear();
	var mon = birthDate.getMonth()+1;
	var day = birthDate.getDate();
	var decimal = 0;
	var roundMethod = "rounddown"
	var years = calculateAge(yr,mon,day,"years",decimal,roundMethod);
	var months = calculateAge(yr,mon,day,"months",decimal,roundMethod);
	var days = calculateAge(yr,mon,day,"days",decimal,roundMethod);
	
	if(years>=150) ageString = "(unlikely)"
	else if(years>=2) ageString = years + " years";
	else if(months>0){
		if(months==1) unit = "month";
		else unit = "months";
		ageString = months + " " + unit;
	}
	else if(days>=0){
		if(days==1) unit = "day";
		else unit = "days";
		ageString = days + " " + unit;
	}
	else ageString = "(unborn)";
	
	return ageString;
}

function displayAgeInFormField(birthDate,obj,next_obj){
	if(isSpace(birthDate)) obj.value = "";
	else obj.value = displayAge(birthDate);
	if(next_obj) next_obj.focus();
}

function getAgeInYears(birthDate){
	if(!validDate(birthDate)) return 0;
	else birthDate = new Date(birthDate);
	var currentDate = new Date();

	return dateDiff("y",currentDate,birthDate,0);
}

function getAgeInYearsOnSpecificDate(birthDate,specDate){
	if(!validDate(birthDate)) return 0;
    if(!validDate(specDate)) return 0;
	else birthDate = new Date(birthDate);
	var currentDate = new Date(specDate);

	return dateDiff("y",specDate,birthDate,0);
}

//-->