
// Customizable variables
var DefaultDateFormat = 'YYYY-MM-DD';
var FontSize = 11; // In pixels
var FontFamily = 'Tahoma';
var CellWidth = 18;
var CellHeight = 16;
var ImageURL = 'img/calendar.jpg';
var NextURL = 'img/next.gif';
var PrevURL = 'img/prev.gif';
var CalBGColor = 'white';
var TopRowBGColor = 'buttonface';
var DayBGColor = 'lightgrey';

// Global variables
var ZCounter = 100;
var Today = new Date();
var WeekDays = new Array('Ni','Pn','Wt','Śr','Cz','Pt','So');
var MonthDays = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var MonthNames = new Array('Styczeń','Luty','Marzec','Kwiecień','Maj','Czerwiec','Lipiec','Sierpień','Wrzesień','Październik','Listopad','Grudzień');

// Write out the stylesheet definition for the calendar
with (document) {
   writeln('<style>');
   writeln('td.calendarDateInput {letter-spacing:normal;line-height:normal;font-family:' + FontFamily + ',Sans-Serif;font-size:' + FontSize + 'px;}');
   writeln('select.calendarDateInput {letter-spacing:.06em;font-family:Verdana,Sans-Serif;font-size:11px;}');
   writeln('input.calendarDateInput {letter-spacing:.06em;font-family:Verdana,Sans-Serif;font-size:11px;}');
   
   writeln('.calendarDays{letter-spacing:normal;line-height:normal;font-family:' + FontFamily + ',Sans-Serif;font-size:' + FontSize + 'px; text-align: center;height:' + CellHeight + 'px;width:' + CellWidth + 'px;font-weight:bold;border-top:1px solid dimgray;border-bottom:1px solid dimgray;}');
   writeln('.calendarDay{letter-spacing:normal;line-height:normal;font-family:' + FontFamily + ',Sans-Serif;font-size:' + FontSize + 'px; cursor:pointer; text-align: center;height:' + CellHeight + 'px;width:' + CellWidth + 'px;}');
   writeln('.calendarPrev, .calendarNext, .calendarCurrent{letter-spacing:normal;line-height:normal;font-family:' + FontFamily + ',Sans-Serif;font-size:' + FontSize + 'px; cursor:pointer;height:' + CellHeight + 'px; text-align: center}');
   writeln('.calendarPrev:hover, .calendarNext:hover, .calendarCurrent:hover, .calendarDay:hover{background: ' + DayBGColor + ';}');
   writeln('</style>');
}

// Gets the absolute pixel position of the supplied element
function GetTagPixels(StartTag, Direction) {
   var PixelAmt = (Direction == 'LEFT') ? StartTag.offsetLeft : StartTag.offsetTop;
   while ((StartTag.tagName != 'BODY') && (StartTag.tagName != 'HTML')) {
      StartTag = StartTag.offsetParent;
      PixelAmt += (Direction == 'LEFT') ? StartTag.offsetLeft : StartTag.offsetTop;
	  //alert(PixelAmt);
   }
   return PixelAmt;
}

// Returns the number of days in a month (handles leap-years)
function GetDayCount(SomeYear, SomeMonth) {
   return ((SomeMonth == 1) && ((SomeYear % 400 == 0) || ((SomeYear % 4 == 0) && (SomeYear % 100 != 0)))) ? 29 : MonthDays[SomeMonth];
}

function PickDisplayDay(ClickedDay) {
   this.show();
   this.picked = new storedDateObject(this.format, this.displayed.date.getFullYear(), this.displayed.date.getMonth(), ClickedDay);
   this.getDayTable().innerHTML = this.buildCalendar();
   this.getFieldName().value = this.picked.formatted;
}

// Builds the HTML for the calendar days
function BuildCalendarDays() {
   var Rows = 5;
   if (((this.displayed.dayCount == 31) && (this.displayed.firstDay > 4)) || ((this.displayed.dayCount == 30) && (this.displayed.firstDay == 6))) Rows = 6;
   else if ((this.displayed.dayCount == 28) && (this.displayed.firstDay == 0)) Rows = 4;
   var HTML = '<table width="' + (CellWidth * 7) + '" cellspacing="0" cellpadding="1" style="cursor:default">';
   
   for (var j=0;j<Rows;j++) {
      HTML += '<tr>';
      for (var i=1;i<=7;i++) {
         Day = (j * 7) + (i - this.displayed.firstDay);
         if ((Day >= 1) && (Day <= this.displayed.dayCount)) {
            if ((this.displayed.yearValue == this.picked.yearValue) && (this.displayed.monthIndex == this.picked.monthIndex) && (Day == this.picked.day)) {
               if (i>1) TextStyle = 'color:white;font-weight:bold;';
               else TextStyle = 'color:red;font-weight:bold;'
               BackColor = DayBGColor;
            }
            else {
               if (i>1) TextStyle = 'color:black;';
               else TextStyle = 'color:red;';
               BackColor = CalBGColor;
            }
            if ((this.displayed.yearValue == Today.getFullYear()) && (this.displayed.monthIndex == Today.getMonth()) && (Day == Today.getDate())) TextStyle += 'border:1px solid darkred;padding:0px;';
            HTML += '<td class="calendarDay" style="' + TextStyle + ';background:' + BackColor + '" onClick="' + this.FieldName + '_Object.pickDay(' + Day + ')">' + Day + '</td>';
         }
         else HTML += '<td class="calendarDateInput" style="height:' + CellHeight + '">&nbsp;</td>';
      }
      HTML += '</tr>';
   }
   return HTML += '</table>';
}

