
/* Original:  Kedar R. Bhave (softricks@hotmail.com) 
 * Web Site:  http://www.softricks.com 
 *
 * This script and many more are available free online at
 * The JavaScript Source!! http://javascript.internet.com
 */
 
/* Modified by KNL for Learn.Net November 2001 
 * Calendar window background is white, not default
 * Print button is removed
 * Coding style is different (brackets, no tabs)
 * Removed formatting capability for various date formats
 * Added date parsing and initialization from form value
 */

var weekend = [0,6];
var weekendColor = "#e0e0e0";
var fontface = "Arial";

var gNow = new Date();
var ggWinCal;
var isNav = (navigator.appName.indexOf("Netscape") != -1) ? true : false;
var bIsIE = (navigator.appName.indexOf("Microsoft") != -1) ? true : false;

Calendar.Months = ["January", "February", "March", "April", "May", "June", 
"July", "August", "September", "October", "November", "December"];

// Non-Leap year Month days..
Calendar.DOMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// Leap year Month days..
Calendar.lDOMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

var isId=false;

function Calendar(p_item, p_WinCal, p_month, p_year, p_format) 
{
 if ((p_month == null) && (p_year == null)) return;

 if (p_WinCal == null)
  this.gWinCal = ggWinCal;
 else
  this.gWinCal = p_WinCal;
 
 if (p_month == null) 
 {
  this.gMonthName = null;
  this.gMonth = null;
  this.gYearly = true;
 }
 else 
 {
  this.gMonthName = Calendar.get_month(p_month);
  this.gMonth = new Number(p_month);
  this.gYearly = false;
 }

 this.gYear = p_year;
 this.gFormat = p_format;
 this.gBGColor = "white";
 this.gFGColor = "black";
 this.gTextColor = "black";
 this.gHeaderColor = "black";
 
 var escQ = /'/g;
 this.gReturnItem = p_item.replace(escQ,"\\'");
}

Calendar.get_month = Calendar_get_month;
Calendar.get_daysofmonth = Calendar_get_daysofmonth;
Calendar.calc_month_year = Calendar_calc_month_year;
Calendar.print = Calendar_print;

function Calendar_get_month(monthNo) 
{
 return Calendar.Months[monthNo];
}

function Calendar_get_daysofmonth(monthNo, p_year) 
{
 /* 
 Check for leap year ..
 1.Years evenly divisible by four are normally leap years, except for... 
 2.Years also evenly divisible by 100 are not leap years, except for... 
 3.Years also evenly divisible by 400 are leap years. 
 */
 if ((p_year % 4) == 0) 
 {
  if ((p_year % 100) == 0 && (p_year % 400) != 0)
   return Calendar.DOMonth[monthNo];
 
  return Calendar.lDOMonth[monthNo];
 }
   else
  return Calendar.DOMonth[monthNo];
}

function Calendar_calc_month_year(p_Month, p_Year, incr) 
{
 /* 
 Will return an 1-D array with 1st element being the calculated month 
 and second being the calculated year 
 after applying the month increment/decrement as specified by 'incr' parameter.
 'incr' will normally have 1/-1 to navigate thru the months.
 */
 var ret_arr = new Array();
 
 if (incr == -1) 
 {
  // B A C K W A R D
  if (p_Month == 0) 
  {
   ret_arr[0] = 11;
   ret_arr[1] = parseInt(p_Year) - 1;
  }
  else 
  {
   ret_arr[0] = parseInt(p_Month) - 1;
   ret_arr[1] = parseInt(p_Year);
  }
 }
 else if (incr == 1) 
 {
  // F O R W A R D
  if (p_Month == 11) 
  {
   ret_arr[0] = 0;
   ret_arr[1] = parseInt(p_Year) + 1;
  }
  else 
  {
   ret_arr[0] = parseInt(p_Month) + 1;
   ret_arr[1] = parseInt(p_Year);
  }
 }
 
 return ret_arr;
}

function Calendar_print() 
{
 ggWinCal.print();
}

function Calendar_calc_month_year(p_Month, p_Year, incr) 
{
 /* 
 Will return an 1-D array with 1st element being the calculated month 
 and second being the calculated year 
 after applying the month increment/decrement as specified by 'incr' parameter.
 'incr' will normally have 1/-1 to navigate thru the months.
 */
 var ret_arr = new Array();
 
 if (incr == -1) 
 {
  // B A C K W A R D
  if (p_Month == 0) 
  {
   ret_arr[0] = 11;
   ret_arr[1] = parseInt(p_Year) - 1;
  }
  else 
  {
   ret_arr[0] = parseInt(p_Month) - 1;
   ret_arr[1] = parseInt(p_Year);
  }
 }
 else if (incr == 1) 
 {
  // F O R W A R D
  if (p_Month == 11) 
  {
   ret_arr[0] = 0;
   ret_arr[1] = parseInt(p_Year) + 1;
  }
  else 
  {
   ret_arr[0] = parseInt(p_Month) + 1;
   ret_arr[1] = parseInt(p_Year);
  }
 }
 
 return ret_arr;
}

// This is for compatibility with Navigator 3, we have to create and discard one object before the prototype object exists.
new Calendar();

