/*
my.php Calendar

Date Input 1.1.6
Requires jQuery version: 1.2.6
*/

DateInput_v2 = (function($) { // Localise the $ function

function DateInput_v2(el, opts) {

  if (typeof(opts) != "object") opts = {};
  $.extend(this, DateInput_v2.DEFAULT_OPTS, opts);

  this.input = $(el);
  this.bindMethodsToObj("show", "hide", "hideIfClickOutside", "selectDate", "prevMonth", "nextMonth");

  this.build();
  this.selectDate();
  //this.hide();
};
DateInput_v2.DEFAULT_OPTS = {
  month_names: ["styczeń", "luty", "marzec", "kwiecień","maj", "czerwiec", "lipiec", "sierpień", "wrzesień", "październik", "listopad", "grudzień"],
  short_month_names: ["sty", "lut", "mar", "kwi", "maj", "cze", "lip", "sie", "wrz", "paź", "lis", "gru"],
  short_day_names: ["nd", "pn", "wt", "śr", "cz", "pt", "so"],
  start_of_week: 1
};
DateInput_v2.prototype = {
  build: function() {
    this.monthNameSpan = $('<span class="month_name"></span>');
    var monthNav = $('<p class="month_nav"></p>').append(
      $('<a href="#" class="prev">&laquo;</a>').click(this.prevMonth),
      " ", this.monthNameSpan, " ",
      $('<a href="#" class="next">&raquo;</a>').click(this.nextMonth)
    );

	var tableShell = "<table><thead><tr>";
    $(this.adjustDays(this.short_day_names)).each(function() {
      tableShell += "<th>" + this + "</th>";
    });
	var data=new Date();
	var dzien=data.getDate();
	var miesiac=data.getMonth()
	var rok=data.getFullYear();
	miesiace_string = new Array('stycznia', 'lutego', 'marca', 'kwietnia', 'maja', 'czerwca', 'lipca', 'sierpnia', 'wrzeÅnia', 'paÅºdziernika', 'listopada', 'grudnia');

    tableShell += "</tr></thead><tbody></tbody></table>";
	tableShell += "<div style='width:160px; margin:21px 0px 0px 0px; font-size:14px; font-weight:bold; color:#BFBFBF; text-align:center;'>"+dzien+"&nbsp;"+miesiace_string[miesiac]+"&nbsp;"+rok+"</div>";
	//tableShell += "<div style='position:absolute;left:45px;top:145px;'><a href='javascript:void(0)' onclick=$('.date_selector_v2').hide()><img src='btn_cancel.png' border='0'></a></div>";
	//tableShell += "<div style='position:absolute;left:95px;top:145px;'><a href='javascript:void(0)' onclick=frm_calendar.submit()><img src='btn_ok.png' border='0'></a></div>";

    this.dateSelector = this.rootLayers = $('<div class="date_selector_v2"></div>').append(monthNav, tableShell).appendTo(".kalendarz");

    if ($.browser.msie && $.browser.version < 7) {
      this.ieframe = $('<iframe class="date_selector_ieframe_v2" style="display:none" frameborder="0" src="#"></iframe>').insertBefore(this.dateSelector);
      this.rootLayers = this.rootLayers.add(this.ieframe);
    };

    this.tbody = $("tbody", this.dateSelector);
    // The anon function ensures the event is discarded
    //this.input.change(this.bindToObj(function() { this.selectDate(); }));
  },

  selectMonth: function(date) {
    this.currentMonth = new Date(date.getFullYear(), date.getMonth(), 1);

    var rangeStart = this.rangeStart(date), rangeEnd = this.rangeEnd(date);
    var numDays = this.daysBetween(rangeStart, rangeEnd);
    var dayCells = "";

    for (var i = 0; i <= numDays; i++) {
      var currentDay = new Date(rangeStart.getFullYear(), rangeStart.getMonth(), rangeStart.getDate() + i);

      if (this.isFirstDayOfWeek(currentDay)) dayCells += "<tr>";

      if (currentDay.getMonth() == date.getMonth()) {
        dayCells += '<td date="' + this.dateToString(currentDay) + '"';
			if ((i+1)%7==0) dayCells +=' class="weekend"';
			if ((i+2)%7==0) dayCells +=' class="weekend"';
		dayCells += '><a href="#">' + currentDay.getDate() + '</a></td>';
      } else {
        dayCells += '<td class="unselected_month" date="' + this.dateToString(currentDay) + '"><a href="#">' + currentDay.getDate() + '</a></td>';
      };

      if (this.isLastDayOfWeek(currentDay)) dayCells += "</tr>";
    };

    this.monthNameSpan.empty().append(this.monthName(date) + " " + date.getFullYear());
    this.tbody.empty().append(dayCells);

    $("a", this.tbody).click(this.bindToObj(function(event) {
      //this.selectDate(this.stringToDate($(event.target).parent().attr("date")));
	  location.href="?date="+(this.dateToCal(this.stringToDateJs($(event.target).parent().attr("date"))));
      //this.hide();
      return false;
    }));

    $("td[date=" + this.dateToString(new Date()) + "]", this.tbody).addClass("today");
  },

  selectDate: function(date) {

	if (typeof(currentDate) == "undefined") {
      currentDate = this.stringToDate(this.dateToStringJs(new Date()));
    };

	var cd = currentDate.split("-");
	date = new Date(cd[0], cd[1]-1, cd[2]);
    if (date) {

      this.selectedDate = date;
      this.selectMonth(date);
      var stringDate = this.dateToString(date);
      $('td[date=' + stringDate + ']', this.tbody).addClass("today selected");

	 $('#inp_hidden_calendar').val(this.dateToStringPlus(date));

     if (this.input.val() != stringDate) {
        this.input.val(stringDate).change();
      };
    } else {
      this.selectMonth(new Date());
    };
  },

  show: function() {
    this.rootLayers.css("display", "block");
    this.setPosition();
    this.input.unbind("focus", this.show);
    $([window, document.body]).click(this.hideIfClickOutside);
  },

  hide: function() {
    this.rootLayers.css("display", "none");
    $([window, document.body]).unbind("click", this.hideIfClickOutside);
   this.input.click(this.show);
  },

  hideIfClickOutside: function(event) {
    if (event.target != this.input[0] && !this.insideSelector(event)) {
      this.hide();
    };
  },

  stringToDate: function(string) {
    var matches;
    if (matches = string.match(/^(\d{1,2}) ([^\s]+) (\d{4,4})$/)) {
      return new Date(matches[3], this.shortMonthNum(matches[2]), matches[1]);
    } else {
      return null;
    };
  },
  stringToDateJs: function(string) {
    var matches;
    if (matches = string.match(/^(\d{4,4})\.(\d{1,2})\.(\d{1,2})$/)) {
      return new Date(matches[1], matches[2], matches[3]);
    } else {
      return null;
    };
  },

  dateToString: function(date) {
    return date.getFullYear()+"."+date.getMonth()+"."+date.getDate();
  },
  dateToStringPlus: function(date) {
    return date.getFullYear()+"."+(date.getMonth()+1)+"."+date.getDate();
  },
  dateToCal: function(date) {
    m = date.getMonth();
    d = date.getDate();
    m++;
    if(m<10) m='0'+m;
    if(d<10) d='0'+d;

    return date.getFullYear()+""+m+""+d;
  },

  dateToStringJs: function(date) {
    return date.getDate() + " " + this.short_month_names[date.getMonth()] + " " + date.getFullYear();
  },

  setPosition: function() {
    var offset = this.input.offset();
    this.rootLayers.css({
      top: offset.top + this.input.height() - 10,
      left: offset.left - 155
    });

    if (this.ieframe) {
      this.ieframe.css({
        //width: this.dateSelector.outerWidth(),
        //height: this.dateSelector.outerHeight()
      });
    };
  },

  moveMonthBy: function(amount) {
    this.selectMonth(new Date(this.currentMonth.setMonth(this.currentMonth.getMonth() + amount)));
  },

  prevMonth: function() {
    this.moveMonthBy(-1);
    return false;
  },

  nextMonth: function() {
    this.moveMonthBy(1);
    return false;
  },

  monthName: function(date) {
    return this.month_names[date.getMonth()];
  },

  insideSelector: function(event) {
    var offset = this.dateSelector.offset();
    offset.right = offset.left + this.dateSelector.width();
    offset.bottom = offset.top + this.dateSelector.height();

    return event.pageY < offset.bottom &&
           event.pageY > offset.top &&
           event.pageX < offset.right &&
           event.pageX > offset.left;
  },

  bindToObj: function(fn) {
    var self = this;
    return function() { return fn.apply(self, arguments) };
  },

  bindMethodsToObj: function() {
    for (var i = 0; i < arguments.length; i++) {
      this[arguments[i]] = this.bindToObj(this[arguments[i]]);
    };
  },

  indexFor: function(array, value) {
    for (var i = 0; i < array.length; i++) {
      if (value == array[i]) return i;
    };
  },

  monthNum: function(month_name) {
    return this.indexFor(this.month_names, month_name);
  },

  shortMonthNum: function(month_name) {
    return this.indexFor(this.short_month_names, month_name);
  },

  shortDayNum: function(day_name) {
    return this.indexFor(this.short_day_names, day_name);
  },

  daysBetween: function(start, end) {
    start = Date.UTC(start.getFullYear(), start.getMonth(), start.getDate());
    end = Date.UTC(end.getFullYear(), end.getMonth(), end.getDate());
    return (end - start) / 86400000;
  },

  changeDayTo: function(to, date, direction) {
    var difference = direction * (Math.abs(date.getDay() - to - (direction * 7)) % 7);
    return new Date(date.getFullYear(), date.getMonth(), date.getDate() + difference);
  },

  rangeStart: function(date) {
    return this.changeDayTo(this.start_of_week, new Date(date.getFullYear(), date.getMonth()), -1);
  },

  rangeEnd: function(date) {
    return this.changeDayTo((this.start_of_week - 1) % 7, new Date(date.getFullYear(), date.getMonth() + 1, 0), 1);
  },

  isFirstDayOfWeek: function(date) {
    return date.getDay() == this.start_of_week;
  },

  isLastDayOfWeek: function(date) {
    return date.getDay() == (this.start_of_week - 1) % 7;
  },

  adjustDays: function(days) {
    var newDays = [];
    for (var i = 0; i < days.length; i++) {
      newDays[i] = days[(i + this.start_of_week) % 7];
    };
    return newDays;
  }
};

$.fn.date_input_v2 = function(opts) {
  return this.each(function() { new DateInput_v2(this, opts); });
};
$.date_input_v2 = { initialize: function(opts) {
  $("input.date_input_v2").date_input_v2(opts);
} };

return DateInput_v2;
})(jQuery); // End localisation of the $ function
