//
// JavaScript Calendar Component
// Author: Robert W. Husted  (robert.husted@iname.com)
// Date:   8/22/1999
// Modified Date: 11/30/1999
// Modified By:   Robert W. Husted
// Notes:  Added frameset support (changed reference for "calWin" to "self.calWin")
//         Also changed Spanish "March" from "Marcha" to "Marzo"
//         Fixed JavaScript Date Anomaly affecting days > 28
//
// http://developer.iplanet.com/viewsource/husted_calendar/husted_calendar.html
//
// Usage:  Add the following lines of code to your page to enable the Calendar component.
//
//
//         // THIS LINE LOADS THE JS LIBRARY FOR THE CALENDAR COMPONENT
//         <SCRIPT LANGUAGE="JavaScript" SRC="calendar.js"></SCRIPT>
//
//
//         // THIS LINE IS USED IN CONJUNCTION WITH A FORM FIELD (txtMyDate) IN A FORM (myForm).
//         // Replace "myForm" and "txtMyDate" WITH THE NAME OF YOUR FORM AND INPUT FIELD RESPECTIVELY
//         // WINDOW OPTIONS SET THE WIDTH, HEIGHT, AND X/Y POSITION OF THE CALENDAR WINDOW
//         // WITH TITLEBAR ON, ALL OTHER OPTIONS (TOOLBARS, ETC) ARE DISABLED BY DEFAULT
//
//
//     <INPUT type='text' class='text' name='txtMyDate' value='' size='10' maxlength='10' title='Enter Date in this format: MM/DD/YYYY' label='My Date'>
//     <A HREF="Calendar" onClick='showCalendar(document.myForm.txtMyDate);return(false);'>
//     <IMG SRC='calendar.gif' vspace='0' align='top' BORDER='0' alt='Calendar'></A></nobr>
//
//
//
//
// Required Files:
//
//         calendar.js   - contains all JavaScript functions to make the calendar work
//
//
// Files Generally Included:
//
//         calendar.html - frameset document (not required if you call the showCalendar()
//                         function, which is recommended.  However, calling showCalendar()
//                         directly causes the Java Virtual Machine (JVM) to start which
//                         slows down the loading of the calendar.)
//
//         calendar.gif  - image that looks like a little calendar
//
//


// BEGIN USER-EDITABLE SECTION -----------------------------------------------------


// SPECIFY DATE FORMAT RETURNED BY THIS CALENDAR
// (THIS IS ALSO THE DATE FORMAT RECOGNIZED BY THIS CALENDAR)

// DATE FORMAT OPTIONS:
//
// dd   = 1 or 2-digit Day
// DD   = 2-digit Day
// mm   = 1 or 2-digit Month
// MM   = 2-digit Month
// yy   = 2-digit Year
// YY   = 4-digit Year
// yyyy = 4-digit Year
// month   = Month name in lowercase letters
// Month   = Month name in initial caps
// MONTH   = Month name in captital letters
// mon     = 3-letter month abbreviation in lowercase letters
// Mon     = 3-letter month abbreviation in initial caps
// MON     = 3-letter month abbreviation in uppercase letters
// weekday = name of week in lowercase letters
// Weekday = name of week in initial caps
// WEEKDAY = name of week in uppercase letters
// wkdy    = 3-letter weekday abbreviation in lowercase letters
// Wkdy    = 3-letter weekday abbreviation in initial caps
// WKDY    = 3-letter weekday abbreviation in uppercase letters
//
// Examples:
//
// calDateFormat = "mm/dd/yy";
// calDateFormat = "Weekday, Month dd, yyyy";
// calDateFormat = "wkdy, mon dd, yyyy";
// calDateFormat = "DD.MM.YY";     // FORMAT UNSUPPORTED BY JAVASCRIPT -- REQUIRES CUSTOM PARSING
//

var UNDEFINED;   // do not assign!

calDateFormat    = "DD-MM-YYYY";


// CALENDAR COLORS
topBackground    = "#e5e5e5";      // BG COLOR OF THE TOP FRAME
bottomBackground = "#e5e5e5";       // BG COLOR OF THE BOTTOM FRAME
tableBGColor     = "black";         // BG COLOR OF THE BOTTOM FRAME'S TABLE
cellColor        = "#e5e5e5";       // TABLE CELL BG COLOR OF THE DATE CELLS IN THE BOTTOM FRAME
headingCellColor = "#bec3c6";       // TABLE CELL BG COLOR OF THE WEEKDAY ABBREVIATIONS
headingTextColor = "#555555";         // TEXT COLOR OF THE WEEKDAY ABBREVIATIONS
dateColor        = "#555555";          // TEXT COLOR OF THE LISTED DATES (1-28+)
focusColor       = "black";       // TEXT COLOR OF THE SELECTED DATE (OR CURRENT DATE)
hoverColor       = "#555555";           // TEXT COLOR OF A LINK WHEN YOU HOVER OVER IT
hoverBgColor     = "#bec3c6";       // BACKGROUND COLOR OF A LINK WHEN YOU HOVER OVER IT
fontStyle        = "11px Verdana, arial, helvetica";           // TEXT STYLE FOR DATES
headingFontStyle = "bold 11px Verdana, arial, helvetica";      // TEXT STYLE FOR WEEKDAY ABBREVIATIONS