Calendar.prototype.getMonthlyCalendarCode = function() 
{
 var vCode = "";
 var vHeader_Code = "";
 var vData_Code = "";
 
 // Begin Table Drawing code here..
 vCode = vCode + "<TABLE BORDER=1 BGCOLOR=\"" + this.gBGColor + "\">";
 
 vHeader_Code = this.cal_header();
 vData_Code = this.cal_data();
 vCode = vCode + vHeader_Code + vData_Code;
 
 vCode = vCode + "</TABLE>";
 
 return vCode;
}

Calendar.prototype.show = function() 
{
 var vCode = "";
 
 this.gWinCal.document.open();

 // Setup the page...
 this.wwrite("<html>");
 this.wwrite("<head><title>Calendar</title>");
 this.wwrite("<script src='/js/date-picker.js'></script>");
 this.wwrite("<style>");
 this.wwrite("BODY { font-face: arial; font-size: 12px; } ");
 this.wwrite("TH { font-face: arial; color: blue; background-color: white; font-size: 12px; } ");
 this.wwrite("</style>");
 this.wwrite("</head>");

 this.wwrite("<body " + 
  "bgcolor='white' " +
  "link=\"" + this.gLinkColor + "\" " + 
  "vlink=\"" + this.gLinkColor + "\" " +
  "alink=\"" + this.gLinkColor + "\" " +
  "text=\"" + this.gTextColor + "\"" +
  "onLoad='window.focus()'>");
 this.wwriteA("<B>");
 this.wwriteA(this.gMonthName + " " + this.gYear);
 this.wwriteA("</B><BR>");

 // Show navigation buttons
 var prevMMYYYY = Calendar.calc_month_year(this.gMonth, this.gYear, -1);
 var prevMM = prevMMYYYY[0];
 var prevYYYY = prevMMYYYY[1];

 var nextMMYYYY = Calendar.calc_month_year(this.gMonth, this.gYear, 1);
 var nextMM = nextMMYYYY[0];
 var nextYYYY = nextMMYYYY[1];
 
 this.wwrite("<TABLE WIDTH='100%' BORDER=1 CELLSPACING=0 CELLPADDING=0 BGCOLOR='#e0e0e0'><TR><TD ALIGN=center>");
 this.wwrite("<A HREF=\"" +
  "javascript:window.opener.Build(" + 
  "'" + this.gReturnItem + "', '" + this.gMonth + "', '" + (parseInt(this.gYear)-1) + "', '" + this.gFormat + "'" +
  ");" +
  "\">[<<]<\/A></TD><TD ALIGN=center>");
 this.wwrite("<A HREF=\"" +
  "javascript:window.opener.Build(" + 
  "'" + this.gReturnItem + "', '" + prevMM + "', '" + prevYYYY + "', '" + this.gFormat + "'" +
  ");" +
  "\">[<]<\/A></TD><TD ALIGN=center>");
 //this.wwrite("[<A HREF=\"javascript:window.print();\">Print</A>]</TD><TD ALIGN=center>");
 this.wwrite("<A HREF=\"" +
  "javascript:window.opener.Build(" + 
  "'" + this.gReturnItem + "', '" + nextMM + "', '" + nextYYYY + "', '" + this.gFormat + "'" +
  ");" +
  "\">[>]<\/A></TD><TD ALIGN=center>");
 this.wwrite("<A HREF=\"" +
  "javascript:window.opener.Build(" + 
  "'" + this.gReturnItem + "', '" + this.gMonth + "', '" + (parseInt(this.gYear)+1) + "', '" + this.gFormat + "'" +
  ");" +
  "\">[>>]<\/A></TD></TR></TABLE><BR>");

 // Get the complete calendar code for the month..
 vCode = this.getMonthlyCalendarCode();
 this.wwrite(vCode);

 this.wwrite("</font></body></html>");
 this.gWinCal.document.close();
}

Calendar.prototype.showY = function() 
{
 var vCode = "";
 var i;
 var vr, vc, vx, vy;  // Row, Column, X-coord, Y-coord
 var vxf = 285;   // X-Factor
 var vyf = 200;   // Y-Factor
 var vxm = 10;   // X-margin
 var vym;        // Y-margin
 if (bIsIE) vym = 75;
 else if (isNav) vym = 25;
 
 this.gWinCal.document.open();

 this.wwrite("<html>");
 this.wwrite("<head><title>Calendar</title>");

 this.wwrite("</head>");

 this.wwrite("<body " + 
  "link=\"" + this.gLinkColor + "\" " + 
  "vlink=\"" + this.gLinkColor + "\" " +
  "alink=\"" + this.gLinkColor + "\" " +
  "text=\"" + this.gTextColor + "\">" +
  "onLoad='window.focus()'>");
 this.wwrite("<B>");
 this.wwrite("Year : " + this.gYear);
 this.wwrite("</B><BR>");

 // Show navigation buttons
 var prevYYYY = parseInt(this.gYear) - 1;
 var nextYYYY = parseInt(this.gYear) + 1;
 
 this.wwrite("<TABLE WIDTH='100%' BORDER=1 CELLSPACING=0 CELLPADDING=0 BGCOLOR='#e0e0e0'><TR><TD ALIGN=center>");
 this.wwrite("<A HREF=\"" +
  "javascript:window.opener.Build(" + 
  "'" + this.gReturnItem + "', null, '" + prevYYYY + "', '" + this.gFormat + "'" +
  ");" +
  "\" alt='Prev Year'>[<<]<\/A></TD><TD ALIGN=center>");
 //this.wwrite("[<A HREF=\"javascript:window.print();\">Print</A>]</TD><TD ALIGN=center>");
 this.wwrite("<A HREF=\"" +
  "javascript:window.opener.Build(" + 
  "'" + this.gReturnItem + "', null, '" + nextYYYY + "', '" + this.gFormat + "'" +
  ");" +
  "\">[>>]<\/A></TD></TR></TABLE><BR>");

 // Get the complete calendar code for each month..
 var j;
 for (i=11; i>=0; i--) 
   {
  if (bIsIE)
   this.wwrite("<DIV ID=\"layer" + i + "\" CLASS=\"lclass" + i + "\">");
  else if (isNav)
   this.wwrite("<LAYER ID=\"layer" + i + "\" CLASS=\"lclass" + i + "\">");

  this.gMonth = i;
  this.gMonthName = Calendar.get_month(this.gMonth);
  vCode = this.getMonthlyCalendarCode();
  this.wwrite(this.gMonthName + "/" + this.gYear + "<BR>");
  this.wwrite(vCode);

  if (bIsIE)
   this.wwrite("</DIV>");
  else if (isNav)
   this.wwrite("</LAYER>");
 }

 this.wwrite("</font><BR></body></html>");
 this.gWinCal.document.close();
}

