/* him_info_vtcal.js */

/* Textauswahl fur das Informationsfeld */
// ~~~ Declaration of Calendar object
//
//  notes:
//   uses 0-11 range for months internal - only for disply 1-12!
//
//  usage:
//  var cal = new Calendar("window.document", "formular", "datefield", "cal");
//      ^^^                                                             ^^^
//  these two names above must be identical. The following global arrays need to be available:
//
//  weekdaysTexts = new Array("Mo","Di","Mi","Do","Fr","Sa","So");
//  monthsTexts = new Array("Januar","Februar",...);
//
//
function CalendarRange(returnWindow, returnForm, returnTextField, instancename) {
   //  methods
   //  ~~~
   this.draw                   = CalendarRange_draw;
   this.setDate                = CalendarRange_setDate;
   this.getStartDateFromString = CalendarRange_getStartDateFromString;
   this.getStartDateFrom       = CalendarRange_getStartDateFrom;
   this.getEndDateFromString   = CalendarRange_getEndDateFromString;
   this.getEndDateFrom         = CalendarRange_getEndDateFrom;
   this.parseUserDateInput     = CalendarRange_parseUserDateInput;
   this.refReturnField         = CalendarRange_refReturnField;

   this.selectWeekends         = CalendarRange_selectWeekends;
   this.selectWorkdays         = CalendarRange_selectWorkdays;
   this.selectMonth            = CalendarRange_selectMonth;
   this.selectDays             = CalendarRange_selectDays;
   this.getFromBitfield        = CalendarRange_getFromBitfield;
   this.setToBitfield          = CalendarRange_setToBitfield;

   //  fields
   //  ~~~

   this.returnWindow = returnWindow;
   this.name = instancename;
   this.returnForm = returnForm;
   this.returnTextfield = returnTextField;

   this.startday   = null;
   this.startmonth = null;
   this.startyear  = null;
   this.endday     = null;
   this.endmonth   = null;
   this.endyear    = null;

   this.howmanydays = 1;

   /* from global arrays */
   this.monthsTexts   = monthsTexts;
   /* spelling check to avoid modifying maaany files */
   this.weekdaysTexts = (typeof (weekdayTexts) != "undefined") ? weekdayTexts : weekdaysTexts;

   // view-only bitfields
   this.readOnly = false;
}


function CalendarRange_getStartDateFrom(ioField) {
   eval("userInput = "+this.returnWindow+"."+this.returnForm+"."+ioField+".value;");

   this.getStartDateFromString(userInput);
}

function CalendarRange_getStartDateFromString(datestring) {
   var startdate = this.parseUserDateInput(datestring);

   this.startday   = startdate.getDate();
   this.startmonth = startdate.getMonth();
   this.startyear  = startdate.getFullYear();
}

function CalendarRange_getEndDateFrom(ioField) {
   eval("userInput = "+this.returnWindow+"."+this.returnForm+"."+ioField+".value;");
   this.getEndDateFromString(userInput);
}


function CalendarRange_getEndDateFromString(datestring) {
   var enddate = this.parseUserDateInput(datestring);

   this.endday   = enddate.getDate();
   this.endmonth = enddate.getMonth();
   this.endyear  = enddate.getFullYear();
}


function CalendarRange_parseUserDateInput(userInput){
   var matchReg = /(\d+)\D+(\d+)\D+(\d+)\D*/;
   var success = matchReg.exec( userInput );

   userInput_day   = RegExp.$1;
   userInput_month = RegExp.$2;
   userInput_year  = RegExp.$3;

   if (!success) {
      return new Date();
      }

   userInput_day *= 1; userInput_month *= 1; userInput_year *= 1;
   // attention: userInput_month is 1-12-ranged!
   // ~~~
   if(userInput_month!="") {
     userInput_month -= 1;
     if(userInput_month<0) {
       userInput_month = 11;
     } else if(userInput_month>11) {
       userInput_month = 0;
     }
   }
   if(userInput_year!="") {
     if(userInput_year<100) {
       if(userInput_year<50){
          userInput_year+=2000;
        } else {
          userInput_year+=1900;
        }
     } else if (userInput_year < 1000) {
       if(userInput_year<200){
          userInput_year+=1900;
        } else {
          userInput_year+=1000;
        }
     }
   }

   return new Date(userInput_year, userInput_month, userInput_day);
}