// FORMATTING PREFERENCES
bottomBorder  = false;        // TRUE/FALSE (WHETHER TO DISPLAY BOTTOM CALENDAR BORDER)
tableBorder   = 0;            // SIZE OF CALENDAR TABLE BORDER (BOTTOM FRAME) 0=none
var winTitle  = "Choose a Date";



// END USER-EDITABLE SECTION -------------------------------------------------------



// DETERMINE BROWSER BRAND

var isNav = (navigator.appName=="Netscape");
var isIE  = !isNav;

// GET CURRENTLY SELECTED LANGUAGE
selectedLanguage = navigator.language;

// PRE-BUILD PORTIONS OF THE CALENDAR WHEN THIS JS LIBRARY LOADS INTO THE BROWSER
buildCalParts();


// CALENDAR FUNCTIONS BEGIN HERE ---------------------------------------------------


// SET THE INITIAL VALUE OF THE GLOBAL DATE FIELD
function setDateField(dateField)
{
   // ASSIGN THE INCOMING FIELD OBJECT TO A GLOBAL VARIABLE
   calDateField = dateField;

   // GET THE VALUE OF THE INCOMING FIELD
   inDate = dateField.value;

   // rbrown added
   if ( dateField.value=="" && dateField.caldate!=UNDEFINED )
        inDate = dateField.caldate;

   // SET calDate TO THE DATE IN THE INCOMING FIELD OR DEFAULT TO TODAY'S DATE
   setInitialDate(inDate);

   // THE CALENDAR FRAMESET DOCUMENTS ARE CREATED BY JAVASCRIPT FUNCTIONS
   calDocTop    = buildTopCalFrame();
   calDocBottom = buildBottomCalFrame();
//alert(calDocBottom);
}


// SET THE INITIAL CALENDAR DATE TO TODAY OR TO THE EXISTING VALUE IN dateField
function setInitialDate(inDate)
{
   // CREATE A NEW DATE OBJECT (WILL GENERALLY PARSE CORRECT DATE EXCEPT WHEN "." IS USED AS A DELIMITER)
   // (THIS ROUTINE DOES *NOT* CATCH ALL DATE FORMATS, IF YOU NEED TO PARSE A CUSTOM DATE FORMAT, DO IT HERE)
   calDate = new Date(inDate);

   // IF THE INCOMING DATE IS INVALID, USE THE CURRENT DATE
   if (isNaN(calDate))
   {
       // ADD CUSTOM DATE PARSING HERE
       // IF IT FAILS, SIMPLY CREATE A NEW DATE OBJECT WHICH DEFAULTS TO THE CURRENT DATE
       calDate = new Date();
   }

   if ( (y=calDate.getYear()) < 100 )
   {
        calDate.setYear( y<80 ? y+2000 : y+1900 );
   }

   // KEEP TRACK OF THE CURRENT DAY VALUE
   calDay  = calDate.getDate();

   // SET DAY VALUE TO 1... TO AVOID JAVASCRIPT DATE CALCULATION ANOMALIES
   // (IF THE MONTH CHANGES TO FEB AND THE DAY IS 30, THE MONTH WOULD CHANGE TO MARCH
   // AND THE DAY WOULD CHANGE TO 2.  SETTING THE DAY TO 1 WILL PREVENT THAT)
   calDate.setDate(1);
}


// functions to get X and Y coordinates of the date field
function getX(obj)
{
  return( obj.offsetParent==null ? obj.offsetLeft : obj.offsetLeft+getX(obj.offsetParent) );
}


function getY(obj)
{
  return( obj.offsetParent==null ? obj.offsetTop : obj.offsetTop+getY(obj.offsetParent) );
}