function previousMonth(){
   this.displayed.date.setTime(this.displayed.date.getTime() - 86400000);
   this.displayed = new storedDateObject(this.format, this.displayed.date.getFullYear(), this.displayed.date.getMonth(),1);
   this.getDayTable().innerHTML = this.buildCalendar();
   this.getMonthDisplay().innerHTML = this.displayed.fullName;
}

function nextMonth(){
   this.displayed.date.setTime( this.displayed.date.getTime() + (86400000 * (this.displayed.dayCount + 1)));
   this.displayed = new storedDateObject(this.format, this.displayed.date.getFullYear(), this.displayed.date.getMonth(),1);
   this.getDayTable().innerHTML = this.buildCalendar();
   this.getMonthDisplay().innerHTML = this.displayed.fullName;
}

function currentMonth(){
	this.displayed = new storedDateObject(this.format, Today.getFullYear(), Today.getMonth(),1);
   	this.getDayTable().innerHTML = this.buildCalendar();
   	this.getMonthDisplay().innerHTML = this.displayed.fullName;
}

function ShowCalendar() {
	if (this.isShowing()) {
      this.getCalendar().style.zIndex = --ZCounter;
      this.getCalendar().style.visibility = 'hidden';
   }
   else {
      this.getCalendar().style.left = parseInt(GetTagPixels(this.getFieldName(), 'LEFT'))+'px';
	  this.getCalendar().style.top = parseInt(GetTagPixels(this.getFieldName(), 'TOP') + 20)+'px';
	  this.getCalendar().style.zIndex = ++ZCounter;
      this.getCalendar().style.visibility = 'visible';
   }
}