function CalendarRange_refReturnField() {
   return this.returnWindow+"."+this.returnForm+"."+this.returnTextfield;
}

//
// This function toggles the given date's style
//
function CalendarRange_setDate(cell) {
  // set the colors by style
  var selectedDay = document.getElementById(cell);
  selectedDay.className = (selectedDay.className == "active") ? "enabled" : "active";
}

//
// This function fills the calendar table with the days of
// the selected month and year.
//
function CalendarRange_draw() {
   // saving some time - only redraw if inputs have changed
   if ((this.lastdrawstartday   != this.startday) ||
       (this.lastdrawstartmonth != this.startmonth) ||
       (this.lastdrawstartyear  != this.startyear) ||
       (this.lastdrawendday     != this.endday) ||
       (this.lastdrawendmonth   != this.endmonth) ||
       (this.lastdrawendyear    != this.endyear))
      {
      this.lastdrawstartday   = this.startday;
      this.lastdrawstartmonth = this.startmonth;
      this.lastdrawstartyear  = this.startyear;
      this.lastdrawendday     = this.endday;
      this.lastdrawendmonth   = this.endmonth;
      this.lastdrawendyear    = this.endyear;
      var div = document.getElementById(this.name);
      var numMonths = 0;

      /* set time to 00:00 */
      var tempstartdate   = new Date(this.startyear, this.startmonth, this.startday);
      var tempenddate   = new Date(this.endyear, this.endmonth, this.endday);
      //Set 1 day in milliseconds
      var one_day=86400000;
      this.howmanydays = Math.ceil((tempenddate.getTime()-tempstartdate.getTime())/(one_day))

      // create table if it does not already exist
      var table = document.getElementById(this.name+"_table");
/*
      if (table != null) {
       // remove existing content to prevent render errors of calendar
       while(table.hasChildNodes()) {
        table.removeChild(table.lastChild);
       }
       div.removeChild(table);
    }
*/
      if (table == null) {
         table = document.createElement("TABLE");
         div.insertBefore(table,div.firstChild);
         table.id = this.name+"_table";
         table.className="calendar";
         table.setAttribute( "cellspacing", "0" );
         }

      // Recycling: remove complete table body...it's recreated => fast delete
      var tbody = document.getElementById(this.name+"_tbody");
      if (tbody != null) {
           tbody.parentNode.removeChild(tbody);
         }

      // (re-)create tbody
      tbody = document.createElement("TBODY");
      table.appendChild(tbody);
      tbody.id = this.name+"_tbody";

      // update header and status texts
      // Always draw full months
      var tempdate = new Date(this.startyear,this.startmonth,1);
      var maxMonthReached = false;
      var maxMonthsPerRow = 6;

      // remember latest month header in order to adjust its width to the weeks drawn:
      var latestHeader = null;

      calendarRow = 0;

      while( tempenddate >= tempdate )
        {
        var cell = null;
        ++calendarRow;

        numMonths = 0;

        // Calculate skip between first table cell and first one with content (which
        // weekday does the calendar start with)
        // if it is 0 (sunday) set to 6 as the week begins on monday
        daystoskip = (tempdate.getDay()-1 < 0) ? 6 : tempdate.getDay()-1;

        var newmonth = true;
        var oldtempcolspan = 0;
        var colspan = 1;

        var w = -1;
        var newWeekNeeded = true;
        var numWeeksInMonth = 0;

        while (newWeekNeeded == true)
            {
            ++w;
            ++numWeeksInMonth;

            if (tempdate.getDate() == 1 && newmonth == true)
               {
               numWeeksInMonth = 1;
               ++numMonths;
               // a new month begins...

               // which weekday is the current date (e.g. 1st April 2005 is a Friday (5))?
               // if it is 0 (sunday) set to 6 as the week begins on monday
               daystoskip = (tempdate.getDay()-1 < 0) ? 6 : tempdate.getDay()-1;

               // retrieve row with month names
               var current_row = document.getElementById(this.name+"_monthrow_" + calendarRow);
               if (current_row == null)
                   {
                   current_row=document.createElement("TR");
                   current_row.id=this.name+"_monthrow_" + calendarRow;
                   // first empty cell in first row
                   cell=document.createElement("TH");
                   cell.className="disabled";
                   cell.innerHTML = "&nbsp";
                   cell.style.width = "40px";
                   current_row.appendChild(cell);
                   }
               cell = document.createElement("TH");

               // Remember latest header:
               latestHeader = cell;

               cell.innerHTML = "<b>"+this.monthsTexts[tempdate.getMonth()]+"&nbsp;"+tempdate.getFullYear()+"</b>";
               cell.className = "enabled";
               cell.id = this.name+"_heading_months"+tempdate.getMonth()+"-"+tempdate.getFullYear();
               if (this.readOnly == false) {
                  cell.onclick = function() {
                     var calid = this.id.substring(0,this.id.indexOf("_heading_months"));
                     var month = this.id.substring(this.id.indexOf("_heading_months")+15,this.id.indexOf("-"));
                     var year = this.id.substring(this.id.indexOf("-")+1,this.id.length);
                     var test = eval('calid')+".selectMonth(month,year);";
                     eval(test);
                     }
                  }
               current_row.appendChild(cell);

               // inserts the row TR into TBODY
               if ( numMonths == 1 )
                   tbody.insertBefore(current_row, null);
               }

            // draws a full week
            for(var d = 0; d < 7; d++)
                {
                current_row = document.getElementById(this.name+"_row_"+d + "_" + calendarRow );
                if (current_row == null)
                    {
                    current_row = document.createElement("TR");
                    current_row.id = this.name+"_row_"+d + "_" + calendarRow ;
                    cell = document.createElement("TH");

                    cell.id = this.name+"_heading_"+d;
                    cell.innerHTML = "<b>"+this.weekdaysTexts[d]+"</b>";
                    cell.className = "enabled";
                    if (this.readOnly == false) {
                      cell.onclick = function() {
                          var calid = this.id.substring(0,this.id.indexOf("_heading_"));
                          var day = this.id.substring(this.id.indexOf("_heading_")+9,this.id.length);
                          var test = eval('calid')+".selectDays(day);";
                          eval(test);
                          }
                      }
                    cell.style.width = "40px";
                    cell.setAttribute("style", "width:40px;");

                    current_row.appendChild(cell);
                    tbody.appendChild(current_row);
                    }

                // Adjust colspans:
                var nextDay = new Date( tempdate );
                nextDay.setDate( tempdate.getDate() + 1 );
                newmonth = (nextDay.getMonth() != tempdate.getMonth());

                cell = document.createElement("TD");
                cell.setAttribute("style", "font-size: xx-small;" );

                if(daystoskip <= 0)
                    {
                    if ( (tempdate > tempenddate) || (tempdate < tempstartdate) )
                        {
                        cell.className = "disabled";
                        // give no ID !!!
                        cell.innerHTML = tempdate.getDate();
                        cell.onclick = null;
                        }
                    else
                        {
                        cell.innerHTML = tempdate.getDate();
                        // Change table cells id to represent current displayed date
                        cell.id = this.name+"_df_"+tempdate.getFullYear()+"/"+(tempdate.getMonth())+"/"+tempdate.getDate();
                        cell.className = "enabled";

                        if (this.readOnly == false) {
                            cell.onclick = function(){
                                var calid = this.id.substring(0,this.id.indexOf("_df"));
                                var test = eval('calid')+".setDate(this.id);";
                                eval(test);
                                };
                           }
                        }
                    tempdate.setDate(tempdate.getDate()+1);
                    }
                //  deactivate cell
                else
                    {
                    cell.className = "disabled";
                    // give no ID !!!
                    cell.innerHTML = "&nbsp;";
                    cell.onclick = null;
                    daystoskip -= 1;
                    }

                cell.style.width = "15px";

                current_row.appendChild(cell);

                if (newmonth)
                    {
                    latestHeader.setAttribute("colSpan", numWeeksInMonth);

                    // append remaining empty cells to fill week column:
                    for (var e = d; e < 6; e++)
                        {
                        cell = document.createElement("TD");
                        cell.className = "disabled";
                        cell.innerHTML = "&nbsp;";
                        current_row = document.getElementById(this.name+"_row_"+ (e+1) + "_" + calendarRow );
                        if (current_row != null)
                            {
                            current_row.appendChild(cell);
                            }
                        else
                            {
                            //cell.className = "active";
                            }
                        cell.style.width = "15px";
                        }
                    break;
                    }
                }

            if (((tempdate > tempenddate) || (numMonths >= maxMonthsPerRow)) && (tempdate.getDate() == 1))
                {
                newWeekNeeded = false;
                }
            if (numMonths >= maxMonthsPerRow)
              {
              maxMonthReached = true;
              }
            }
        }

    // auto-correction of div size
    if (maxMonthReached == true) {
      calendarWidth = 1*maxMonthsPerRow*120+60+"px";
      }
    else {
      addWidth = (numMonths == 1)? 85:60;
      calendarWidth = 1*numMonths*120+1*addWidth+"px";
      }
    document.getElementById(this.name).style.width = calendarWidth;
    var temp = document.getElementById(this.name+'_table');
    if (typeof (temp) != "undefined" && temp != null) {
        temp.style.width = calendarWidth;
    }
   }
} // - END function Calendar_draw();