// POPUP A WINDOW WITH THE CALENDAR IN IT
// inX and inY are optional parameters.  Use them to set the calendar window's location.
function showCalendar(dateField,inX,inY)
{
  if ( dateField==UNDEFINED || dateField.value==UNDEFINED )
  {
     alert("Invalid or unspecified date field.");
     return(false);
  }

  if ( dateField.label == UNDEFINED  ||  dateField.label.length == 0 )
     winTitle = "Choose a Date";
  else
     winTitle = dateField.label;

  if ( dateField.title == UNDEFINED  ||  dateField.title.length == 0 )
     dateField.title = "MM/DD/YYYY";

  dateField.focus();
  dateField.select();
  setDateField(dateField);

  // This section calculates the position of the calendar in relation to
  // the dateField.  Be careful changing these as Netscape and IE behave
  // differently, and a small adjustment to one could be big to the other.

  var sx = self.screenX ? self.screenX : self.screenLeft;
  var sy = self.screenY ? self.screenY : self.screenTop;
  if (!sx) sx=10;
  if (!sy) sy=10;

  var W=178 + 10*eval(tableBorder);
  var H=212 + 10*eval(tableBorder);
  var defX = dateField.offsetLeft ? getX(dateField)+sx+5 : ((screen.width/2)-(W/2));
  var defY = dateField.offsetTop  ? getY(dateField)+sy+20 : ((screen.height/2)-(H/2));
  var X = (inX==UNDEFINED) ? Math.min(defX,screen.width-W-20) : eval(inX);
  var Y = (inY==UNDEFINED) ? Math.min(defY,screen.height-H-40) : eval(inY);


  var winPrefs = "width=" + W + ",height=" + H
      + ",innerWidth=" + W + ",innerHeight=" + H
      + ",left=" + X + ",top=" + Y
      + ",screenX=" + X + ",screenY=" + Y
      + ",dependent=yes,titlebar=yes";

  // USE THE JAVASCRIPT-GENERATED DOCUMENTS (calDocTop, calDocBottom) IN THE FRAMESET
  calDocFrameset =
       "<HTML><HEAD><TITLE> &nbsp; " + winTitle + " &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </TITLE></HEAD>\n" +
       "<FRAMESET ROWS='60,*' FRAMEBORDER='0' MARGINHEIGHT='0'>\n" +
       "  <FRAME NAME='topCalFrame' SRC='javascript:parent.opener.calDocTop' SCROLLING='no' MARGINHEIGHT='8' FRAMEBORDER='0' BORDER='0' BORDERCOLOR='"+topBackground+"'>\n" +
       "  <FRAME NAME='bottomCalFrame' SRC='javascript:parent.opener.calDocBottom' SCROLLING='no' MARGINHEIGHT='8' FRAMEBORDER='0' BORDER='0' BORDERCOLOR='"+bottomBackground+"'>\n" +
       "</FRAMESET>\n";

//alert(calDocFrameset);
  // DISPLAY THE CALENDAR IN A NEW POPUP WINDOW
  if ( self.calWin && !self.calWin.closed ) self.calWin.close();
  self.calWin = window.open("javascript:parent.opener.calDocFrameset","calWin",winPrefs);
  self.calWin.focus();

  return(false);  // to prevent the href='#' from jumping
}


// CREATE THE TOP CALENDAR FRAME
function buildTopCalFrame()
{
// CREATE THE TOP FRAME OF THE CALENDAR
var calDoc =
    "<HTML>" +
    "<HEAD>" +

"<STYLE type='text/css'>\n<!--" +
"INPUT.calDataButton {"+
"  BACKGROUND-COLOR: #bec3c6;" +
"  BORDER-BOTTOM: #555555 1px solid;" +
"  BORDER-LEFT: #555555 1px solid;" +
"  BORDER-RIGHT: #555555 1px solid;" +
"  BORDER-TOP: #555555 1px solid;" +
"  FONT-FAMILY: Helvetica, Arial, Verdana;" +
"  FONT-SIZE: 11px;"+
"  PADDING-LEFT: 5px" +
"}\n--->\n</STYLE>" +

    "</HEAD>\n" +
    "<BODY BGCOLOR='" + topBackground + "' vlink='" + dateColor + "'>" +
    "<FORM NAME='calControl' onSubmit='return false;'>" +
    "<CENTER>" +
    "<TABLE CELLPADDING=0 CELLSPACING=1 BORDER=0>\n" +
    "<TR><TD COLSPAN=7>\n" +
    "<CENTER>" +
    getMonthSelect() +
    "<INPUT NAME='year' VALUE='" + calDate.getFullYear() + "'TYPE=TEXT SIZE=4 MAXLENGTH=4 onChange='parent.opener.setYear();'>\n" +
    "</CENTER>" +
    "</TD>" +
     "</TR>\n<TR>" +
    "<TD COLSPAN=7><NOBR>\n" +
    "<INPUT TYPE=BUTTON NAME='previousYear'  CLASS='calDataButton' VALUE='<<'     onClick='parent.opener.setPreviousYear()'  onMouseOver='this.focus();' onMouseOut='this.blur();' title='Previous Year'>" +
    "<INPUT TYPE=BUTTON NAME='previousMonth' CLASS='calDataButton' VALUE=' < '    onClick='parent.opener.setPreviousMonth()' onMouseOver='this.focus();' onMouseOut='this.blur();' title='Previous Month'>" +
    "<INPUT TYPE=BUTTON NAME='today'         CLASS='calDataButton' VALUE='";
    switch( selectedLanguage )
    { case "nl": calDoc += 'Vandaag'; break;
      case "en": calDoc += 'Today'; break;
    }
    calDoc += 
    "'  onClick='parent.opener.setToday()'         onMouseOver='this.focus();' onMouseOut='this.blur();' title='Today'>" +
    "<INPUT TYPE=BUTTON NAME='nextMonth'     CLASS='calDataButton' VALUE=' > '    onClick='parent.opener.setNextMonth()'     onMouseOver='this.focus();' onMouseOut='this.blur();' title='Next Month'>" +
    "<INPUT TYPE=BUTTON NAME='nextYear'      CLASS='calDataButton' VALUE='>>'     onClick='parent.opener.setNextYear()'      onMouseOver='this.focus();' onMouseOut='this.blur();' title='Next Year'>" +
    "</NOBR></TD>" +
    "</TR>" +
    "</TABLE>\n" +
    "</CENTER>" +
    "</FORM>" +
    "</BODY>" +
    "</HTML>";

return calDoc;
}