function calendarObject(DateName, DateFormat, DefaultDate) {
  // Properties 
   this.FieldName = DateName;
   this.calendarID = DateName + '_ID';
   this.dayTableID = DateName + '_DayTable_ID';
   this.calendarLinkID = this.calendarID + '_Link';
   this.monthDisplayID = DateName + '_Current_ID';
   
   this.format = DateFormat;
   this.displayed = null;
   this.picked = null;
   
   //Methods
   this.buildCalendar = BuildCalendarDays;
   this.previous = previousMonth; 
   this.next = nextMonth;
   this.current = currentMonth;
   this.pickDay = PickDisplayDay;
   this.show = ShowCalendar;
   
   this.getFieldName = new Function('return document.getElementById(this.FieldName)');
   this.getDayTable = new Function('return document.getElementById(this.dayTableID)');
   this.getMonthDisplay = new Function('return document.getElementById(this.monthDisplayID)');
   this.getCalendar = new Function('return document.getElementById(this.calendarID)');
   this.isShowing = new Function('return !(this.getCalendar().style.visibility != \'visible\')');
  
  // Constructor 
  var Field = this.getFieldName();
  Field.readOnly = true;
  Field.value = DefaultDate;
  
  //alert(GetTagPixels(this.getFieldName(), 'TOP'));
  //alert(GetTagPixels(this.getFieldName(), 'LEFT'));
  //alert(this.getFieldName.style.height);
  
  //this.getCalendar().style.left = GetTagPixels(this.getFieldName(), 'LEFT')+'px';
  //alert(this.getCalendar.style.left);
  //alert(this.getCalendar());
  //alert(document.getElementById(this.calendarID).style.left);
  
  
   // Functions used only by the constructor
   function getMonthIndex(MonthAbbr) { // Returns the index (0-11) of the supplied month abbreviation
      for (var MonPos=0;MonPos<MonthNames.length;MonPos++) {
         if (MonthNames[MonPos].substr(0,3).toUpperCase() == MonthAbbr.toUpperCase()) break;
      }
      return MonPos;
   }
   function SetGoodDate(CalObj, Notify) { // Notifies the user about their bad default date, and sets the current system date
      //CalObj.setPicked(Today.getFullYear(), Today.getMonth(), Today.getDate());
      //if (Notify) alert('WARNING: The supplied date is not in valid \'' + DateFormat + '\' format: ' + DefaultDate + '.\nTherefore, the current system date will be used instead: ' + CalObj.picked.formatted);
   }
   
   this.displayed = new storedDateObject(this.format, Today.getFullYear(), Today.getMonth(), 1);
   this.picked = new storedDateObject(this.format, Today.getFullYear(), Today.getMonth(), Today.getDate());
   
   
   
  if (DefaultDate != '') {
     if ((this.format == 'YYYYMMDD') && (/^(\d{4})(\d{2})(\d{2})$/.test(DefaultDate))) {
        this.picked = new storedDateObject(this.format, RegExp.$1, parseInt(RegExp.$2,10)-1, RegExp.$3);
        this.displayed = new storedDateObject(this.format, this.picked.date.getFullYear(), this.picked.date.getMonth(), 1);
     } else {
         // Get the year
         if ((this.format.substr(0,4) == 'YYYY') && (/^(\d{4})(-|\/)(\d{2})(-|\/)(\d{2})/.test(DefaultDate))) { 
            var YearPart = RegExp.$1;
            var MonthPart = RegExp.$3;
            var DayPart = RegExp.$5;
            this.picked = new storedDateObject(this.format, parseInt(YearPart), parseInt(MonthPart-1), parseInt(DayPart));
            this.displayed = new storedDateObject(this.format, this.picked.date.getFullYear(), this.picked.date.getMonth(), 1);
          }
          if ((this.format.substr(6,4) == 'YYYY') && (/^(\d{2})(-|\/)(\d{2})(-|\/)(\d{4})/.test(DefaultDate))) { 
            var YearPart = RegExp.$5;
            var MonthPart = RegExp.$3;
            var DayPart = RegExp.$1;
            this.picked = new storedDateObject(this.format, parseInt(YearPart), parseInt(MonthPart-1), parseInt(DayPart));
            //alert(this.picked.formatted);
            this.displayed = new storedDateObject(this.format, this.picked.date.getFullYear(), this.picked.date.getMonth(), 1);
          } 
     }
   }
  
	var InitialStatus = '';
	with (document) {
    write(String.fromCharCode(13) + '<a' + InitialStatus + ' id="' + this.calendarLinkID + '" href="javascript:' + this.FieldName + '_Object.show()"><img src="' + ImageURL + '" title="Calendar" style="border: none; vertical-align:text-bottom`;"></a>&nbsp;');
    writeln('<span id="' + this.FieldName + '_ID" style="position:fixed;visibility:hidden;width:' + (CellWidth * 7) + 'px;background-color:' + CalBGColor + ';border:1px solid dimgray;left:8px;top:29px;"');
		writeln('<table width="' + (CellWidth * 7) + '" cellspacing="0" cellpadding="1">' + String.fromCharCode(13) + '<tr style="background-color:' + TopRowBGColor + ';">');
		//poprzedni
		writeln('<td id="' + this.FieldName + '_Previous_ID" class="calendarPrev" onClick="' + this.FieldName + '_Object.previous()" title="Poprzedni miesiąc"><img src="' + PrevURL + '"></td>');
		//miesiac i rok
		writeln('<td id="' + this.FieldName + '_Current_ID" class="calendarCurrent" colspan="5" onClick="' + this.FieldName + '_Object.current()" title="Bieżący miesiąc">' + this.displayed.fullName + '</td>');
		//nastepny
		writeln('<td id="' + this.FieldName + '_Next_ID" class="calendarNext" onClick="' + this.FieldName + '_Object.next()" title="Następny miesiąc"><img src="' + NextURL + '"></td></tr>' + String.fromCharCode(13) + '<tr>');
		//dni tygodnia
		for (var w=0;w<7;w++) writeln('<td width="' + CellWidth + '" class="calendarDays">' + WeekDays[w] + '</td>');
		writeln('</tr>' + String.fromCharCode(13) + '</table>' + String.fromCharCode(13));
		//kalendarz
		writeln('<span id="' + this.FieldName + '_DayTable_ID"></span>');
		writeln('</span>');
	}
	this.getDayTable().innerHTML = this.buildCalendar();
	
	//alert(this.getCalendar());
	//this.getCalendar().style.left = parseInt(GetTagPixels(this.getFieldName(), 'LEFT'))+'px';
	//alert(this.getFieldName().height);
	//this.getCalendar().style.top = parseInt(GetTagPixels(this.getFieldName(), 'TOP') + 20)+'px';
}