function CalendarRange_selectWeekends(yesorno) {
   var tempdate = new Date(this.startyear,this.startmonth,this.startday);
   var elem = null; var temp = null;
   for (i = 0; i <= this.howmanydays; i++) {

      if (tempdate.getDay() == 6 || tempdate.getDay() == 0) {
        temp = this.name+"_df_"+tempdate.getFullYear()+"/"+(tempdate.getMonth())+"/"+tempdate.getDate();
        elem = document.getElementById(temp);
        if (elem != null) {
           elem.className = (yesorno == true) ? "active" : "enabled";
        }
      }
      tempdate.setDate(tempdate.getDate()+1);
   }
}

function CalendarRange_selectWorkdays(yesorno) {
   var tempdate = new Date(this.startyear,this.startmonth,this.startday);
   for (i = 0; i <= this.howmanydays; i++) {

      if (tempdate.getDay() >= 1 && tempdate.getDay() <= 5) {
        var temp = this.name+"_df_"+tempdate.getFullYear()+"/"+(tempdate.getMonth())+"/"+tempdate.getDate();
        elem = document.getElementById(temp);
        if (elem != null) {
           elem.className = (yesorno) ? "active" : "enabled";
        }
      }
      tempdate.setDate(tempdate.getDate()+1);
   }
}