// CREATE THE BOTTOM CALENDAR FRAME
// (THE MONTHLY CALENDAR)
function buildBottomCalFrame()
{
   // START CALENDAR DOCUMENT
   var calDoc = calendarBegin;

   // GET MONTH, AND YEAR FROM GLOBAL CALENDAR DATE
   month   = calDate.getMonth();
   year    = calDate.getFullYear();


   // GET GLOBALLY-TRACKED DAY VALUE (PREVENTS JAVASCRIPT DATE ANOMALIES)
   day     = calDay;
   var i   = 0;

   // DETERMINE THE NUMBER OF DAYS IN THE CURRENT MONTH
   var days = getDaysInMonth();

   // IF GLOBAL DAY VALUE IS > THAN DAYS IN MONTH, HIGHLIGHT LAST DAY IN MONTH
   if (day > days) day = days;

   // DETERMINE WHAT DAY OF THE WEEK THE CALENDAR STARTS ON
   var firstOfMonth = new Date (year, month, 1);

   // GET THE DAY OF THE WEEK THE FIRST DAY OF THE MONTH FALLS ON
   var startingPos  = firstOfMonth.getDay();
   days += startingPos;

   // KEEP TRACK OF THE COLUMNS, START A NEW ROW AFTER EVERY 7 COLUMNS
   var columnCount = 0;

   // MAKE BEGINNING NON-DATE CELLS BLANK
   for (i=0; i<startingPos; i++)
   {
      calDoc += blankCell;
      columnCount++;
   }

   // SET VALUES FOR DAYS OF THE MONTH
   var currentDay = 0;
   var dayType    = "weekday";

   // DATE CELLS CONTAIN A NUMBER
   for (i=startingPos; i<days; i++)
   {
       var paddingChar = "&nbsp;";

       // ADJUST SPACING SO THAT ALL LINKS HAVE RELATIVELY EQUAL WIDTHS
       if (i-startingPos+1 < 10)
       {
           padding = "&nbsp;&nbsp;";
       }
       else
       {
           padding = "&nbsp;";
       }

       // GET THE DAY CURRENTLY BEING WRITTEN
       currentDay = i-startingPos+1;

       // SET THE TYPE OF DAY, THE focusDay GENERALLY APPEARS AS A DIFFERENT COLOR

       dayType = (currentDay==day) ? "focusDay" : "weekDay";

       // ADD THE DAY TO THE CALENDAR STRING
       calDoc += "<TD align='center' bgcolor='" + cellColor + "' class='" + dayType + "'>" +
                 "<a class='" + dayType + "' href='javascript:parent.opener.returnDate(" +
                 currentDay + ")'>" + padding + currentDay + paddingChar + "</a></TD>\n";

       columnCount++;

       // START A NEW ROW WHEN NECESSARY
       if (columnCount%7 == 0) {
           calDoc += "</TR>\n<TR>";
       }
   }

   // MAKE REMAINING NON-DATE CELLS BLANK
   for (i=days; i<42; i++)
   {
       calDoc += blankCell;
       columnCount++;

       // START A NEW ROW WHEN NECESSARY
       if (columnCount%7 == 0)
       {
           calDoc += "</TR>\n";
           if (i<41)
           {
               calDoc += "<TR>";
           }
       }
   }

   // FINISH THE NEW CALENDAR PAGE
   calDoc += calendarEnd;

   // RETURN THE COMPLETED CALENDAR PAGE
   return calDoc;
}


// WRITE THE MONTHLY CALENDAR TO THE BOTTOM CALENDAR FRAME
function writeCalendar()
{
   // CREATE THE NEW CALENDAR FOR THE SELECTED MONTH & YEAR
   calDocBottom = buildBottomCalFrame();


   // WRITE THE NEW CALENDAR TO THE BOTTOM FRAME
   if (document.getElementById)  // for NS6 support
   {
      self.calWin.frames['bottomCalFrame'].document.getElementById('idBody').innerHTML = calDocBottom;
   }
   else
   {
      self.calWin.frames['bottomCalFrame'].document.open();
      self.calWin.frames['bottomCalFrame'].document.writeln(calDocBottom);
      self.calWin.frames['bottomCalFrame'].document.close();
   }
}