// Holds characteristics about a date
function dateObject() {
   if (Function.call) { // Used when 'call' method of the Function object is supported
      var ParentObject = this;
      var ArgumentStart = 0;
   }
   else { // Used with 'call' method of the Function object is NOT supported
      var ParentObject = arguments[0];
      var ArgumentStart = 1;
   }
   ParentObject.date = (arguments.length == (ArgumentStart+1)) ? new Date(arguments[ArgumentStart+0]) : new Date(arguments[ArgumentStart+0], arguments[ArgumentStart+1], arguments[ArgumentStart+2]);
   ParentObject.yearValue = ParentObject.date.getFullYear();
   ParentObject.monthIndex = ParentObject.date.getMonth();
   ParentObject.monthName = MonthNames[ParentObject.monthIndex];
   ParentObject.fullName = ParentObject.monthName + ' ' + ParentObject.yearValue;
   //alert(ParentObject.fullName);
   ParentObject.day = ParentObject.date.getDate();
   ParentObject.dayCount = GetDayCount(ParentObject.yearValue, ParentObject.monthIndex);
   var FirstDate = new Date(ParentObject.yearValue, ParentObject.monthIndex, 1);
   ParentObject.firstDay = FirstDate.getDay();
}


function storedDateObject(DateFormat, DateYear, DateMonth, DateDay) {
   (Function.call) ? dateObject.call(this, DateYear, DateMonth, DateDay) : dateObject(this, DateYear, DateMonth, DateDay);
   this.yearPad = this.yearValue.toString();
   this.monthPad = (this.monthIndex < 9) ? '0' + String(this.monthIndex + 1) : this.monthIndex + 1;
   this.dayPad = (this.day < 10) ? '0' + this.day.toString() : this.day;
   // Formats the year with 2 digits instead of 4
   if (DateFormat.indexOf('YYYY') == -1) this.yearPad = this.yearPad.substr(2);
   // Define the date-part delimiter
   if (DateFormat.indexOf('/') >= 0) var Delimiter = '/';
   else if (DateFormat.indexOf('-') >= 0) var Delimiter = '-';
   else var Delimiter = '';
   // Determine the order of the months and days
   if (/DD?.?(MM?M?)/.test(DateFormat)) {
      this.formatted = this.dayPad + Delimiter;
      this.formatted += this.monthPad;
   }
   else if (/(MM?M?)?.?DD?/.test(DateFormat)) {
      this.formatted = this.monthPad;
      this.formatted += Delimiter + this.dayPad;
   }
   // Either prepend or append the year to the formatted date
   this.formatted = (DateFormat.substr(0,4) == 'YYYY') ? this.yearPad + Delimiter + this.formatted : this.formatted + Delimiter + this.yearPad;
}

function DateInput(DateName, DateFormat, DefaultDate) {
	if (arguments.length > 0) {
		if (arguments.length == 1) DateFormat = DefaultDateFormat;
		if (/^(Y{4}(-|\/)?)?((MM?M?)|(DD?))(-|\/)?((MM?M?)|(DD?))((-|\/)Y{4})?$/i.test(DateFormat)) DateFormat = DateFormat.toUpperCase();
	    else DateFormat = DefaultDateFormat;
		if (!CurrentDate) var CurrentDate = new storedDateObject(DateFormat, Today.getFullYear(), Today.getMonth(), Today.getDate());
		if (arguments.length < 3) DefaultDate = CurrentDate.formatted; 
		eval(DateName + '_Object=new calendarObject(\'' + DateName + '\',\'' + DateFormat + '\',\'' + DefaultDate + '\')');
	}

}


/*
// The calendar object
function calendarObject(DateName, DateFormat, DefaultDate) {
alert('precreate');
   // Properties 
   this.timerID = this.calendarID + '_Timer';
   this.objName = DateName + '_Object';
   //this.formNumber = -1;

   // Methods 
   //this.setPicked = SetPickedMonth;
   //this.setDisplayed = SetDisplayedMonth;
   //this.checkYear = CheckYearInput;
   //this.fixYear = FixYearInput;
   //this.changeMonth = CheckMonthChange;
   //this.changeDay = CheckDayChange;
   //this.resetTimer = CalTimerReset;
   //this.hideElements = SetElementStatus;
   this.show = ShowCalendar;
   //this.handleTimer = DoTimer;
   //this.iconHover = CalIconHover;
   //this.fixSelects = FixSelectLists;
   //this.setHidden = new Function('D','if (this.formNumber >= 0) this.getHiddenField().value=D');
   // Returns a reference to these elements
   //this.getHiddenField = new Function('return document.forms[this.formNumber].elements[this.hiddenFieldName]');
   //this.getMonthList = new Function('return document.getElementById(this.monthListID)');
   //this.getDayList = new Function('return document.getElementById(this.dayListID)');
   //this.getYearField = new Function('return document.getElementById(this.yearFieldID)');
   //this.getCalendar = new Function('return document.getElementById(this.calendarID)');
   //this.getDayTable = new Function('return document.getElementById(this.dayTableID)');
   //this.getCalendarLink = new Function('return document.getElementById(this.calendarLinkID)');
   //this.getMonthDisplay = new Function('return document.getElementById(this.monthDisplayID)');
}

*/