// Variables for Datepicker DivId and Iframe Id
var datePickerDivID = "datepicker";
var iFrameDivID = "datepickeriframe";

var dayArrayShort = new Array('S', 'M', 'T', 'W', 'T', 'F', 'S');
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.
var defaultDateSeparator = "/";        // common values would be "/" or "."
var defaultDateFormat = "mdy"    // valid values are "mdy", "dmy", and "ymd"
var defaultDateSelRng = "n"; // valid values are "n" : normal, "f" : allow only future dates, "p" : allow only past dates.
var dateSeparator = defaultDateSeparator;
var dateFormat = defaultDateFormat;
var dateSelOptionRng = defaultDateSelRng;
var dateeventsrcElement;
// Variables that stores the current date from the local machine system time.
var now = new Date();
var CDay = now.getDate();
var CMonth = now.getMonth()+1;
var CYear = now.getFullYear();
var dCurrentDate = CMonth + dateSeparator + CDay + dateSeparator + CYear
// Fucntion to display the datepicker
function displayDatePicker(dateFieldName, dtSelRng, displayBelowThisObject, dtFormat, dtSep)
{
  if(document.getElementById(datePickerDivID)!= null && document.getElementById(iFrameDivID)!= null)
  {
    var pickerDiv = document.getElementById(datePickerDivID);
    var iFrameDiv = document.getElementById(iFrameDivID);
    pickerDiv.style.visibility = "hidden";
    pickerDiv.style.display = "none";
    iFrameDiv.style.visibility = "hidden";
    iFrameDiv.style.display = "none";
  }
  
  var targetDateField = document.getElementsByName(dateFieldName).item(0);
 
  // 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;
 
  // if a date Seletable range was given, update the dateSelOption variable
  if (dtSelRng)
    dateSelOptionRng = dtSelRng;
  else
    dateSelOptionRng = defaultDateSelRng;
 
  var x = displayBelowThisObject.offsetLeft;
  var y = displayBelowThisObject.offsetTop + displayBelowThisObject.offsetHeight ;
 
  // deal with elements inside tables and such
  var parent = displayBelowThisObject;
  while (parent.offsetParent) {
    parent = parent.offsetParent;
    x += parent.offsetLeft;
    y += parent.offsetTop ;
  }
 
  drawDatePicker(targetDateField, x, y);
}