// SET THE CALENDAR TO TODAY'S DATE AND DISPLAY THE NEW CALENDAR
function setToday()
{
   // SET GLOBAL DATE TO TODAY'S DATE
   calDate = new Date();

   // SET DAY MONTH AND YEAR TO TODAY'S DATE
   var month = calDate.getMonth();
   var year  = calDate.getFullYear();
   var day   = calDate.getDate();

   // SET MONTH IN DROP-DOWN LIST
   self.calWin.frames['topCalFrame'].document.calControl.month.selectedIndex = month;

   // SET YEAR VALUE
   self.calWin.frames['topCalFrame'].document.calControl.year.value = year;

   // SET DAY
   calDate.setDate(calDay=day);

   // DISPLAY THE NEW CALENDAR
   writeCalendar();
}


// SET THE GLOBAL DATE TO THE NEWLY ENTERED YEAR AND REDRAW THE CALENDAR
function setYear()
{
   // GET THE NEW YEAR VALUE
   var yearfld = self.calWin.frames['topCalFrame'].document.calControl.year;
   var year  = yearfld.value;

   // IF IT'S A FOUR-DIGIT YEAR THEN CHANGE THE CALENDAR
   if (isFourDigitYear(year)) {
       calDate.setFullYear(year);
       writeCalendar();
   }
   else {
       // HIGHLIGHT THE YEAR IF THE YEAR IS NOT FOUR DIGITS IN LENGTH
       yearfld.focus();
       yearfld.select();
       setTimeout("self.calWin.frames['topCalFrame'].document.calControl.year.focus()",1);
   }
}


// SET THE GLOBAL DATE TO THE SELECTED MONTH AND REDRAW THE CALENDAR
function setCurrentMonth()
{
   // GET THE NEWLY SELECTED MONTH AND CHANGE THE CALENDAR ACCORDINGLY
   var month = self.calWin.frames['topCalFrame'].document.calControl.month.selectedIndex;

   calDate.setMonth(month);

   writeCalendar();
}


// SET THE GLOBAL DATE TO THE PREVIOUS YEAR AND REDRAW THE CALENDAR
function setPreviousYear()
{
   var yearfld = self.calWin.frames['topCalFrame'].document.calControl.year;
   var year  = yearfld.value;

   if (isFourDigitYear(year))
   {
       year--;
       calDate.setFullYear(year);
       yearfld.value = year;
       writeCalendar();
   }
}


// SET THE GLOBAL DATE TO THE PREVIOUS MONTH AND REDRAW THE CALENDAR
function setPreviousMonth()
{
   var yearfld = self.calWin.frames['topCalFrame'].document.calControl.year;
   var year  = yearfld.value;

   if (isFourDigitYear(year))
   {
       var month = self.calWin.frames['topCalFrame'].document.calControl.month.selectedIndex;

       // IF MONTH IS JANUARY, SET MONTH TO DECEMBER AND DECREMENT THE YEAR
       if (month == 0)
       {
           month = 11;
           if (year > 1000)
           {
               year--;
               calDate.setFullYear(year);
               yearfld.value = year;
           }
       }
       else
       {
           month--;
       }
       calDate.setMonth(month);
       self.calWin.frames['topCalFrame'].document.calControl.month.selectedIndex = month;
       writeCalendar();
   }
}


// SET THE GLOBAL DATE TO THE NEXT MONTH AND REDRAW THE CALENDAR
function setNextMonth()
{
   var yearfld = self.calWin.frames['topCalFrame'].document.calControl.year;
   var year = yearfld.value;

   if (isFourDigitYear(year))
   {
       var month = self.calWin.frames['topCalFrame'].document.calControl.month.selectedIndex;

       // IF MONTH IS DECEMBER, SET MONTH TO JANUARY AND INCREMENT THE YEAR
       if (month == 11)
       {
           month = 0;
           year++;
           calDate.setFullYear(year);
           yearfld.value = year;
       }
       else
       {
           month++;
       }
       calDate.setMonth(month);
       self.calWin.frames['topCalFrame'].document.calControl.month.selectedIndex = month;
       writeCalendar();
   }
}


// SET THE GLOBAL DATE TO THE NEXT YEAR AND REDRAW THE CALENDAR
function setNextYear()
{
   var yearfld = self.calWin.frames['topCalFrame'].document.calControl.year;
   var year  = yearfld.value;

   if (isFourDigitYear(year))
   {
       year++;
       calDate.setFullYear(year);
       yearfld.value = year;
       writeCalendar();
   }
}


// GET NUMBER OF DAYS IN MONTH
function getDaysInMonth()
{
   var days;
   var month = calDate.getMonth()+1;
   var year  = calDate.getFullYear();

   // RETURN 31 DAYS
   if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)
   {
       days=31;
   }
   // RETURN 30 DAYS
   else if (month==4 || month==6 || month==9 || month==11)
   {
       days=30;
   }
   else if (month==2)  // RETURN 29 DAYS
   {
       if (isLeapYear(year))
       {
           days=29;
       }
       else // RETURN 28 DAYS
       {
           days=28;
       }
   }
   return (days);
}


// CHECK TO SEE IF YEAR IS A LEAP YEAR
function isLeapYear (Year)
{
  return(((Year % 4)==0) && ((Year % 100)!=0) || ((Year % 400)==0));
}