Calendar.prototype.wwrite = function(wtext) 
{
 this.gWinCal.document.writeln(wtext);
}

Calendar.prototype.wwriteA = function(wtext) 
{
 this.gWinCal.document.write(wtext);
}

Calendar.prototype.cal_header = function() 
{
 var vCode = "";
 
 vCode = vCode + "<TR>";
 vCode = vCode + "<TH WIDTH='14%'>Sun</TH>";
 vCode = vCode + "<TH WIDTH='14%'>Mon</TH>";
 vCode = vCode + "<TH WIDTH='14%'>Tue</TH>";
 vCode = vCode + "<TH WIDTH='14%'>Wed</TH>";
 vCode = vCode + "<TH WIDTH='14%'>Thu</TH>";
 vCode = vCode + "<TH WIDTH='14%'>Fri</TH>";
 vCode = vCode + "<TH WIDTH='16%'>Sat</TH>";
 vCode = vCode + "</TR>";
 
 return vCode;
}

Calendar.prototype.cal_data = function() 
{
 var vDate = new Date();
 vDate.setDate(1);
 vDate.setMonth(this.gMonth);
 vDate.setFullYear(this.gYear);

 var vFirstDay=vDate.getDay();
 var vDay=1;
 var vLastDay=Calendar.get_daysofmonth(this.gMonth, this.gYear);
 var vOnLastDay=0;
 var vCode = "";

 /*
 Get day for the 1st of the requested month/year..
 Place as many blank cells before the 1st day of the month as necessary. 
 */

 vCode = vCode + "<TR>";
 for (i=0; i<vFirstDay; i++) 
 {
  vCode = vCode + "<TD WIDTH='14%'" + this.write_weekend_string(i) + " align=center><FONT SIZE='2' FACE='" + fontface + "'> </FONT></TD>";
 }

 // Write rest of the 1st week
 for (j=vFirstDay; j<7; j++) 
 {

   var onClickTxt="";
   //if(isId)
  // {
      onClickTxt = "_calGetElement('" + this.gReturnItem + "',window.opener)";
  // }
   //else
   //{
   //   onClickTxt = "self.opener.document." + this.gReturnItem;
  // }
 
  vCode = vCode + "<TD WIDTH='14%'" + this.write_weekend_string(j) + " align=center><FONT SIZE='2' FACE='" + fontface + "'>" + 
   "<A HREF='#' " + 
     "onclick= \"" + onClickTxt + ".value = '" +
    this.format_data(vDay) +  "';" +
    "if("+onClickTxt+".onchange != null)"+onClickTxt+".onchange();" +
    "window.close();\">" + 
    this.format_day(vDay) + 
   "</A>" + 
   "</FONT></TD>";
  vDay=vDay + 1;
 }
 vCode = vCode + "</TR>";

 // Write the rest of the weeks
 for (k=2; k<7; k++) 
 {
  vCode = vCode + "<TR>";

  for (j=0; j<7; j++) 
  {
   vCode = vCode + "<TD WIDTH='14%'" + this.write_weekend_string(j) + " align=center><FONT SIZE='2' FACE='" + fontface + "'>" + 
    "<A HREF='#' " + 
      "onclick= \"" + onClickTxt + ".value = '" +
    this.format_data(vDay) +  "';" +
    "if("+onClickTxt+".onchange != null)"+onClickTxt+".onchange();" +
    "window.close();\">" + 
     this.format_day(vDay) + 
    "</A>" + 
    "</FONT></TD>";
   vDay=vDay + 1;

   if (vDay > vLastDay) 
   {
    vOnLastDay = 1;
    break;
   }
  }

  if (j == 6)
   vCode = vCode + "</TR>";
  if (vOnLastDay == 1)
   break;
 }
 
 // Fill up the rest of last week with proper blanks, so that we get proper square blocks
 for (m=1; m<(7-j); m++) 
 {
  if (this.gYearly)
   vCode = vCode + "<TD WIDTH='14%'" + this.write_weekend_string(j+m) + 
   "><FONT style='font-size:12px' FACE='" + fontface + "' COLOR='gray'> </FONT></TD>";
  else
   vCode = vCode + "<TD WIDTH='14%'" + this.write_weekend_string(j+m) + 
   "><FONT style='font-size:12px' FACE='" + fontface + "' COLOR='gray'>" + m + "</FONT></TD>";
 }
 
 return vCode;
}

