// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// NOTE: Only for JS 1.2 + 
//
// api_DateTime.asp 
//
// author   : Jason M. Barnett <barnett@unext.com>
// 
// what?    : this script has all functions that have to do with calculating, manipulating,
//            or figuring out date and/or time stuff.
// 
// sections :
//   SECTION I  = Global Variables
//   SECTION II = Date / Time Functions
//
// created  : 3/31/00
// updated  : 5/20/01
//
// notes    : 3/31/00 JMB - finished writing comments for all functions.
//
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++




//
//
// SECTION I 
// --------- 
//
//
// //////////////////////////////////////////////////////////////////////////////////////////////
//
//
// Global Variables
//
// These are variables that are global to any script if this file is included.
// 
// 
// //////////////////////////////////////////////////////////////////////////////////////////////

 // --> days of the week [index 0..6]
 //
 var days   = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");

 // --> name of months [index 1..12]
 //
 var months = new Array("","January","February","March","April","May","June","July",
                        "August","September","October","November","December");



//
//
// SECTION II
// ----------
//
//
// //////////////////////////////////////////////////////////////////////////////////////////////
//
//
// Date / Time  Functions
// 
// These functions are specifically for Dates or Time manipulation or computation.
//
//
// //////////////////////////////////////////////////////////////////////////////////////////////


// FUNCTION ************************************************************************************
//
// GetDaysBetweenDates
//
// Returns the number of days between two dates...
//
// Input  : fromDate [date object], toDate [date object]
//
// Output : numberOfDays [integer]
//
// *********************************************************************************************f
function GetDaysBetween(fromDate,toDate)
{
  if(!fromDate) { fromDate = new Date(); }
  if(!toDate)   { toDate   = new Date(); }

  Milliminutes = 1000 * 60;
  Millihours   = Milliminutes * 60;
  Millidays    = Millihours * 24;

  funcFromDate      = Date.parse(fromDate);
  funcToDate        = Date.parse(toDate);
  differenceInDates = funcFromDate - funcToDate;

  return Math.round( differenceInDates / Millidays );
}


// FUNCTION ************************************************************************************
//
// GetDateByDayOffset
//
// Returns the date of Date + n days...
//
// Input  : fromDate [date object], days [integer]
//
// Output : funcDate [date object]
//
// *********************************************************************************************f
function GetDateByOffset(fromDate, numberOfDays)
{
  if(!numberOfDays) { numberOfDays = 0; }
  if(!fromDate || fromDate == "undefined" || fromDate == "null")
  {
   fromDate = new Date();
  }
  else
  { 
   fromDate = new Date(fromDate);
  }

  Milliminutes = 1000 * 60;
  Millihours   = Milliminutes * 60;
  Millidays    = Millihours * 24;

  funcDate     = Date.parse(fromDate) + (Millidays * numberOfDays);

  return (new Date(funcDate));  
}


// FUNCTION ************************************************************************************
//
// MakeNiceDate
//
// Returns the date in nice format, MM/DD/YYYY where "/" is specified....
//
// Input  : inputDate [date object], delimiter [string]
//
// Output : funcDate [string]
//
// *********************************************************************************************f
function MakeNiceDate(inputDate, delimiter)
{
  if(!delimiter) { delimiter = "/"; }
  inputDate = new Date(inputDate);

  funcDate = (inputDate.getMonth() + 1) + delimiter + 
             inputDate.getDate()        + delimiter + 
             inputDate.getFullYear();

  return funcDate;
}



// FUNCTION ************************************************************************************
//
// MakeNiceTime
//
// Returns the time in nice format, HH:MM AM/PM where ":" is specified....
//
// Input  : inputTime [date object], delimiter [string]
//
// Output : funcTime [string]
//
// *********************************************************************************************f
function MakeNiceTime(inputTime, delimiter)
{
  if(!delimiter) { delimiter = ":"; }
  inputTime = new Date(inputTime);

  H    = (inputTime.getHours() > 12)  ? inputTime.getHours()-12 : inputTime.getHours();
  SUFF = (inputTime.getHours() >= 12) ? " pm" : " am";
  M    = (inputTime.getMinutes() <10) ? "0"+inputTime.getMinutes() : inputTime.getMinutes();
  
  funcTime = H + delimiter + M + SUFF;

  return funcTime;
}