// ENSURE THAT THE YEAR IS FOUR DIGITS IN LENGTH
function isFourDigitYear(year)
{
   var yearfld = self.calWin.frames['topCalFrame'].document.calControl.year;

   //if (year.length==4)
   if ( /^\d{4}$/gi.test(yearfld.value) )
   {
      return(true);
   }
   else
   {
      yearfld.value = calDate.getFullYear();
      yearfld.select();
      yearfld.focus();
   }
}


function fSelected(in1,in2)  // returns " SELECTED " if in1 and in2 are the same
{
 return( (""+in1).toUpperCase()==(""+in2).toUpperCase() ? " SELECTED " : "")
}


// BUILD THE MONTH SELECT LIST
function getMonthSelect()
{
   // BROWSER LANGUAGE CHECK DONE PREVIOUSLY (navigator.language())
   // FIRST TWO CHARACTERS OF LANGUAGE STRING SPECIFIES THE LANGUAGE
   // (THE LAST THREE OPTIONAL CHARACTERS SPECIFY THE LANGUAGE SUBTYPE)
   // SET THE NAMES OF THE MONTH TO THE PROPER LANGUAGE (DEFAULT TO ENGLISH)

   // IF FRENCH
   if (selectedLanguage == "fr")
   {
       monthArray = new Array('Janvier', 'Fèvrier', 'Mars', 'Avril', 'Mai', 'Juin',
                              'Juillet', 'Aout', 'Septembre', 'Octobre', 'Novembre', 'Dècembre');
   }
   // IF GERMAN
   else if (selectedLanguage == "de")
   {
       monthArray = new Array('Januar', 'Februar', 'März', 'April', 'Mai', 'Juni',
                              'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember');
   }
   // IF SPANISH
   else if (selectedLanguage == "es")
   {
       monthArray = new Array('Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio',
                              'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre');
   }
   // IF DUTCH
   else if (selectedLanguage == "nl")
   {
       monthArray = new Array('Januari', 'Februari', 'Maart', 'April', 'Mei', 'Juni',
                              'Juli', 'Augustus', 'September', 'Oktober', 'November', 'December');
   }
   // DEFAULT TO ENGLISH
   else
   {
       monthArray = new Array('January', 'February', 'March', 'April', 'May', 'June',
                              'July', 'August', 'September', 'October', 'November', 'December');
   }

   // DETERMINE MONTH TO SET AS DEFAULT
   var activeMonth = calDate.getMonth();

   // START HTML SELECT LIST ELEMENT
   monthSelect = "<SELECT NAME='month' onChange='parent.opener.setCurrentMonth()'>\n";

   // LOOP THROUGH MONTH ARRAY
   for (i in monthArray)
   {
       // SHOW THE CORRECT MONTH IN THE SELECT LIST (using fSelected)
       monthSelect += "<OPTION" + fSelected(i,activeMonth) + ">" + monthArray[i] + "</OPTION>\n";
   }
   monthSelect += "</SELECT> &nbsp; ";

   // RETURN A STRING VALUE WHICH CONTAINS A SELECT LIST OF ALL 12 MONTHS
   return monthSelect;
}


// SET DAYS OF THE WEEK DEPENDING ON LANGUAGE
function createWeekdayList()
{
   // IF FRENCH
   if (selectedLanguage == "fr")
   {
       weekdayList  = new Array('Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi');
       weekdayArray = new Array('Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa');
   }
   // IF GERMAN
   else if (selectedLanguage == "de")
   {
       weekdayList  = new Array('Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag');
       weekdayArray = new Array('So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa');
   }
   // IF SPANISH
   else if (selectedLanguage == "es")
   {
       weekdayList  = new Array('Domingo', 'Lunes', 'Martes', 'Mi?rcoles', 'Jueves', 'Viernes', 'S?bado')
       weekdayArray = new Array('Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa');
   }
   // IF DUTCH
   else if (selectedLanguage == "nl")
   {
       weekdayList  = new Array('Zondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag')
       weekdayArray = new Array('Zo', 'Ma', 'Di', 'Wo', 'Do', 'Vr', 'Za');
   }
   else
   {
       weekdayList  = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
       weekdayArray = new Array('Su','Mo','Tu','We','Th','Fr','Sa');
   }

   // START HTML TO HOLD WEEKDAY NAMES IN TABLE FORMAT
   var weekdays = "<TR BGCOLOR='" + headingCellColor + "'>\n";

   // LOOP THROUGH WEEKDAY ARRAY
   for (i in weekdayArray)
   {
       weekdays += "<TD class='heading' align=center>" + weekdayArray[i] + "</TD>\n";
   }
   weekdays += "</TR>\n";

   // RETURN TABLE ROW OF WEEKDAY ABBREVIATIONS TO DISPLAY ABOVE THE CALENDAR
   return weekdays;
}