Calendar.prototype.format_day = function(vday) 
{
 var vNowDay = gNow.getDate();
 var vNowMonth = gNow.getMonth();
 var vNowYear = gNow.getFullYear();

 if (vday == vNowDay && this.gMonth == vNowMonth && this.gYear == vNowYear)
  return ("<FONT COLOR=\"RED\"><B> " + vday + " </B></FONT>");
 else
  return (" " + vday + " ");
}

Calendar.prototype.write_weekend_string = function(vday) 
{
 var i;

 // Return special formatting for the weekend day.
 for (i=0; i<weekend.length; i++) 
 {
  if (vday == weekend[i])
   return (" BGCOLOR=\"" + weekendColor + "\"");
 }
 
 return "";
}

Calendar.prototype.format_data = function(p_day) 
{
 var vData;
 var vMonth = 1 + this.gMonth;
 vMonth = (vMonth.toString().length < 2) ? "0" + vMonth : vMonth;
 var vY4 = new String(this.gYear);
 var vDD = (p_day.toString().length < 2) ? "0" + p_day : p_day;
 
 //var vMon = Calendar.get_month(this.gMonth).substr(0,3).toUpperCase();
 //var vFMon = Calendar.get_month(this.gMonth).toUpperCase();
 //var vY2 = new String(this.gYear.substr(2,2));


 vData = vMonth + "\/" + vDD + "\/" + vY4;  // KNL assume MM/DD/YYYY - removed switch stmt
 
 return vData;
}

function Build(p_item, p_month, p_year, p_format) 
{
 var p_WinCal = ggWinCal;
 gCal = new Calendar(p_item, p_WinCal, p_month, p_year, p_format);

 // Customize your Calendar here..
 gCal.gBGColor="white";
 gCal.gLinkColor="black";
 gCal.gTextColor="black";
 gCal.gHeaderColor="blue";

 // Choose appropriate show function
 if (gCal.gYearly) gCal.showY();
 else gCal.show();
}

function show_calendar_orig() 
{
 /* 
  p_month : 0-11 for Jan-Dec; 12 for All Months.
  p_year : 4-digit year
  p_format: Date format (mm/dd/yyyy, dd/mm/yy, ...)
  p_item : Return Item.
 */

 p_item = arguments[0];
 if (arguments[1] == null)
  p_month = new String(gNow.getMonth());
 else
  p_month = arguments[1];
 if (arguments[2] == "" || arguments[2] == null)
  p_year = new String(gNow.getFullYear().toString());
 else
  p_year = arguments[2];
 if (arguments[3] == null)
  p_format = "MM/DD/YYYY";
 else
  p_format = arguments[3];

 vWinCal = window.open("", "Calendar", 
  "width=250,height=250,status=no,resizable=no,top=200,left=200");
 vWinCal.opener = self;
 ggWinCal = vWinCal;

 Build(p_item, p_month, p_year, p_format);
}

/*
 * date parsing - this only supports MM/DD/YYYY
 */
function alldigits(s)
{
  for (var i=0; i<s.length; i++) 
    if ("0123456789".indexOf(s.charAt(i))<0) return false;
    
  return true;
}
function trim(s)
{
  var t = "";
  var c = s.charAt(0);
  for (var i=0; i<s.length; c = s.charAt(++i))
    if (c!=' ') t += c; 
  return t;
}
 
/*
 * show calendar - initialize with the value in the form
 */
function show_calendar()
{
 p_item = arguments[0];

 var vDateInput = null;

 var vInputElement = _calGetElement(p_item);

if(vInputElement == null)
{
 try
 {
    vDateInput = eval("document." + p_item + ".value");
    isId=false;
 }
 catch(err)
 {
    vDateInput = document.getElementById(p_item).value;
    isId=true;
 }
}
else
{
	vDateInput = vInputElement.value;
}


 var dt = new Date();
 
 
 var ms=null;
 
 if(vDateInput!=null && vDateInput.length>0)
 {
   ms = Date.parse(vDateInput);
 }
 
 if(ms!=null && ms.toString() == "NaN" && vDateInput.length>0)
 {
 	alert("Invalid date: " + vDateInput + ". Defaulting to current date");
 }
 else if(ms!=null && ms.toString()!="NaN")
 {
 	 dt.setTime(ms);
 }
 
 //if(ms.toString() != "NaN")
 //{
 //   dt.setTime(ms);
 //}


 var yr = dt.getYear();
 if(yr < 1900) yr += 2000;

   show_calendar_orig(p_item, dt.getMonth(), yr);

}

function _calGetElement(nam, w)
{
	var retval = null;
	if(nam.indexOf("forms.") == 0)
	{
		nam = nam.substring(6);
	}
	var idx = nam.indexOf(".");
	if(idx > 0)
	{
		var e1 = nam.substring(0,idx);
		var d = document;
		if(w != null)
			d = w.document;
		var ele1 = d.getElementById(e1);
		if(ele1 != null)
		{
			var e2 = nam.substring(idx+1);
			retval = ele1.children[e2];
		}
	}
	return retval;
}