function CalendarRange_selectDays(weekday) {
   var tempdate = new Date(this.startyear,this.startmonth,this.startday);
   var state = null;
   var day = null;

   for (i = 0; i <= this.howmanydays; i++) {
      day = tempdate.getDay()-1;
      day = (day == -1) ? 6 : day;

      if (day == weekday) {
        elem = document.getElementById(this.name+"_df_"+tempdate.getFullYear()+"/"+(tempdate.getMonth())+"/"+tempdate.getDate());
        if (elem != null) {
           if (state == null) {
              state = (elem.className == "active") ? 1 : 0;
           }
           elem.className = (state == 1) ? "enabled" : "active";
        }
        i += 6;
        tempdate.setDate(tempdate.getDate()+7);
      } else {
        tempdate.setDate(tempdate.getDate()+1);
      }
   }
}

function CalendarRange_selectMonth(selectedmonth,selectedyear) {
   var tempdate = new Date(selectedyear,selectedmonth,1);
   var state = null;
   var month = null;
   var begun = null;

   for (i = 0; i <= this.howmanydays; i++) {
      month = tempdate.getMonth();

      if (month == selectedmonth) {
        begun = true;
        elem = document.getElementById(this.name+"_df_"+tempdate.getFullYear()+"/"+(tempdate.getMonth())+"/"+tempdate.getDate());
        if (elem != null) {
           if (state == null) {
              state = (elem.className == "active") ? 1 : 0;
           }
           elem.className = (state == 1) ? "enabled" : "active";
           }
      } else {
        // end if months last day has been reached
        if (begun == true) {break;}
      }
      tempdate.setDate(tempdate.getDate()+1);
   }
}