// PRE-BUILD PORTIONS OF THE CALENDAR (FOR PERFORMANCE REASONS)
function buildCalParts()
{
  // GENERATE WEEKDAY HEADERS FOR THE CALENDAR
  weekdays = createWeekdayList();

  // BUILD THE BLANK CELL ROWS
  blankCell = "<TD align=CENTER bgcolor='" + cellColor + "'>&nbsp;&nbsp;&nbsp;</TD>\n";

  // BUILD THE TOP PORTION OF THE CALENDAR PAGE USING CSS TO CONTROL SOME DISPLAY ELEMENTS
  calendarBegin =
    "<HTML>\n<HEAD>\n" +
    // STYLESHEET DEFINES APPEARANCE OF CALENDAR
    "<STYLE type='text/css'>\n" +
    "<!--" +
    "TD               { text-decoration: none; font: " + fontStyle + "; }\n" +
    "TD.heading       { text-decoration: none; color:" + headingTextColor + "; font: " + headingFontStyle + "; }\n" +
    "TD.focusDay      { text-decoration: none; color:" + headingTextColor + "; font:bold " + fontStyle + "; }\n" +
    "A.focusDay:link  { color:" + focusColor + "; text-decoration:none; font:bold " + fontStyle + "; }\n" +
    "A.focusDay:hover { color:" + hoverColor + "; text-decoration:none; font:bold " + fontStyle + "; }\n" +
    "A.focusDay       { color:" + focusColor + "; text-decoration:none; font:bold " + fontStyle + "; }\n" +
    "A.weekDay:link   { color:" + dateColor  + "; text-decoration:none; font:" + fontStyle + "; }\n" +
    "A.weekDay:hover  { color:" + hoverColor + "; background-color:" + hoverBgColor + "; font: " + fontStyle + "; }\n" +
    "A.weekDay        { color:" + dateColor  + "; text-decoration:none; font:" + fontStyle + "; }\n" +
    "-->\n" +
    "</STYLE>\n</HEAD>\n" +
    "<BODY id='idBody' BGCOLOR='" + bottomBackground + "' vlink='" + dateColor + "' >" +
    "<CENTER>\n";

  // NAVIGATOR NEEDS A TABLE CONTAINER TO DISPLAY THE TABLE OUTLINES PROPERLY
  if (isNav)
  {
      calendarBegin +=
        "<TABLE CELLPADDING=0 CELLSPACING=1 BORDER=" + tableBorder + " ALIGN=CENTER BGCOLOR='" + tableBGColor + "'>\n<TR><TD>\n";
  }

  // BUILD WEEKDAY HEADINGS
  calendarBegin +=
     "<TABLE CELLPADDING=0 CELLSPACING=1 BORDER=" + tableBorder + " ALIGN=CENTER BGCOLOR='" + tableBGColor + "'>\n" +
     weekdays +
     "<TR>\n";


  // BUILD THE BOTTOM PORTION OF THE CALENDAR PAGE
  calendarEnd = "\n";

  // WHETHER OR NOT TO DISPLAY A THICK LINE BELOW THE CALENDAR
  if (bottomBorder)
  {
     calendarEnd += "<TR></TR>\n";
  }

  // NAVIGATOR NEEDS A TABLE CONTAINER TO DISPLAY THE BORDERS PROPERLY
  if (isNav)
  {
     calendarEnd += "</TD></TR></TABLE>\n";
  }

  // END THE TABLE AND HTML DOCUMENT
  calendarEnd +=
    "</TABLE>\n" +
    "<a href='javascript:parent.opener.returnDate()'>";
    switch( selectedLanguage )
    { case "nl": calendarEnd += 'Geen'; break;
      case "en": calendarEnd += 'None'; break;
    }
  calendarEnd +=
    "</a>" +
    "</CENTER>\n" +
    "</BODY>\n" +
    "</HTML>\n";
}


// REPLACE ALL INSTANCES OF find WITH replace
// inString: the string you want to convert
// find:     the value to search for
// replace:  the value to substitute
//
// usage:    jsReplace(inString, find, replace);
// example:  jsReplace("To be or not to be", "be", "ski");
//           result: "To ski or not to ski"
//
function jsReplace(inString, sFind, sReplace)
{
   if (!inString) return "";
   return inString.split(sFind).join(sReplace)
}


// ENSURE THAT VALUE IS TWO DIGITS IN LENGTH (adds leading zero)
function makeTwoDigit(inValue)
{
  var numVal = parseInt(inValue, 10);
  return( (numVal<10) ? ("0"+numVal) : numVal );
}