/**************************************************************/
/**************************************************************/
/**************************************************************/

var datePickerDivID = "datepicker";
var iFrameDivID = "datepickeriframe";

var dayArrayShort = new Array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa');
var dayArrayMed = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
var dayArrayLong = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
var monthArrayShort = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
var monthArrayMed = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
var monthArrayLong = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
 
// these variables define the date formatting we're expecting and outputting.
// If you want to use a different format by default, change the defaultDateSeparator
// and defaultDateFormat variables either here or on your HTML page.
var defaultDateSeparator = "/";        // common values would be "/" or "."
var defaultDateFormat = "mdy"    // valid values are "mdy", "dmy", and "ymd"
var dateSeparator = defaultDateSeparator;
var dateFormat = defaultDateFormat;

/**
This is the main function you'll call from the onClick event of a button.
Normally, you'll have something like this on your HTML page:

Start Date: <input name="StartDate">
<input type=button value="select" onclick="displayDatePicker('StartDate');">

That will cause the datepicker to be displayed beneath the StartDate field and
any date that is chosen will update the value of that field. If you'd rather have the
datepicker display beneath the button that was clicked, you can code the button
like this:

<input type=button value="select" onclick="displayDatePicker('StartDate', this);">

So, pretty much, the first argument (dateFieldName) is a string representing the
name of the field that will be modified if the user picks a date, and the second
argument (displayBelowThisObject) is optional and represents an actual node
on the HTML document that the datepicker should be displayed below.

In version 1.1 of this code, the dtFormat and dtSep variables were added, allowing
you to use a specific date format or date separator for a given call to this function.
Normally, you'll just want to set these defaults globally with the defaultDateSeparator
and defaultDateFormat variables, but it doesn't hurt anything to add them as optional
parameters here. An example of use is:

<input type=button value="select" onclick="displayDatePicker('StartDate', false, 'dmy', '.');">

This would display the datepicker beneath the StartDate field (because the
displayBelowThisObject parameter was false), and update the StartDate field with
the chosen value of the datepicker using a date format of dd.mm.yyyy

y_offset : name of the element containing datePicker
*/
function displayDatePicker(dateFieldName, displayBelowThisObject, dtFormat, dtSep, y_offset)
{

  var targetDateField = $(dateFieldName);

  if (!displayBelowThisObject)
	  displayBelowThisObject = $(targetDateField.parentNode);
	  	
  // if we weren't told what node to display the datepicker beneath, just display it
  // beneath the date field we're updating
  if (!displayBelowThisObject)
    displayBelowThisObject = targetDateField;
 
  // if a date separator character was given, update the dateSeparator variable
  if (dtSep)
    dateSeparator = dtSep;
  else
    dateSeparator = defaultDateSeparator;
 
  // if a date format was given, update the dateFormat variable
  if (dtFormat)
    dateFormat = dtFormat;
  else
    dateFormat = defaultDateFormat;
 
   var x;
   var y;
 try
 {
  
 
   var y1 = displayBelowThisObject.positionedOffset().top;
   //var y1a = $(targetDateField).cumulativeOffset().top;
   
   var y2 = $(targetDateField).cumulativeScrollOffset().top;
   var queenY = 0;
   var bScroll = false;
   var divScroll = false;
   
    var root= document.compatMode =='BackCompat'? document.body : document.documentElement;
	 var mainScroll= root.scrollHeight>root.clientHeight;
	 
	 
	 //do a loop if we have to
	  if(targetDateField.scrollHeight>targetDateField.clientHeight)
  	  {
  		   divScroll = true;
  	  }
  	  else
  	  {
	    var divEl = targetDateField.up();
	 
	 	while(divEl!=root)
  	 	{
  		 //alert('div id: ' + $(divEl).id + " scrollHeight=" + $(divEl).scrollHeight + " clientHeight: " + $(divEl).clientHeight);
  		
  		 if(divEl.scrollHeight>divEl.clientHeight && divEl.clientHeight>0)
  		 {
  		   divScroll = true;
  		   //alert('found scroll, break!');
  		   break;
  		 }
  		 
  		 divEl = divEl.up();
   	 	}
   	  } 
   
   //alert('y1,y2:' + y1 + ',' + y2);
   
   //on manage coursework, in IE, it is offsetting from the right pane/div, freaking nuts!
   
   if(bIsIE)
   {	
     if(mainScroll || divScroll)
     { 
       //alert('there is a scroll');
       queenY = y1 - y2;
       bScroll = true;
      }
      else
      {
       //alert('no scroll');
       queenY = y1;
      }
      
   }  
   else 
   {   
       if(y2>0)
       {
         bScroll = true;
       }
       
       queenY = y1 - y2;  
         
   }   
 
   
   x = targetDateField.positionedOffset().left;
   y = queenY;// + displayBelowThisObject.getDimensions().height;//displayBelowThisObject.positionedOffset().top + displayBelowThisObject.getDimensions().height ;
 }
 catch(e)
 {
    x =displayBelowThisObject.offsetLeft;
    x+= targetDateField.next(".calendarButton").offsetLeft;
   y = displayBelowThisObject.offsetTop;
 }
 
  // deal with elements inside tables and such 

  drawDatePicker(targetDateField, x, y, displayBelowThisObject, bScroll, mainScroll, divScroll);
}