/**
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)
{
  //var dt = getFieldDate(targetDateField.value );
 var dt = new Date();
  // 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 = document.createElement("div");
    newNode.setAttribute("id", datePickerDivID);
    newNode.setAttribute("class", "dpDiv");
    newNode.setAttribute("style", "visibility: hidden;");
    document.body.appendChild(newNode);
  }
 
  // move the datepicker div to the proper x,y coordinate and toggle the visiblity
  var pickerDiv = document.getElementById(datePickerDivID);
  pickerDiv.style.position = "absolute";
  pickerDiv.style.left = x -30 + "px";
  pickerDiv.style.top = y+2 + "px";
  pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
  pickerDiv.style.display = (pickerDiv.style.display == "block" ? "none" : "block");
  pickerDiv.style.zIndex = 999;
 
  // draw the datepicker table
  refreshDatePicker(targetDateField.name, dt.getFullYear(), dt.getMonth(), dt.getDate());
}


/**
This is the function that actually draws the datepicker calendar.
*/
function refreshDatePicker(dateFieldName, year, month, day)
{
  // 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 HTML = "<HTML><BODY>";
  var xHTML = "</BODY></HTML>";
  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_todayLink = "<tr class='dpTodayLinkTR'>";
  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_todayButton = "<td class='dpTodayButtonTd' onMouseOut='this.className=\"dpTodayButtonTd\";' onMouseOver=' this.className=\"dpTDHover\";' ";    // leave this tag open, because we'll be adding an onClick event
  var TD_LineThr = "<td class='dpTD dpLineThrough'>";
  var TD_title = "<td colspan=5 class='dpTitleTD'>";
  var TD_buttons = "<td class='dpButtonTD'>";
  var TD_todayLink = "<td colspan=7 class='dpTodayLinkTD'>";
  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;
  html = HTML;
  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;","prev.gif") + xTD;
  html += TD_title + DIV_title + monthArrayLong[ thisDay.getMonth()] + " " + thisDay.getFullYear() + xDIV + xTD;
  html += TD_buttons + getButtonCode(dateFieldName, thisDay, 1, "&gt;","next.gif") + 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 += TD_days + dayArrayShort[i] + xTD;
  html += xTR;
  // now we'll start populating the table with days of the month
  html += TR;
  // first, the previous month dates.
  var PrevMonthLastDay = new Date((new Date(year, month,1))-1).getDate();
  var PrevMonth = month;
  var NextMonth = month+1;
  for (i = 0; i < thisDay.getDay(); i++)
  {
		dCurMon = thisDay.getMonth();
		var sMonth, SelDate;
		if(PrevMonth == 0)
		{
		    sMonth = 12;
		}
		else
		{
		    sMonth = PrevMonth;
		}
		var dtCurVal = (parseInt(PrevMonthLastDay) - ((thisDay.getDay()-1) - i));
		
		var dayString = "00" + dtCurVal;
        var monthString = "00" + sMonth;
        dayString = dayString.substring(dayString.length - 2);
        monthString = monthString.substring(monthString.length - 2);
        
        switch (dateFormat) 
        {
            case "dmy" :
            SelDate =  dayString + dateSeparator + monthString + dateSeparator + year;
            case "ymd" :
            SelDate = year + dateSeparator + monthString + dateSeparator + dayString;
            case "mdy" :
            default :
            SelDate = monthString + dateSeparator + dayString + dateSeparator + year;
        }
        
		TD_onSel = " onclick=\"updateDateField('" + dateFieldName + "', '" + SelDate + "');\">";
		
		if(dateSelOptionRng == "n")
		{
			if(CYear == year && CMonth == PrevMonth && dtCurVal == CDay)
			{
			    html += TD_todayButton + TD_onclick + dtCurVal + xTD;
			}
			else
			{
			    html += TD + TD_onSel + dtCurVal + xTD;    
			}
		}
		else if((dateSelOptionRng.toLowerCase() == "f") || (dateSelOptionRng.toLowerCase() == "p"))
		{
			if(dateSelOptionRng.toLowerCase() == "f")
			{
				if(CYear == year && PrevMonth == 0)
				{
				    html += TD_LineThr + dtCurVal + xTD;
				}
				else if(CYear < year && PrevMonth == 0)
				{
				    html += TD + TD_onSel + dtCurVal + xTD;
				}
				else if(year > CYear)
				{
					html += TD + TD_onSel + dtCurVal + xTD;
				}
				else if(CYear > year)
				{
				    html += TD_LineThr + dtCurVal + xTD;
				}
				else if(CMonth > PrevMonth && year == CYear)
                {
                    html += TD_LineThr + dtCurVal + xTD;
                }
                else if(CYear == year && CMonth == PrevMonth)
                {
                    if(dtCurVal == CDay)
                    {
                        html += TD_todayButton + TD_onSel + dtCurVal + xTD;
                    }
                    else if(dtCurVal > CDay)
                    {
                        html += TD + TD_onSel + dtCurVal + xTD;
                    }
                    else if(dtCurVal < CDay)
                    {
                        html += TD_LineThr + dtCurVal + xTD;
                    }
                }
                else
                {
					html += TD + TD_onSel + dtCurVal + xTD;
                }
			}
			if(dateSelOptionRng.toLowerCase() == "p")
			{
			    if(CYear == year && PrevMonth == 0)
			    {
			        html += TD + TD_onSel + dtCurVal + xTD;
			    }
			    else if(CYear < year && PrevMonth == 0)
			    {
			        html += TD_LineThr + dtCurVal + xTD;
			    }
			    else if(year > CYear)
			    {
			        html += TD_LineThr + dtCurVal + xTD;
			    }
			    else if(CYear > year)
			    {
			        html += TD + TD_onSel + dtCurVal + xTD;
			    }
				else if(CMonth > PrevMonth && year == CYear)
                {
                    html += TD + TD_onSel + dtCurVal + xTD;
                }
                else if(CYear == year && CMonth == PrevMonth)
                {
                    if(dtCurVal == CDay)
                    {
                        html += TD_todayButton + TD_onSel + dtCurVal + xTD;
                    }
                    else if(dtCurVal > CDay)
                    {
                        html += TD_LineThr + dtCurVal + xTD;
                    }
                    else if(dtCurVal < CDay)
                    {
                        html += TD + TD_onSel + dtCurVal + xTD;
                    }
                }
                else
                {
					html += TD_LineThr + dtCurVal + xTD;
                }
			}
		}
  }
  // now, the days of the month
  do {
    dayNum = thisDay.getDate();
    dCurMon = thisDay.getMonth()+1;
    TD_onclick = " onclick=\"updateDateField('" + dateFieldName + "', '" + getDateString(thisDay) + "');\">";
    var CCdate = new Date();
    CCday = CCdate.getDate();
    if(dateSelOptionRng == "n")
    {
        if(CYear == year && CMonth == dCurMon && dayNum == CCday)
        {
            html += TD_todayButton + TD_onclick + dayNum + xTD;
        }
        else
        {
            html += TD + TD_onclick + dayNum + xTD;    
        }
    }
    else if((dateSelOptionRng.toLowerCase() == "f") || (dateSelOptionRng.toLowerCase() == "p"))
    {
        if(dateSelOptionRng.toLowerCase() == "f")
        {
              if(day != undefined)
              {
                    if(CYear > year)
                    {
                        html += TD_LineThr + dayNum + xTD;
                    }
                    else if(CMonth > dCurMon)
                    {
                        html += TD_LineThr + dayNum + xTD;
                    }
                    else if(dayNum < day)
                    {
                        html += TD_LineThr + dayNum + xTD;    
                    }
                    else if(dayNum > day)
                    {
                        html += TD + TD_onclick + dayNum + xTD;
                    }
                    else if(dayNum == day)
                    {
                        html += TD_todayButton + TD_onclick + dayNum + xTD;
                    }
              }
              else if(day == undefined)
              {
                    if(year < CYear)
                    {
                        html += TD_LineThr + dayNum + xTD;
                    }
                    if(year > CYear)
                    {
                        html += TD + TD_onclick + dayNum + xTD;
                    }
                    if(year == CYear)
                    {
                        if(dCurMon < CMonth)
                        {
                            html += TD_LineThr + dayNum + xTD;
                        }
                        else if(dCurMon > CMonth)
                        {
                            html += TD + TD_onclick + dayNum + xTD;
                        }
                        else if(dCurMon == CMonth)
                        {
                            if(dayNum == CCday)
                            {
                                html += TD_todayButton + TD_onclick + dayNum + xTD;
                            }
                            else if(dayNum < CCday)
                            {
                                html += TD_LineThr + dayNum + xTD;
                            }
                            else if(dayNum > CCday)
                            {
                                html += TD + TD_onclick + dayNum + xTD;
                            }
                        }
                    }
              }
        }
        if(dateSelOptionRng.toLowerCase() == "p")
        {
            if(day != undefined)
            {
                if(CYear > year)
                {
                    html += TD + TD_onclick + dayNum + xTD;
                }
                else if(CMonth > dCurMon)
                {
                    html += TD + TD_onclick + dayNum + xTD;
                }
                else if(dayNum < day)
                {
                    html += TD + TD_onclick + dayNum + xTD;
                }
                else if(dayNum > day)
                {
                    html += TD_LineThr + dayNum + xTD;
                }
                else if(dayNum == day)
                {
                    html += TD_todayButton + TD_onclick + dayNum + xTD;
                }
            }
            else if(day == undefined)
            {
                var CCdate = new Date();
                CCday = CCdate.getDate();
                if(year < CYear)
                {
                    html += TD + TD_onclick + dayNum + xTD;
                }
                if(year > CYear)
                {
                    html += TD_LineThr + dayNum + xTD;
                }
                if(year == CYear)
                {
                    if(dCurMon < CMonth)
                    {
                        html += TD + TD_onclick + dayNum + xTD;
                    }
                    else if(dCurMon > CMonth)
                    {
                        html += TD_LineThr + dayNum + xTD;
                    }
                    else if(dCurMon == CMonth)
                    {
                        if(dayNum == CCday)
                        {
                            html += TD_todayButton + TD_onclick + dayNum + xTD;
                        }
                        else if(dayNum < CCday)
                        {
                            html += TD + TD_onclick + dayNum + xTD;
                        }
                        else if(dayNum > CCday)
                        {
                            html += TD_LineThr + 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 next month values
  var DateArr = new Array("1", "2", "3", "4", "5", "6", "7");
  NextMonth = NextMonth+1;
  if(NextMonth > 12)
  {
     NextMonth = 1;
  }
  if (thisDay.getDay() > 0) 
  {
    var rlen = 7 - thisDay.getDay();
    for(var i = 0; i < rlen;i++)
    {
	  var dtCurVal;
      var sMonth, SelDate;
      sMonth = NextMonth;
	  dtCurVal = DateArr[i];
	  
	  var dayString = "00" + dtCurVal;
      var monthString = "00" + sMonth;
      dayString = dayString.substring(dayString.length - 2);
      monthString = monthString.substring(monthString.length - 2);
      switch (dateFormat) 
      {
            case "dmy" :
            SelDate =  dayString + dateSeparator + monthString + dateSeparator + year;
            case "ymd" :
            SelDate = year + dateSeparator + monthString + dateSeparator + dayString;
            case "mdy" :
            default :
            SelDate = monthString + dateSeparator + dayString + dateSeparator + year;
      }
      
	  TD_onSel = " onclick=\"updateDateField('" + dateFieldName + "', '" + SelDate + "');\">";
	  
	  if(dateSelOptionRng.toLowerCase() == "n")
	  {
			if(CYear == year && CMonth == NextMonth && dtCurVal == CDay)  
			{
			    html += TD_todayButton + TD_onSel + dtCurVal + xTD;
			}
			else
			{
			    html += TD + TD_onSel + dtCurVal + xTD;
			}
      }
      else if((dateSelOptionRng.toLowerCase() == "f") || (dateSelOptionRng.toLowerCase() == "p"))
      {
            if(dateSelOptionRng.toLowerCase() == "f")
            {
                if(CYear == year && NextMonth == 1)
                {
                    html += TD + TD_onSel + dtCurVal + xTD;
                }
                else if(CYear < year && NextMonth == 1)
                {
                    html += TD + TD_onSel + dtCurVal + xTD;
                }
                else if(CYear > year)
                {
                    html += TD_LineThr + dtCurVal + xTD;
                }
                else if(CYear < year)
                {
                    html += TD + TD_onSel + dtCurVal + xTD;
                }
                else if(CYear == year && CMonth == NextMonth)
                {
                    if(dtCurVal == CDay)
                    {
                        html += TD_todayButton + TD_onSel + dtCurVal + xTD;
                    }
                    else if(dtCurVal > CDay)
                    {
                        html += TD + TD_onSel + dtCurVal + xTD;
                    }
                    else if(dtCurVal < CDay)
                    {
                        html += TD_LineThr + dtCurVal + xTD;
                    }
                }
                else if(CYear == year && CMonth > NextMonth)
                {
                    html += TD_LineThr + dtCurVal + xTD;
                }
                else
                {
                    html += TD + TD_onSel + dtCurVal + xTD;
                }
            }
            if(dateSelOptionRng.toLowerCase() == "p")
            {
                if(CYear == year && NextMonth == 1)
                {
                    html += TD_LineThr + dtCurVal + xTD;
                }
                else if(CYear < year && NextMonth == 1)
                {
                    html += TD_LineThr + dtCurVal + xTD;
                }
                else if(CYear > year)
                {
                    html += TD + TD_onSel + dtCurVal + xTD;
                }
                else if(CYear < year)
                {
                    html += TD_LineThr + dtCurVal + xTD;
                }
                else if(CYear == year && CMonth == NextMonth)
                {
                    if(dtCurVal == CDay)
                    {
                        html += TD_todayButton + TD_onSel + dtCurVal + xTD;
                    }
                    else if(dtCurVal > CDay)
                    {
                        html += TD_LineThr + dtCurVal + xTD;    
                    }
                    else if(dtCurVal < CDay)
                    {
                        html += TD + TD_onSel + dtCurVal + xTD;
                    }
                }
                else if(CYear == year && CMonth > NextMonth)
                {
                    html += TD + TD_onSel + dtCurVal + xTD;
                }
                else
                {
                    html += TD_LineThr + dtCurVal + 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:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; " + dayArrayMed[today.getDay()] + ", " + monthArrayMed[ today.getMonth()] + " " + today.getDate();
  var todayString = "Today:&nbsp;&nbsp;&nbsp;"+monthArrayMed[ today.getMonth()] + "&nbsp;&nbsp;"+today.getDate() +",&nbsp;&nbsp;" + today.getFullYear();
  //html += TR_todayLink + TD_todaybutton + "&nbsp;&nbsp;" + xTD + xTR;
  html += TR_todayLink + TD_todayLink;
  html += "<span class='dpTodayLink' onMouseOver='this.className=\"dpTodayLinkMouseOver\";' onMouseOut='this.className=\"dpTodayLinkMouseOut\";' onClick='updateDateField(\"" + dateFieldName + "\",\"" + dCurrentDate + "\");'>"+todayString+"</span>";
  html += xTD + xTR;
  // and finally, close the table
  html += xTABLE;
  html += xHTML;
 
  document.getElementById(datePickerDivID).innerHTML = html;
  // add an "iFrame shim" to allow the datepicker to display above selection lists
  adjustiFrame();
  document.getElementById(datePickerDivID).onclick = DisableEvent;
}
// function to disable click event inside the Div
function DisableEvent(evt)
{
	var evt  = (evt) ? evt : ((event) ? event : null); 
    evt.cancelBubble = true;
}
// function to check whether the datepicker is visible.
function IsDatePickerVisible(evt)
{
  if(document.getElementById(datePickerDivID)!= null && document.getElementById(iFrameDivID)!= null)
  {
    var pickerDiv = document.getElementById(datePickerDivID);
    var iFrameDiv = document.getElementById(iFrameDivID);
    var isVisible, isdisplay
    if(pickerDiv.style.visibility == "visible")
    {
        isVisible = true;
    }
    else
    {
        isVisible = false;
    }
    if(pickerDiv.style.display == "block")
    {
        isdisplay = true;
    }
    else
    {
        isdisplay = false;
    }
    var evt  = (evt) ? evt : ((event) ? event : null); 
	var srcEl = (typeof evt.target != 'undefined') ? evt.target : evt.srcElement;
    if(isVisible && isdisplay && (srcEl.id != dateeventsrcElement))
    {
        return true;
    }
    else
    {
        return false;
    }
  }
}
// function to hide the date picker control.
function hidedatePicker()
{
  if(document.getElementById(datePickerDivID)!= null && document.getElementById(iFrameDivID)!= null)
  {
    var pickerDiv = document.getElementById(datePickerDivID);
    var iFrameDiv = document.getElementById(iFrameDivID);
    pickerDiv.style.visibility = "hidden";
    pickerDiv.style.display = "none";
    iFrameDiv.style.visibility = "hidden";
    iFrameDiv.style.display = "none";
  }
}
// function to display the datepicker or hide the datepicker.
function toggleDatePickerDisplay(objctrl, displaytype, srcElement,evt)
{
     dateeventsrcElement = srcElement;
     if(IsDatePickerVisible(evt))
     {
        hidedatePicker();
     }
     else
     {
        displayDatePicker(objctrl, displaytype);
     }
}
function hideCalendar(evt)
{
    var evt  = (evt) ? evt : ((event) ? event : null); 
	var srcEl = (typeof evt.target != 'undefined') ? evt.target : evt.srcElement;
    //alert(srcEl);
    if(srcEl.id != dateeventsrcElement)
    {
        hidedatePicker();
    }
}

/**
Convenience function for writing the code for the buttons that bring us back or forward
a month.
*/
function getButtonCode(dateFieldName, dateVal, adjust, label,sSrc)
{
  var newMonth = (dateVal.getMonth () + adjust) % 12;
  var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
  if (newMonth < 0) {
    newMonth += 12;
    newYear += -1;
  }
  var sImgBtnVal = "";
  if(sSrc == "prev.gif")
  {
    sImgBtnVal = "<div class='dpButtonPrev' onClick='refreshDatePicker(\"" + dateFieldName + "\", " + newYear + ", " + newMonth + ");'><<</div>"
  }
  else
  {
    sImgBtnVal = "<div class='dpButtonPrev' onClick='refreshDatePicker(\"" + dateFieldName + "\", " + newYear + ", " + newMonth + ");'>>></div>"
  }
  return sImgBtnVal;
}


/**
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);
 
  switch (dateFormat) {
    case "dmy" :
      return dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();
    case "ymd" :
      return dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;
    case "mdy" :
    default :
      return monthString + dateSeparator + dayString + dateSeparator + dateVal.getFullYear();
  }
}


/**
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);
    } 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;
}

function updateDateField(dateFieldName, dateString)
{
  var targetDateField = document.getElementsByName (dateFieldName).item(0);
  if (dateString)
  {
    if(CheckDateSelRng(dateString))
    {
        targetDateField.value = dateString;
		 targetDateField.focus();
    }
	else
	{
		targetDateField.value = '';
	}
  }
 
  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);
}
function CheckDateSelRng(dateString)
{
	var SDate = dateString;
	if(dateSelOptionRng == "n")
	{
	    return true;
	}
	else if(dateSelOptionRng.toLowerCase() == "f")
	{
	    if(Date.parse(SDate) < Date.parse(dCurrentDate))
	    {
	        alert('The selected date should be greater than or equal to current date.');
		    return false;
	    }
	    else
	    {
	        return true;
	    }
	}
	else if(dateSelOptionRng.toLowerCase() == "p")
	{
	    if(Date.parse(SDate) > Date.parse(dCurrentDate))
	    {
	        alert('The selected date should be less than or equal to current date.');
		    return false;
	    }
	    else
	    {
	        return true;
	    }
	}
}

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", "");
      newNode.setAttribute("scrolling", "no");
      newNode.setAttribute ("frameborder", "0");
      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.clientWidth +'px';
      iFrameDiv.style.height = pickerDiv.clientHeight+'px';
      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) {
  }
 
}

function changedateformat(dtDate)
{
	var dtBeforeChange = dtDate.split('/');
	
	var dtAfterChange = dtBeforeChange[2]+'-'+ dtBeforeChange[0]+'-'+dtBeforeChange[1];  
	return dtAfterChange;
}
function DateDiff(dtObj1,dtObj2)
{
 
	//Getting Start date value from the control   
	var dtStDate =new Date (dtObj1.value);
	//Getting End date value from the control
	var dtEndDate = new Date (dtObj2.value);
	var one_day=1000*60*60*24;  
	var total=-1;
	if(dtObj1.value !="" &&  dtObj2.value !="")  
	{
		if(new Date (dtObj1.value) < new Date (dtObj2.value))
		{
			total= Math.ceil((dtEndDate.getTime()-dtStDate.getTime())/(one_day)) 
		}
		else
		{
			
			dtObj2.value='';	
			total=0;
		}
	}
	return total;
}

function checkValidDate(dateStr) {
    // dateStr must be of format month day year with either slashes
    // or dashes separating the parts. Some minor changes would have
    // to be made to use day month year or another format.
    // This function returns True if the date is valid.
    var slash1 = dateStr.indexOf("/");
    if (slash1 == -1) { slash1 = dateStr.indexOf("-"); }
    if (slash1 == -1) { slash1 = dateStr.indexOf("."); }
    // if no slashes or dashes or dots, invalid date
    if (slash1 == -1) { 
    alert('Please enter a date in the format MM/DD/YYYY');
    return false; }
    var dateMonth = dateStr.substring(0, slash1)
    var dateMonthAndYear = dateStr.substring(slash1+1, dateStr.length);
    var slash2 = dateMonthAndYear.indexOf("/");
    if (slash2 == -1) { slash2 = dateMonthAndYear.indexOf("-"); }
    if (slash2 == -1) { slash2 = dateMonthAndYear.indexOf("."); }
    // if not a second slash or dash or dot, invalid date
    if (slash2 == -1) { 
    alert('Please enter a date in the format MM/DD/YYYY');
	return false; }
	var dateDay = dateMonthAndYear.substring(0, slash2);
    var dateYear = dateMonthAndYear.substring(slash2+1, dateMonthAndYear.length);
    if ( (dateMonth == "") || (dateDay == "") || (dateYear == "") ) 
    {alert('Please enter a date in the format MM/DD/YYYY'); return false; }
    // if any non-digits in the month, invalid date
    for (var x=0; x < dateMonth.length; x++) {
        var digit = dateMonth.substring(x, x+1);
        if ((digit < "0") || (digit > "9")) {
    	alert('Please enter a valid month.');
		return false; }
    }
   
    // convert the text month to a number
    var numMonth = 0;
    for (var x=0; x < dateMonth.length; x++) {
        digit = dateMonth.substring(x, x+1);
        numMonth *= 10;
        numMonth += parseInt(digit);
    }
    if ((numMonth <= 0) || (numMonth > 12)) { 
    alert('Please enter a valid month.');
	return false; }
    // if any non-digits in the day, invalid date
    for (var x=0; x < dateDay.length; x++) {
        digit = dateDay.substring(x, x+1);
        if ((digit < "0") || (digit > "9")) { alert('Please enter a valid day.'); 
        return false; }
    }
    // convert the text day to a number
    var numDay = 0;
    for (var x=0; x < dateDay.length; x++) {
        digit = dateDay.substring(x, x+1);
        numDay *= 10;
        numDay += parseInt(digit);
    }
    if ((numDay <= 0) || (numDay > 31)) { 
    alert('Please enter a valid day.');
	return false; }
    // February can't be greater than 29 (leap year calculation comes later)
    if ((numMonth == 2) && (numDay > 29)) { 
    alert('Please enter a valid day.');
	return false; }
    // check for months with only 30 days
    if ((numMonth == 4) || (numMonth == 6) || (numMonth == 9) || (numMonth == 11)) { 
        if (numDay > 30) { 
	    alert('Please enter a valid day.');
		return false; }
    }
    // if any non-digits in the year, invalid date
    for (var x=0; x < dateYear.length; x++) {
        digit = dateYear.substring(x, x+1);
        if ((digit < "0") || (digit > "9")) { 
	    alert('Please enter a valid year.');
		return false; }
    }
    // convert the text year to a number
    var numYear = 0;
    for (var x=0; x < dateYear.length; x++) {
        digit = dateYear.substring(x, x+1);
        numYear *= 10;
        numYear += parseInt(digit);
    }
    // Year must be a 4-digit year
    //NOTE: Original Code supprted 2 and 4 digit years.
    //	Since this led to errors in Specialist Eligibility searches,
    //	only 4 digit dates are supported by appending the following line.
//  if ( (dateYear.length != 2) && (dateYear.length != 4) ) {
    if ( (dateYear.length != 4) ) {  
    alert('Please enter a valid year in the format YYYY.');
	return false; }
    // if 2-digit year, use 50 as a pivot date
    //NOTE: Original Code supprted 2 and 4 digit years.
    //	Since this led to errors in Specialist Eligibility searches,
    //	only 4 digit dates are supported now. Hence following lines were commented.
//  if ( (numYear < 50) && (dateYear.length == 2) ) { numYear += 2000; }
//  if ( (numYear < 100) && (dateYear.length == 2) ) { numYear += 1900; }
    if ((numYear <= 1752) || (numYear > 9999)) { 
    alert('Please enter a valid year.');
	return false; }
    // check for leap year if the month and day is Feb 29
    if ((numMonth == 2) && (numDay == 29)) {
        var div4 = numYear % 4;
        var div100 = numYear % 100;
        var div400 = numYear % 400;
        // if not divisible by 4, then not a leap year so Feb 29 is invalid
        if (div4 != 0) { 
	    alert('Not a leap year! February has 28 days.');
		return false; }
        // at this point, year is divisible by 4. So if year is divisible by
        // 100 and not 400, then it's not a leap year so Feb 29 is invalid
        if ((div100 == 0) && (div400 != 0)) {
	    alert('Not a leap year! February has 28 days.');
		return false; }
    }
    // date is valid
    return true;
}
