/*
Script: DatePickerTop.js

Autor:
	IntraCOM, <http://intracom.pl>

Info:
  Adaptacja skryptu DatePicker, użytego do wyboru daty w polach input. 
*/

var DatePickerTop = new Class({

  Implements: [Options,Events],
  
	options: {
		onShow: function(dp){
			dp.setStyle('visibility', 'visible');
		},
		onHide: function(dp){
			dp.setStyle('visibility', 'hidden');
		},
    data      : false,
    container : 't_kalendarz_tresc',
		bName     : 'menu1_mc',
    bPrev     : 't_miesiac_prev',
		bNext     : 't_miesiac_next',
    className : 'kalendarzyk',
		daysInMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
		monthNames: new Array('Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień'),
		dayNames  : new Array('Niedziela', 'Poniedziałek', 'Wtorek', 'Środa', 'Czwartek', 'Piątek', 'Sobota'),
		format: 'yyyy-mm-dd',
		yearStart: (new Date().getFullYear() - 20),
		yearRange: 21,
		yearOrder: 'asc',
		offsets: {'x':0, 'y':-4},
		width: 190,
		delay: 100,
		zIndex: 99999
	},
	
	/* setup the new DatePicker */
	initialize: function(el, options){
		
		this.setOptions(options);
		
		if ( ! $(this.options.container) && ! el ) { return; }
		
		this.bName = $(this.options.bName);
		this.bPrev  = $(this.options.bPrev);
		this.bNext  = $(this.options.bNext);
		
	  if ( this.options.data == false ) {
      d = new Date(); this.year = d.getFullYear(); this.month = d.getMonth(); this.day = d.getDate();
    }
    else {
      d = this.options.data.split('-'); this.year = d[0].toInt(); (this.month = d[1].toInt() - 1); this.day = d[2].toInt();
    }
		
		this.cur_year  = this.year;
		this.cur_month = this.month;
		
    this.element = el;
		this.active  = false;

		if (el.value.length > 9){
			switch (this.options.format){
				case 'mm/dd/yyyy': d = el.value.split('/'); this.year = d[2].toInt(); (this.month = d[0].toInt() - 1); this.day = d[1].toInt(); break;
				case 'yyyy-mm-dd': d = el.value.split('-'); this.year = d[0].toInt(); (this.month = d[1].toInt() - 1); this.day = d[2].toInt(); break;
				case 'yyyy.mm.dd': d = el.value.split('.'); this.year = d[0].toInt(); (this.month = d[1].toInt() - 1); this.day = d[2].toInt(); break;
				case 'mm.dd.yyyy': d = el.value.split('.'); this.year = d[2].toInt(); (this.month = d[0].toInt() - 1); this.day = d[1].toInt(); break;
				default: d = new Date(); this.year = d.getFullYear(); this.month = d.getMonth(); this.day = d.getDate(); break;
			}
		} else {
			d = new Date(); this.year = d.getFullYear(); this.month = d.getMonth(); this.day = d.getDate();
		}

		this.dp =  new Element('div', {
			'class': this.options.className + '',
			'styles': {
				'position':'absolute',
				'top':'0px',
				'left':'0px',
				'z-index':this.options.zIndex,
				'visibility':'hidden'
			}
		}).injectInside(document.body);
		this.wrapper = new Element('div', {
			'class':this.options.className + '-Wrapper',
			'styles': {
				'position':'absolute',
				'min-width':this.options.width + 'px'
			}
		}).injectInside(this.dp);

		this.setup();
	},
	
	setup: function(){
    this.element.set('autocomplete', 'off');
    this.element.addEvent('click', function(){
			this.position();
			this.build();
		}.bind(this));
		var destroy = this.destroy.bind(this);
		this.dp.addEvent('mouseleave', destroy);
	},

	/** build the calendar */
	build: function(){
    this.wrapper.empty();
		date = new Date();
		date.setFullYear(this.year, this.month, 1);
		this.year % 4 == 0 ? this.options.daysInMonth[1] = 29 : this.options.daysInMonth[1] = 28;
		var firstDay = 2 - date.getDay();

    /** przyciski następny/poprzedni miesiąc */
		var btnNext = new Element('img', {'src':'pics/ico/strzalka_1_p.gif','class':'bn','title':'następny miesiąc'});
		var btnPrev = new Element('img', {'src':'pics/ico/strzalka_1_l.gif','class':'bp','title':'poprzedni miesiąc'});

		btnNext.addEvent('click', function(event) {
			event.stopPropagation();
			this.nextMonth();
		}.bind(this));
		btnPrev.addEvent('click', function(event) {
			event.stopPropagation();
			this.prevMonth();
		}.bind(this));

    /** create the month select box */
		monthSel = new Element('select', {'class':this.options.className + '-monthSelect'});
		for (var m = 0; m < this.options.monthNames.length; m++){
			monthSel.options[m] = new Option(this.options.monthNames[m], m);
			if (this.month == m) monthSel.options[m].selected = true;
		}

		/** create the year select box */
		yearSel = new Element('select', {'class':this.options.className + '-yearSelect'});
		i = 0;
		if (this.options.yearOrder == 'desc'){
			for (var y = this.options.yearStart; y > (this.options.yearStart - this.options.yearRange - 1); y--){
				yearSel.options[i] = new Option(y, y);
				if (this.year == y) yearSel.options[i].selected = true;
				i++;
			}
		} else {
			for (var y = this.options.yearStart; y < (this.options.yearStart + this.options.yearRange + 1); y++){
				yearSel.options[i] = new Option(y, y);
				if (this.year == y) yearSel.options[i].selected = true;
				i++;
			}
		}

		/** start creating calendar */
		var calTable = new Element('table', {'styles':{'width':'100%'}}).injectInside(this.wrapper);
		var calTableTbody = new Element('tbody').injectInside(calTable);
		new Element('tr').adopt(new Element('td', {'class':'nav', 'styles':{'text-align':'center'}, 'colspan':'7'}).adopt(btnPrev).adopt(monthSel).adopt(yearSel).adopt(btnNext)).injectInside(calTableTbody);

		/** create day names */
		var calDayNameRow = new Element('tr').injectInside(calTableTbody);
		for (var i = 0; i < this.options.dayNames.length; i++){
			//klasa = ( i == 0 ) ? 'dayName n' : 'dayName';
			klasa = 'dayName';
			nazwa = (i<6) ? this.options.dayNames[i+1].substr(0, 1) : this.options.dayNames[0].substr(0, 1);
      calDayNameCell = new Element('td', {'class':klasa, 'styles':{'text-align':'center', 'width':'14%'}}).set('text', nazwa).injectInside(calDayNameRow);
		}

		/** create the day cells */
		date2 = new Date();
		while (firstDay <= this.options.daysInMonth[this.month]){
			calDayRow = new Element('tr').injectInside(calTableTbody);
			for (i = 0; i < 7; i++){
				klasa = ( i == 6 ) ? 'day n' : 'day';
        if ((firstDay <= this.options.daysInMonth[this.month]) && (firstDay > 0)){
					calDayCell = new Element('td', {'class':klasa, 'styles':{'cursor':'pointer', 'text-align':'center'}, 'axis':this.year + '-' + (this.month + 1) + '-' + firstDay}).set('text', firstDay).injectInside(calDayRow);
					if (date2.getFullYear() == this.year && date2.getMonth() == this.month && date2.getDate() == firstDay) calDayCell.addClass('current');
				} else {
					calDayCell = new Element('td', {'class':'empty'}).set('text', ' ').injectInside(calDayRow);
				}
				firstDay++;
			}
		}

		/** set the onclick events for all calendar days */
		$$('div.'+this.options.className+'-Wrapper td.day').each(function(d){
			d.addEvent('click', function(e){
				ds = d.axis.split('-');
				this.element.value = this.formatValue(ds[0], ds[1], ds[2]);
				this.hide();
      }.bind(this));
		}.bind(this));

		/** ukrywanie kalendarza */
    document.addEvent('click', function() {
  		if (!this.active) this.fireEvent('onHide', [this.dp]);
    }.bind(this));


		/** set the onchange event for the month & year select boxes */
		monthSel.onfocus = function(){ this.active = true; }.bind(this);
		monthSel.onblur = function(){ this.active = false; }.bind(this);
		monthSel.onchange = function(){
			this.month = monthSel.value.toInt();
			this.year = yearSel.value.toInt();
			this.active = false;
			this.build();
		}.bind(this);

		yearSel.onfocus = function(){ this.active = true; }.bind(this);
		yearSel.onblur = function(){ this.active = false; }.bind(this);
		yearSel.onchange = function(){
			this.month = monthSel.value.toInt();
			this.year = yearSel.value.toInt();
			this.active = false;
			this.build();
		}.bind(this);
		this.timer = this.show.delay(this.options.delay, this);
		
		this.wrapper.getChildren().addEvent('click', function(e) {
		 e.stopPropagation();
	  });
	},

	nextMonth: function(){
		if ( this.month == 11 ) {
			this.month = 0;
			this.year  = this.year + 1;
		}
		else {
			this.month++;
		}
		this.active = false;
		this.build();
	},

	prevMonth: function(){
		if ( this.month == 0 ) {
			this.month = 11;
			this.year  = this.year - 1;
		}
		else {
			this.month--;
		}
		this.active = false;
		this.build();
	},

	/* ustaw aktywny dzień */
	biezacaData: function(){
		var da  = this.year + '-';
        da += (this.month+1<10) ? '0'+(this.month+1) : (this.month+1);
        da += '-';
        da += (this.day<10) ? '0'+this.day : this.day;
	  return da;
  },

	/* ustaw aktywny dzień */
	setActive: function(td){
		if ( this.active ) {
      this.active.removeClass('active');
    }
    this.active = td;
    this.active.addClass('active');
	},

	/* destroy the calendar */
	destroy: function(event){
		$clear(this.timer);
		this.timer = this.hide.delay(this.options.delay, this);
	},

	/* position the calendar */
	position: function(){
		this.coords = this.element.getCoordinates();
		this.dp.setStyles({'top':(this.coords.top + this.options.offsets.y) + 'px', 'left':(this.coords.left + this.options.offsets.x) + 'px', 'width':this.coords.width + 'px', 'padding-top': this.coords.height + 'px'});
	},

	/* show the calendar */
	show: function(){
		this.fireEvent('onShow', [this.dp]);
	},

	/* hide the calendar */
	hide: function(){
		if (!this.active) this.fireEvent('onHide', [this.dp]);
	},

	/* format the returning date value */
	formatValue: function(year, month, day){
		var dateStr = '';

		if (day < 10) { day = '0' + day; }
		if (month < 10) { month = '0' + month; }

		dateStr = this.options.format.replace( /dd/i, day ).replace( /mm/i, month ).replace( /yyyy/i, year );
		this.month = month.toInt() - 1;
		this.year = year.toInt();

		return dateStr;
	}
});