function ObjectPosition(obj) 
{
    var curleft = 0;
     var curtop = 0;
     
      if (obj.offsetParent) 
      {
            do 
            {
                  curleft += obj.offsetLeft;
                  curtop += obj.offsetTop;
            } 
            while (obj = obj.offsetParent);
      }
      return [curleft,curtop];
}

function getHeight() 
{
    /**
     * Mozilla/netscape/opera/IE7+
     */
    if (typeof window.innerHeight !== 'undefined') {
        return window.innerHeight;
    }
    /**
     * IE6 in standards compliant mode with valid doctype
     */
    if (typeof document.documentElement != 'undefined'
            && typeof document.documentElement.clientHeight != 'undefined'
            && document.documentElement.clientHeight != 0) {
        return document.documentElement.clientHeight;
    }
    /**
     * older versions of IE
     */
    return document.getElementsByTagName('body')[0].clientHeight;
}

/**
Draw the datepicker object (which is just a table with calendar elements) at the
specified x and y coordinates, using the targetDateField object as the input tag
that will ultimately be populated with a date.

This function will normally be called by the displayDatePicker function.
*/
function drawDatePicker(targetDateField, x, y, displayBelowThisObject, isScroll, mainScroll, divScroll)
{
  var dt = getFieldDate(targetDateField.value );
 
  // the datepicker table will be drawn inside of a <div> with an ID defined by the
  // global datePickerDivID variable. If such a div doesn't yet exist on the HTML
  // document we're working with, add one.
  if (!document.getElementById(datePickerDivID)) {
    // don't use innerHTML to update the body, because it can cause global variables
    // that are currently pointing to objects on the page to have bad references
    //document.body.innerHTML += "<div id='" + datePickerDivID + "' class='dpDiv'></div>";
    
    var newNode = new Element("div");
    
    newNode.setAttribute("id", datePickerDivID);
    newNode.addClassName("dpDiv");
    newNode.setAttribute("style", "visibility: hidden;");

    targetDateField = $(targetDateField);
  	$(displayBelowThisObject).insert(newNode);
  	//alert('inserted calendar at; ' + $(displayBelowThisObject).id)
  }
 
  //this is to insure that the datepicker doesnt display too low on the screen
    var height = getHeight();//document.body.clientHeight;
    var bottomOffset = 0;
    
   //alert('viewport:' + targetDateField.viewportOffset().top + ' height:' + height);
    
    if(getHeight()>document.body.scrollHeight && !isScroll)
    {
       bottomOffset = height -y;
     //  alert('no scroll');
    }
    else
    {
       //alert('scroll');
       bottomOffset = height - targetDateField.viewportOffset().top;
      // alert(bottomOffset);
       
        if(mainScroll)
        {
           y = y + targetDateField.cumulativeScrollOffset().top;
        }
       
    }
   
  /*
    if(mainScroll)
      alert('mainscroll');
    else if(divScroll)
           alert('divscroll');  
    */
  
   // alert('before offset, y=' + y);
    if(bottomOffset<175)
    {
      y = y - (175-bottomOffset);
    }
   // alert('after offset, y=' + y);
  
 
  // move the datepicker div to the proper x,y coordinate and toggle the visiblity
  var pickerDiv = $(datePickerDivID);
  pickerDiv.style.position = "absolute";
  pickerDiv.style.left = x + "px";
  pickerDiv.style.top = y + "px";
  pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
  pickerDiv.style.display = (pickerDiv.style.display == "block" ? "none" : "block");
  pickerDiv.style.zIndex = 10000;
  pickerDiv.style.width = "11em";
 
  // draw the datepicker table
  
  refreshDatePicker(targetDateField.id, dt.getFullYear(), dt.getMonth(), dt.getDate());
}