// SET FIELD VALUE TO THE DATE SELECTED AND CLOSE THE CALENDAR WINDOW
function returnDate(inDay)
{
   if( inDay ) {
     // inDay = THE DAY THE USER CLICKED ON
     calDate.setDate(inDay);

     // SET THE DATE RETURNED TO THE USER
     var day           = calDate.getDate();
     var month         = calDate.getMonth()+1;
     var year          = calDate.getFullYear();
     var monthString   = monthArray[calDate.getMonth()];
     var monthAbbrev   = monthString.substring(0,3);
     var weekday       = weekdayList[calDate.getDay()];
     var weekdayAbbrev = weekday.substring(0,3);
  
     outDate = calDateFormat;
  
     // RETURN TWO DIGIT DAY
     if (calDateFormat.indexOf("DD") != -1)
     {
         day = makeTwoDigit(day);
         outDate = jsReplace(outDate, "DD", day);
     }
     // RETURN ONE OR TWO DIGIT DAY
     else if (calDateFormat.indexOf("dd") != -1)
     {
         outDate = jsReplace(outDate, "dd", day);
     }
  
     // RETURN TWO DIGIT MONTH
     if (calDateFormat.indexOf("MM") != -1)
     {
         month = makeTwoDigit(month);
         outDate = jsReplace(outDate, "MM", month);
     }
     // RETURN ONE OR TWO DIGIT MONTH
     else if (calDateFormat.indexOf("mm") != -1)
     {
         outDate = jsReplace(outDate, "mm", month);
     }
  
     // RETURN FOUR-DIGIT YEAR
     if (calDateFormat.indexOf("yyyy") != -1)
     {
         outDate = jsReplace(outDate, "yyyy", year);
     }
     // RETURN FOUR-DIGIT YEAR
     else if (calDateFormat.indexOf("YYYY") != -1)
     {
         outDate = jsReplace(outDate, "YYYY", year);
     }
     // RETURN TWO-DIGIT YEAR
     else if (calDateFormat.indexOf("yy") != -1)
     {
         var yearString = "" + year;
         var yearString = yearString.substring(2,4);
         outDate = jsReplace(outDate, "yy", yearString);
     }
     // RETURN FOUR-DIGIT YEAR
     else if (calDateFormat.indexOf("YY") != -1)
     {
         outDate = jsReplace(outDate, "YY", year);
     }
  
     // RETURN DAY OF MONTH (Initial Caps)
     if (calDateFormat.indexOf("Month") != -1)
     {
         outDate = jsReplace(outDate, "Month", monthString);
     }
     // RETURN DAY OF MONTH (lowercase letters)
     else if (calDateFormat.indexOf("month") != -1)
     {
         outDate = jsReplace(outDate, "month", monthString.toLowerCase());
     }
     // RETURN DAY OF MONTH (UPPERCASE LETTERS)
     else if (calDateFormat.indexOf("MONTH") != -1)
     {
         outDate = jsReplace(outDate, "MONTH", monthString.toUpperCase());
     }
  
     // RETURN DAY OF MONTH 3-DAY ABBREVIATION (Initial Caps)
     if (calDateFormat.indexOf("Mon") != -1)
     {
         outDate = jsReplace(outDate, "Mon", monthAbbrev);
     }
     // RETURN DAY OF MONTH 3-DAY ABBREVIATION (lowercase letters)
     else if (calDateFormat.indexOf("mon") != -1)
     {
         outDate = jsReplace(outDate, "mon", monthAbbrev.toLowerCase());
     }
     // RETURN DAY OF MONTH 3-DAY ABBREVIATION (UPPERCASE LETTERS)
     else if (calDateFormat.indexOf("MON") != -1)
     {
         outDate = jsReplace(outDate, "MON", monthAbbrev.toUpperCase());
     }
  
     // RETURN WEEKDAY (Initial Caps)
     if (calDateFormat.indexOf("Weekday") != -1)
     {
         outDate = jsReplace(outDate, "Weekday", weekday);
     }
     // RETURN WEEKDAY (lowercase letters)
     else if (calDateFormat.indexOf("weekday") != -1)
     {
         outDate = jsReplace(outDate, "weekday", weekday.toLowerCase());
     }
     // RETURN WEEKDAY (UPPERCASE LETTERS)
     else if (calDateFormat.indexOf("WEEKDAY") != -1)
     {
         outDate = jsReplace(outDate, "WEEKDAY", weekday.toUpperCase());
     }
  
     // RETURN WEEKDAY 3-DAY ABBREVIATION (Initial Caps)
     if (calDateFormat.indexOf("Wkdy") != -1)
     {
         outDate = jsReplace(outDate, "Wkdy", weekdayAbbrev);
     }
     // RETURN WEEKDAY 3-DAY ABBREVIATION (lowercase letters)
     else if (calDateFormat.indexOf("wkdy") != -1)
     {
         outDate = jsReplace(outDate, "wkdy", weekdayAbbrev.toLowerCase());
     }
     // RETURN WEEKDAY 3-DAY ABBREVIATION (UPPERCASE LETTERS)
     else if (calDateFormat.indexOf("WKDY") != -1)
     {
         outDate = jsReplace(outDate, "WKDY", weekdayAbbrev.toUpperCase());
     }
   }
   else
     outDate = '';

   // SET THE VALUE OF THE FIELD THAT WAS PASSED TO THE CALENDAR
   calDateField.value = outDate;

   // GIVE FOCUS BACK TO THE DATE FIELD
   calDateField.focus();

   // CLOSE THE CALENDAR WINDOW
   self.calWin.close();
   self.calWin=null;
}

