
/*
 * window: Window to use for displaying the calendar
 * mode: 0: Freetext complete date; 1: Combobox complete date; 2: Comboboxes Date, Month/Year (Departure Date)
 *       3: Comboboxes Date, Month/Year (Return Date)
 * formname: Name of form to reflect choices in the calendar
 * formelements: Array of names of form elements to reflect choices in the calendar
 *              if mode 0: one element (input field)
 *              if mode 1: one element (combobox)
 *              if mode 2 or 3: two elements (comboboxes in sequence date, month/year;
 *                           optional other comboboxes for calendar validation in sequence date, month, year)
 * originalChosen: date which was chosen on the original web page
 * chosen: date which defines the month to display
 * numberOfMonth: Number of months to display (starting with the current month)
 * validateCalendar: Indicates whether a service method is to include after a date was selected.
 *                   The service method can influence the contents of other form elements.
 * selectedArea: Index of the area currently selected
 * pattern: display pattern
 * submit: Indicates whether to submit the calendar launching form after a date was selected in the calendar.
 * alwaysOnTop (optional):  Indicates if the popup should alwyas be on top. If alwaysOnTop is true
 *							onblur="self.focus();opener.blur();" is added to the body tag
 */

function generateCal(
        window, mode, formname, formelements, originalChosen, chosen,
        numberOfMonths, validateCalendar, selectedArea, pattern, submit, alwaysOnTop) {
   var calDoc = window.document;
   calDoc.open();

   var selectedMonth;
   var selectedYear;

   var elements = formelements;

   // prepare holidays
   var vacationArray = new Array();

   if (selectedArea > - 1) {
      // Prepare holidays for the selected area
      for (var i = 1; i < vacations[selectedArea].length; i++) {
         var vacationDate = new String(vacations[selectedArea][i]);
         // Compute day
         var vacationDay = vacationDate.substring(0, vacationDate.indexOf('.'));
         // Compute month
         var vacationMonth = vacationDate.substring(vacationDate.indexOf('.') + 1, vacationDate.lastIndexOf('.'));
         // Compute year
         var vacationYear = vacationDate.substring(vacationDate.lastIndexOf('.') + 1);
         // if year has only 2 characters: prefix with "20"
         if (vacationYear < 100) {
            vacationYear = "20" + vacationYear;
         }
         // Create date
         vacationArray[i - 1] = new Date(vacationYear, vacationMonth - 1, vacationDay);
      }
   }

   var today = new Date();

   calDoc.writeln('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">');
   calDoc.writeln('<html>');
   calDoc.writeln('<head>');
   calDoc.writeln('	<title>' + calendarTitle + '</title>');
   calDoc.writeln('	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">');
   calDoc.writeln('	<link rel="stylesheet" href="' + calendarCss + '" type="text/css">');
   calDoc.writeln('</head>');
   calDoc.writeln('<body id="genCalPopupBody">');
   calDoc.writeln('<form name="calForm">');
   calDoc.writeln('	<div id="genCalPopup">');
   calDoc.writeln('		<div id="genCalPopupHeadline">' + calendarTitle + '</div>');

   calDoc.writeln('<script type="text/javascript" language="JavaScript">function submitMonthSel() {');
   calDoc.writeln('   var forms = new Array(' + formelements.length + ');');

   for (i = 0; i < formelements.length; i++) {
      calDoc.writeln('   forms[' + i + '] = \''  + formelements[i]+ '\';');
   }

   calDoc.writeln('    opener.calendarChooseMonth(self,' + mode + ',\'' + formname  + '\', forms,' + originalChosen.getTime() + ',document.calForm.monthBox.options[document.calForm.monthBox.selectedIndex].value,' + numberOfMonths + ',' + validateCalendar + ',document.calForm.areas.options[document.calForm.areas.selectedIndex].value,\'' + pattern + '\',' + submit + ');');
   calDoc.writeln('}</script>');
   // show selectbox with month and year
   calDoc.writeln('<div id="genCalPopupMonthSelCell"><div id="genCalPopupMonthPrev" title="' + calendarMonthPrevTitle + '" onclick="select = document.getElementById(\'genCalPopupMonthSel\'); if (select.selectedIndex > 0) { select.selectedIndex= select.selectedIndex-1; submitMonthSel()};"></div>');
   calDoc.writeln('<select name="monthBox" onchange="submitMonthSel()" id="genCalPopupMonthSel" class="genCalPopupSel">');

   var optionDate = new Date();
   // preset day to first day because of overrun of last days on some months:
   // starting with (today) 31.10 and after adding 1 month we get 31.11 (non-existant date), therefore
   // we get not november as month but dezember (bugs 42339, 45402)!!!
   optionDate.setDate(1);
   for (i = 0; i < numberOfMonths; i++) {
      selectedMonth = (today.getMonth() + i) % 12;
      optionDate.setMonth(selectedMonth);
      selectedYear = today.getFullYear() + (today.getMonth() + i)/12;
      optionDate.setYear(selectedYear);
      var optionDateString = "" + calendarMonths[optionDate.getMonth()] + " " + optionDate.getFullYear();
      if ((mode != 1)
            || ((mode == 1) && (comboboxContainsMonth(optionDate, formname, elements[0], pattern)))) {
         calDoc.write('<option value = "' + optionDate.getTime() + '"');
         if ((optionDate.getMonth() == chosen.getMonth()) && (optionDate.getFullYear() == chosen.getFullYear())) {
            calDoc.write(' selected');
         }
         calDoc.writeln('>' + optionDateString + '</option>');
      }
   }
   calDoc.writeln('</select>');
   calDoc.writeln('<div id="genCalPopupMonthNext" title="' + calendarMonthNextTitle + '" onclick="select = document.getElementById(\'genCalPopupMonthSel\'); if (select.selectedIndex < select.length-1) { select.selectedIndex=select.selectedIndex+1; submitMonthSel(); };"></div></div>');


   calDoc.writeln('<div id="genCalPopupCalendar">');

   calDoc.writeln('<div id="genCalPopupDayNames">');
   for (i = 0; i < calendarDays.length; i++) {
      calDoc.writeln('<div class="genCalPopupDayName">' + calendarDays[i] + '</div>');
   }
   calDoc.writeln('</div>');

   calDoc.writeln('<div id="genCalPopupDays"><div class="genCalPopupWeek">');

   var iter = new Date(chosen.getFullYear(), chosen.getMonth(), 1);
   var diff = iter.getDay();

   // Weeks start with monday
   if (diff > 0)
    iter = new Date(iter.getTime() - 86400000 * (diff - 1));
   else
    iter = new Date(iter.getTime() - 86400000 *(diff + 6));

   // create days
   for (i = 0; i < 42; i++) {
      var bgc = "genCalPopupDay";

      // check if special vacations are selected
      if (selectedArea > - 1) {
         // check all intervals
         for (var j = 0; j < vacationArray.length; j = j + 2) {
            if ((iter.getTime() >= vacationArray[j].getTime())
                    && (iter.getTime() < (vacationArray[j + 1].getTime() + 86400000))) {
               bgc = "genCalPopupVacationDay";
            }
         }
      }

      var isChosen = false;

      if ((originalChosen != null)
            && (iter.getFullYear() == originalChosen.getFullYear())
            && (iter.getMonth() == originalChosen.getMonth())
            && (iter.getDate() == originalChosen.getDate())) {
                isChosen = true;
      }

      var isToday = false;
      if ((iter.getFullYear() == today.getFullYear())
            && (iter.getMonth() == today.getMonth())
            && (iter.getDate() == today.getDate())) {
                isToday = true;
      }

      var id = '';
      if (isToday && isChosen) {
          id = ' id="genCalPopupDayTodayChosen"';
      } else if (isToday) {
          id = ' id="genCalPopupDayToday"';
      } else if (isChosen) {
          id = ' id="genCalPopupDayChosen"';
      }

      calDoc.writeln('<div class="' + bgc + '"' + id + '>');

      var call = null;
      var isInThePast = false;

      if ((iter.getFullYear() == today.getFullYear())
            && (iter.getMonth() == today.getMonth())
            && (iter.getDate() < today.getDate())) {
                isInThePast = true;
      }

      if (!isInThePast) {
          if (mode == 0) {
            if (iter.getMonth() == chosen.getMonth()) {
              var element = formelements[0];
                call = 'setDateToFreeTextField(\'' + formname + '\',\'' + element + '\',' + iter.getDate() + ',' + iter.getMonth() + ',' + iter.getFullYear() + ',\'' + pattern + '\', self);';
            }
          } else if (mode == 1) {
            var idx = comboboxContainsDay(iter, formname, elements[0], pattern);
            if (idx >= 0) {
                call = 'setDateToDateCombobox(\'' + formname + '\',\'' + elements[0] + '\',' + idx + ', self);';
             }
          } else if ((mode == 2) || (mode == 3)) {
             if (iter.getMonth() == chosen.getMonth()) {
                call = 'setDateToDayAndMonthYearCombobox(\'' + formname + '\',\'' + elements[0] + '\',\'' + elements[1] + '\',' + iter.getDate() + ',' + iter.getMonth() + ',' + iter.getFullYear() + ', self);';

            }
          }
      }

      if (call != null) {
        calDoc.write('<a class="genCalPopupDayLink" href="javascript:opener.' + call + ' window.close();');
        if (validateCalendar) {
            if (mode == 2) {
                calDoc.write('opener.validateVacationDateDayAndMonthCombobox(\''
                    + formname + '\',\''
                    + elements[0] + '\',\''
                    + elements[0] + '\',\''
                    + elements[1] + '\',\''
                    + elements[2] + '\',\''
                    + elements[3] + '\');');
            } else if (mode == 3) {
                calDoc.write('opener.validateVacationDateDayAndMonthCombobox(\''
                    + formname + '\',\''
                    + elements[0] + '\',\''
                    + elements[2] + '\',\''
                    + elements[3] + '\',\''
                    + elements[0] + '\',\''
                    + elements[1] + '\')');
            } else if (mode == 0) {
               calDoc.write('opener.validateVacationDateField(\''
                    + pattern + '\',\''
                    + formname + '\',\''
                    + elements[0] + '\',\''
                    + elements[0] + '\',\''
                    + elements[1] + '\')');
            }
        }
        if (submit) {
            calDoc.write('opener.document.forms[\'' + formname + '\'].submit();');
        }
        calDoc.write('">');
      }

      calDoc.write(iter.getDate());

      if (call != null) {
         calDoc.writeln('</a>');
      }

      calDoc.write('</div>');

      if (i % 7 == 6) {
         calDoc.writeln('</div><div class="genCalPopupWeek">');
      }
      iter.setDate(iter.getDate() + 1);
   }

   calDoc.writeln('</div></div></div>');
   calDoc.writeln('<div id="genCalPopupInstruction">' + calendarInstruction + '.</div>');
   calDoc.writeln('<div id="genCalPopupVacationCell">');
   calDoc.writeln('<div id="genCalPopupVacationLabel">' + calendarHolidays + ':</div>');

   // special areas
   calDoc.writeln('<select name="areas" onChange="submitMonthSel()" id="genCalPopupStateSel" class="genCalPopupSel">');
   calDoc.writeln('<option value = "-1">' + calendarChooseArea);
   for (var i = 0; i < vacations.length; i++) {
      calDoc.write('<option ');
      // selected area must be reselected upon regeneration
      if (i == selectedArea) {
         calDoc.write('selected ');
      }
      calDoc.writeln('value = "' + i + '"> ' + vacations[i][0]);
   }
   calDoc.writeln('</select>');
   calDoc.writeln('</div>');
   calDoc.writeln('<div id="genCalPopupWindowCloseCell"><a id="genCalPopupWindowClose" href="javascript:window.close()">' + calendarClose + '</a></div>');
   calDoc.writeln('</div>');
   calDoc.writeln('</form>');
   calDoc.writeln('</body>');
   calDoc.writeln('</html>');
   calDoc.close();
};