/**
This is the function that actually draws the datepicker calendar.
*/
function refreshDatePicker(dateFieldName, year, month, day)
{
	//convert double quotes back to single quotes
	dateFieldName = dateFieldName.replace(/\"/g, "'");
	
  // if no arguments are passed, use today's date; otherwise, month and year
  // are required (if a day is passed, it will be highlighted later)
  var thisDay = new Date();
 
  if ((month >= 0) && (year > 0)) {
    thisDay = new Date(year, month, 1);
  } else {
    day = thisDay.getDate();
    thisDay.setDate(1);
  }
  // the calendar will be drawn as a table
  // you can customize the table elements with a global CSS style sheet,
  // or by hardcoding style and formatting elements below
  var crlf = "\r\n";
  var TABLE = "<table cols=7 class='dpTable'>" + crlf;
  var xTABLE = "</table>" + crlf;
  var TR = "<tr class='dpTR'>";
  var TR_title = "<tr class='dpTitleTR'>";
  var TR_days = "<tr class='dpDayTR'>";
  var TR_todaybutton = "<tr class='dpTodayButtonTR'>";
  var xTR = "</tr>" + crlf;
  var TD = "<td class='dpTD' onMouseOut='this.className=\"dpTD\";' onMouseOver=' this.className=\"dpTDHover\";' ";    // leave this tag open, because we'll be adding an onClick event
  var TD_title = "<td colspan=5 class='dpTitleTD'>";
  var TD_buttons = "<td class='dpButtonTD'>";
  var TD_todaybutton = "<td colspan=7 class='dpTodayButtonTD'>";
  var TD_days = "<td class='dpDayTD'>";
  var TD_selected = "<td class='dpDayHighlightTD' onMouseOut='this.className=\"dpDayHighlightTD\";' onMouseOver='this.className=\"dpTDHover\";' ";    // leave this tag open, because we'll be adding an onClick event
  var xTD = "</td>" + crlf;
  var DIV_title = "<div class='dpTitleText'>";
  var DIV_selected = "<div class='dpDayHighlight'>";
  var xDIV = "</div>";
 
  // start generating the code for the calendar table
  var html = TABLE;
 
  // this is the title bar, which displays the month and the buttons to
  // go back to a previous month or forward to the next month
  html += TR_title;
  html += TD_buttons + getButtonCode(dateFieldName, thisDay, -1, "&lt;") + xTD;
  html += TD_title + DIV_title + monthArrayLong[ thisDay.getMonth()] + " " + thisDay.getFullYear() + xDIV + xTD;
  html += TD_buttons + getButtonCode(dateFieldName, thisDay, 1, "&gt;") + xTD;
  html += xTR;
 
  // this is the row that indicates which day of the week we're on
  html += TR_days;
  for(i = 0; i < dayArrayShort.length; i++)
    html += "<th>" + dayArrayShort[i] + "</th>";
  html += xTR;
 
  // now we'll start populating the table with days of the month
  html += TR;
 
  // first, the leading blanks
  for (i = 0; i < thisDay.getDay(); i++)
    html += TD + "&nbsp;" + xTD;
 
  // now, the days of the month
  do {
    dayNum = thisDay.getDate();

	var tempDateFieldName = dateFieldName.replace(/'/g,"\\'");
    TD_onclick = " onclick=\"updateDateField('" + tempDateFieldName + "', '" + getDateString(thisDay) + "');\">";
    
    if (dayNum == day)
      html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
    else
      html += TD + TD_onclick + dayNum + xTD;
    
    // if this is a Saturday, start a new row
    if (thisDay.getDay() == 6)
      html += xTR + TR;
    
    // increment the day
    thisDay.setDate(thisDay.getDate() + 1);
  } while (thisDay.getDate() > 1)
 
  // fill in any trailing blanks
  if (thisDay.getDay() > 0) {
    for (i = 6; i > thisDay.getDay(); i--)
      html += TD + "&nbsp;" + xTD;
  }
  html += xTR;
 
  // add a button to allow the user to easily return to today, or close the calendar
  var today = new Date();
  var todayString = "Today is " + dayArrayMed[today.getDay()] + ", " + monthArrayMed[ today.getMonth()] + " " + today.getDate();
  html += TR_todaybutton + TD_todaybutton;
  
  var tempDateFieldName = dateFieldName.replace(/'/g, "\\\"");
  var t = "";
  t += "<input type='button' value='Today' class='button' onClick='refreshDatePicker(\"" + tempDateFieldName + "\");'></input> ";
  t += "<input type='button' value='Close' class='button' onClick='updateDateField(\"" + tempDateFieldName + "\");'></input>";
  html += t;
  html += xTD + xTR;
 
  // and finally, close the table
  html += xTABLE;
  document.getElementById(datePickerDivID).innerHTML = html;
  // add an "iFrame shim" to allow the datepicker to display above selection lists
  if(Maple.isIE("6"))
  		adjustiFrame();
}


/**
Convenience function for writing the code for the buttons that bring us back or forward
a month.
*/
function getButtonCode(dateFieldName, dateVal, adjust, label)
{
  var newMonth = (dateVal.getMonth () + adjust) % 12;
  var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
  if (newMonth < 0) {
    newMonth += 12;
    newYear += -1;
  }

  var tempDateFieldName = dateFieldName.replace(/'/g, "\\\"");
  return "<input type='button' value='" + label + "' class='button' onClick='refreshDatePicker(\"" + tempDateFieldName.replace(/'/g, "\\'") + "\", " + newYear + ", " + newMonth + ");'></input>";
	
}


/**
Convert a JavaScript Date object to a string, based on the dateFormat and dateSeparator
variables at the beginning of this script library.
*/
function getDateString(dateVal)
{
  var dayString = "00" + dateVal.getDate();
  var monthString = "00" + (dateVal.getMonth()+1);
  dayString = dayString.substring(dayString.length - 2);
  monthString = monthString.substring(monthString.length - 2);
 
  var val;
  switch (dateFormat) {
    case "dmy" :
      val = dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();
    case "ymd" :
      val =  dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;
    case "mdy" :
    default :
      val =  monthString + dateSeparator + dayString + dateSeparator + dateVal.getFullYear();
  }
  return val;
}


/**
Convert a string to a JavaScript Date object.
*/
function getFieldDate(dateString)
{
  var dateVal;
  var dArray;
  var d, m, y;
  try {
    dArray = splitDateString(dateString);
    if (dArray) {
      switch (dateFormat) {
        case "dmy" :
          d = parseInt(dArray[0], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
        case "ymd" :
          d = parseInt(dArray[2], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[0], 10);
          break;
        case "mdy" :
        default :
          d = parseInt(dArray[1], 10);
          m = parseInt(dArray[0], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
      }
      dateVal = new Date(y, m, d);
//	  if(dateVal.getYear() < 50)
//  		dateVal.setYear(dateVal.getYear() + 2000);
//	  else
//  		dateVal.setYear(dateVal.getYear() + 1900);
    } else if (dateString) {
      dateVal = new Date(dateString);
    } else {
      dateVal = new Date();
    }
  } catch(e) {
    dateVal = new Date();
  }
  
  	
  return dateVal;
}


/**
Try to split a date string into an array of elements, using common date separators.
If the date is split, an array is returned; otherwise, we just return false.
*/
function splitDateString(dateString)
{
  var dArray;
  if (dateString.indexOf("/") >= 0)
    dArray = dateString.split("/");
  else if (dateString.indexOf(".") >= 0)
    dArray = dateString.split(".");
  else if (dateString.indexOf("-") >= 0)
    dArray = dateString.split("-");
  else if (dateString.indexOf("\\") >= 0)
    dArray = dateString.split("\\");
  else
    dArray = false;
 
  return dArray;
}

/**
Update the field with the given dateFieldName with the dateString that has been passed,
and hide the datepicker. If no dateString is passed, just close the datepicker without
changing the field value.

Also, if the page developer has defined a function called datePickerClosed anywhere on
the page or in an imported library, we will attempt to run that function with the updated
field as a parameter. This can be used for such things as date validation, setting default
values for related fields, etc. For example, you might have a function like this to validate
a start date field:

function datePickerClosed(dateField)
{
  var dateObj = getFieldDate(dateField.value);
  var today = new Date();
  today = new Date(today.getFullYear(), today.getMonth(), today.getDate());
 
  if (dateField.name == "StartDate") {
    if (dateObj < today) {
      // if the date is before today, alert the user and display the datepicker again
      alert("Please enter a date that is today or later");
      dateField.value = "";
      document.getElementById(datePickerDivID).style.visibility = "visible";
      adjustiFrame();
    } else {
      // if the date is okay, set the EndDate field to 7 days after the StartDate
      dateObj.setTime(dateObj.getTime() + (7 * 24 * 60 * 60 * 1000));
      var endDateField = document.getElementsByName ("EndDate").item(0);
      endDateField.value = getDateString(dateObj);
    }
  }
}

*/
function updateDateField(dateFieldName, dateString)
{
	//convert double quotes  back to single quotes.
	dateFieldName = dateFieldName.replace(/\"/g, "'");
  var targetDateField = document.getElementById(dateFieldName);
  if (dateString)
  {
    targetDateField.value = dateString;
    Event.fire($(targetDateField),"maple:changed");
   }
 
  var pickerDiv = document.getElementById(datePickerDivID);
  pickerDiv.style.visibility = "hidden";
  pickerDiv.style.display = "none";
 
  adjustiFrame();
  targetDateField.focus();
 
  // after the datepicker has closed, optionally run a user-defined function called
  // datePickerClosed, passing the field that was just updated as a parameter
  // (note that this will only run if the user actually selected a date from the datepicker)
  if ((dateString) && (typeof(datePickerClosed) == "function"))
    datePickerClosed(targetDateField);
}


/**
Use an "iFrame shim" to deal with problems where the datepicker shows up behind
selection list elements, if they're below the datepicker. The problem and solution are
described at:

http://dotnetjunkies.com/WebLog/jking/archive/2003/07/21/488.aspx
http://dotnetjunkies.com/WebLog/jking/archive/2003/10/30/2975.aspx
*/
function adjustiFrame(pickerDiv, iFrameDiv)
{
  // we know that Opera doesn't like something about this, so if we
  // think we're using Opera, don't even try
  var is_opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
  if (is_opera)
    return;
  
  // put a try/catch block around the whole thing, just in case
  try {
    if (!document.getElementById(iFrameDivID)) {
      // don't use innerHTML to update the body, because it can cause global variables
      // that are currently pointing to objects on the page to have bad references
      //document.body.innerHTML += "<iframe id='" + iFrameDivID + "' src='javascript:false;' scrolling='no' frameborder='0'>";
      var newNode = $(document.createElement("iFrame"));
      newNode.setAttribute("id", iFrameDivID);
//      newNode.setAttribute("src", "javascript:false;");
      newNode.setAttribute("scrolling", "no");
      newNode.setAttribute ("frameborder", "0");
      newNode.setAttribute({width:'0px',height:'0px'});
      document.body.appendChild(newNode);
    }
    
    if (!pickerDiv)
      pickerDiv = document.getElementById(datePickerDivID);
    if (!iFrameDiv)
      iFrameDiv = document.getElementById(iFrameDivID);
    try {
      iFrameDiv.style.position = "absolute";
      iFrameDiv.style.width = pickerDiv.offsetWidth;
      iFrameDiv.style.height = pickerDiv.offsetHeight ;
      iFrameDiv.style.top = pickerDiv.style.top;
      iFrameDiv.style.left = pickerDiv.style.left;
      iFrameDiv.style.zIndex = pickerDiv.style.zIndex - 1;
      iFrameDiv.style.visibility = pickerDiv.style.visibility ;
      iFrameDiv.style.display = pickerDiv.style.display;
    } catch(e) {
    }
 
  } catch (ee) {
  }
 
}