// FUNCTION ************************************************************************************
//
// MinutesToTime
//
// Converts an input of minutes from midnight to a "readable" time object. The object has
// hours in obj.h and minutes in obj.m
//
// Input  : inputMinutes [integer]
//
// Output : Time [object]
//
// *********************************************************************************************f
function MinutesToTime(inputMinutes)
{   
 funcTime = new Object();
 hours    = Math.floor(inputMinutes / 60);
 minutes  = inputMinutes - (hours * 60);

 if (minutes < 10) { minutes = '0' + minutes; }
 if (hours > 12)   { hours  -= 12;            }
 if (hours < 10)   { hours   = '0' + hours;   }

 funcTime.hours   = hours;
 funcTime.minutes = minutes;

 return (funcTime);
}


// FUNCTION ************************************************************************************
//
// PrintNiceTime
//
// Takes minutes from midnight and returns a string of "nice" time format eg. "3:03 am"
//
// Input  : inputMinutes [integer]
//
// Output : "nice" Time [string]
//
// *********************************************************************************************
function PrintNiceTime(inputMinutes)
{
  if(parseFloat("0"+inputMinutes) == 0){return "";}
  suffix = "";
  tyme   = MinutesToTime(inputMinutes);

  if(inputMinutes >= 720) { suffix = " pm"; }
  else                   { suffix = " am"; }

  return funcTime.hours + ":" + funcTime.minutes + suffix;
}



// FUNCTION ************************************************************************************
//
// TimeToMinutes
//
// Takes pretty-time and converts to minutes past midnight
//
// Input  : strTime [string]
//
// Output : minutes [integer]
//
// *********************************************************************************************
function TimeToMinutes(strTime)
{
  if(strTime == "") { return ""; }

  timeArr = strTime.split(":");
  hours   = parseFloat("0"+timeArr[0]);
  timeArr = timeArr[1].split(" ");
  minutes = parseFloat("0"+timeArr[0]);
  if(timeArr[1].indexOf("pm") > -1) { hours += 12; } 
  minutes = minutes + (hours * 60);

  return minutes;
}



// FUNCTION ************************************************************************************
//
// TimeSelectionList
//
// Just a wrapper around GetTimeSelectionList to allow for ?:?? am as values...
//
// Input  : selName [string], interval [integer], , selectedTime [string], onchange [string], 
//          firstOptText [string], firstOptValue [string]
//
// Output : timeList [string]
//
// NOTE : Interval must be in minutes.
//
// *********************************************************************************************
function TimeSelectionList(selName,interval,selectedTime,onchange,firstOptText,firstOptValue,size,options)
{
  selectedTime = TimeToMinutes(selectedTime);
  return GetTimeSelectionList(selName,interval,'',1200,selectedTime,onchange,firstOptText,firstOptValue,true,size,options);
}


// FUNCTION ************************************************************************************
//
// GetTimeSelectionList
//
// Takes 3 optional params and returns HTML for a select list with time...
//
// Input  : selName [string], interval [integer], startTime [integer], endTime [integer], 
//          selectedTime [integer], onchange [string], firstOption [string], timeAsValue [boolean]
//
// Output : timeList [string]
//
// NOTE : Interval must be in minutes.
//
// *********************************************************************************************
function GetTimeSelectionList(selName,interval,startTime,endTime,selectedTime,onchange,firstOptText,firstOptValue,timeAsValue,size,options)
{
  interval  = (interval!="" || interval) ? interval : 30;
  startTime = (startTime) ? startTime : 360;
  endTime = (endTime) ? endTime : 1080;
  onchange  = (onchange != "") ? 'onchange"'+onchange+'"' : '';
  size      = (size) ? size : 1; 

  timeList  = '<select name="'+selName+'" size="'+size+'"' + onchange + ' '+options+'>';
  timeList += (firstOptText != "") ? '<option value="'+firstOptValue+'">'+firstOptText+'</option>' : '';

  // --> from start to finish...
  //
  for(currTime = startTime; currTime <= endTime; currTime += interval)
  {
    if(selectedTime == currTime) { selected = "selected"; } 
    else                         { selected = "";         }
    if(timeAsValue) { timeList += '<option ' + selected + ' value="'+ PrintNiceTime(currTime) + '">'; }
    else            { timeList += '<option ' + selected + ' value="'+ currTime + '">';                }
    timeList += '&nbsp;' + PrintNiceTime(currTime) + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>';
  }
   
  return timeList + '</select>';
}