function CalendarRange_getFromBitfield(bitfield) {
   if (bitfield == null) {
      eval("bitfield = "+this.refReturnField()+".value;");
   }

   var td = new Date(this.startyear,this.startmonth,this.startday);
   for (i = 0; i < this.howmanydays; i++) {
     elem = document.getElementById(this.name+"_df_"+td.getFullYear()+"/"+(td.getMonth())+"/"+td.getDate());
     if (elem != null) {
        elem.className = (bitfield.charAt(i) == "0") ? "enabled" : "active";
     }
     td.setDate(td.getDate()+1);
   }
}

function CalendarRange_setToBitfield() {
   var tempdate = new Date(this.startyear,this.startmonth,this.startday);
   var bitfield = "";
   var lastactive = "";
   var firstactive = "";
   for (i = 0; i < this.howmanydays; i++) {

        elem = document.getElementById(this.name+"_df_"+tempdate.getFullYear()+"/"+(tempdate.getMonth())+"/"+tempdate.getDate());
        if (elem != null) {
           if (elem.className == "active" ) {
              if (firstactive == "") {
                firstactive = elem;
              }
              bitfield += "1";
              lastactive = elem;
           } else {
              bitfield += "0";
           }
        }
      tempdate.setDate(tempdate.getDate()+1);
   }
   bitfield = bitfield + "";

   eval(this.refReturnField()+".value = \""+bitfield+"\"");
}

function isLeapYear(y){if(((y%4)==0 && (y%100)!=0) || (y%400)==0) return true;}

function openCalDiv(name, fieldPrefix) {

  var periodIsInLimit = checkDisplayPeriod(fieldPrefix);

  if (periodIsInLimit == false)
    document.getElementById("periodLimitHint").innerHTML = "<b>Die Periode die angezeigt werden soll ist zu groß (max. 2 Jahre können dargestellt werden)</b>";
  else
    document.getElementById("periodLimitHint").innerHTML = "";

  var elem = window.document.getElementById(name);

  if (elem.style.display == 'none' && periodIsInLimit == true)
    {
    eval(name).getStartDateFrom(fieldPrefix+'Date1');
    eval(name).getEndDateFrom(fieldPrefix+'Date2');
    eval(name).draw();
    eval(name).getFromBitfield();
    elem.style.display = 'block';
    }
  else
    {
    elem.style.display = 'none';
    }

}

function openCal(name) {
    cal2.readOnly = true;
    cal2.draw();
    cal2.getFromBitfield();
}

function checkDisplayPeriod(fieldPrefix)
  {
  var period2DisplayLimit = 730; // in days
  var d1 = string2dateObj(document.getElementById(fieldPrefix+'Date1').value)
  var d2 = string2dateObj(document.getElementById(fieldPrefix+'Date2').value)
  var period2Display = parseInt((d2-d1)/(60*60*24*1000));

  //console.info(period2Display ," - ", d2-d1);

  if(period2Display <= period2DisplayLimit && period2Display >= 0)
    return true
  else
    return false
  }

function string2dateObj(dateString)
  {
  var today = new Date();
  var dateArray = dateString.split(".")
  //var yy = today.getFullYear();
  var yy = parseInt(dateArray[2]);
  var mm = parseInt(dateArray[1]-1);
  var dd = parseInt(dateArray[0]);
  var compDate = new Date(yy , mm , dd);
  return compDate;
  }