// FUNCTION ************************************************************************************
//
// GetWeekDayId
//
// Returns the day id [integer] of the specific day. eg. 2 => Tuesday
//
// Input  : inputDate [string or object]
//
// Output : day id [integer]
//
// *********************************************************************************************
function GetWeekDayId(inputDate) 
{
 if(typeof(inputDate) == "string")
 {
  dateArray = inputDate.split('/');
  month     = dateArray[0];
  day       = dateArray[1];
  year      = dateArray[2];
  funcDate   = new Date(year,month-1,day);
 } 
 else 
 {
  funcDate   = new Date(inputDate);
 }
 
 return funcDate.getDay();
}


// FUNCTION ************************************************************************************
//
// GetToday
//
// Returns to days date in string format MM/DD/YYYY
//
// Input  : none
//
// Output : date [string]
//
// *********************************************************************************************
function GetToday()
{
 today = new Date();
 month = today.getMonth() + 1;
 day   = today.getDate();
 year  = today.getFullYear();

 return month + '/' + day + '/' + year;;
}


// FUNCTION ************************************************************************************
//
// GetCurrentTime
//
// Gets current time (server side, so the time on the server /CINCY/) and returns it in minutes
// past 12:00 midnight
//
// Input  : none
//
// Output : minutes [integer]
//
// *********************************************************************************************
function GetCurrentTime()
{
 today   = new Date();
 hours   = today.getHours();
 minutes = today.getMinutes();

 return hours * 60 + minutes;
}


// FUNCTION ************************************************************************************
//
// IsDateDigit & ValidateDate
//
// Validates dates (usually onblur and onkeypress)
//
// Input  : oField [object]
//
// Output : alert &/| boolean
//
// *********************************************************************************************f
var iSlashCount = 0;

function IsDateDigit(oField)
{ 
  iSlashCount = (oField.value.split("/")).length-1;
  iRangeStart = (iSlashCount >= 2) ? 48 : 47;
  return ( (event.keyCode >= iRangeStart) && (event.keyCode <= 57) ); 
}

function ValidateDate(sValue,oField)
{ 
  oToday  = new Date();
  sValue +="";

  if(sValue == "") return;

  aValue = sValue.split("/");
  
  if(aValue.length != 3)
  {
    if(sValue.length<4)
    {
     alert("OOPS!\nYour date is in the incorrect format. It must be in this format:\n\n\tMM/DD/YYYY");
     oField.select();
    }
    else
    {
      if(sValue.length>=6)
      {
        sValue = sValue.substr(0,2)+"/"+sValue.substr(2,2)+"/"+((sValue.substr(4)<100) ? "20"+sValue.substr(4) : sValue.substr(4));
        ValidateDate(sValue,oField);
      }
      else
      {
        alert("OOP!\nThis nifty program can't figure out the date.\n\nTry these formats:\n\tMM/DD/YYYY\n\tMMDDYY");
        oField.select();
      }
    }
  }
  else
  {
    if(aValue[0] > 12 || aValue[0] < 1)
    {
      alert("OOPS.\nThe month is incorrect. 1 - 12 please.\n\nTry again.");
      oField.select();
      return false;
    }
    if(aValue[1] > 31 || aValue[1] < 1)
    {
      alert("OOPS.\nThe day is incorrect. 1 - 31 please.\n\nTry again.");
      oField.select();
      return false;
    }
    aValue[2] = (aValue[2]<100) ? "20"+aValue[2] : aValue[2];
    if(aValue[2] < oToday.getFullYear())
    {
      alert("OOPS.\nThe year is incorrect. "+oToday.getFullYear()+" and later.\n\nTry again.");
      oField.select();
      return false;
    }

    oFieldDate = new Date(aValue[0]+"/"+aValue[1]+"/"+aValue[2]);
    if( GetDaysBetween(oFieldDate,oToday) < -1 )
    {
      alert("OOPS.\nYou cannot make something due in the past!\n\nToday is "+MakeNiceDate(oToday)+".\n\nTry again.");
      oField.value = MakeNiceDate(oToday);
      oField.select();
    }
  }
  oField.value=sValue;
}


// EOF;
