/*
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 : 'DatePicker', 
		daysInMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
		monthNames: ['Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień'],
		dayNames  : ['Niedziela', 'Poniedziałek', 'Wtorek', 'Środa', 'Czwartek', 'Piątek', 'Sobota'],
		format: 'yyyy-mm-dd',
		yearStart: (new Date().getFullYear() - 60),
		yearRange: 61,
		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;
		
		if ( 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 + '-Container',
  			'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(el);
	},
	
	/* setup the calendar */
	setup: function(el){
    if ( el ) {
      this.setupEl(el);
      return;
    }

    /*następny miesiąc*/
    this.bNext.addEvent('click', function() {
  		if ( this.month == 11 ) {
        this.month = 0;
        this.year = this.year + 1;
      }
      else {
        this.month = this.month + 1;
      }
      this.build();
    }.bind(this));
    
    /*poprzedni miesiąc*/
		this.bPrev.addEvent('click', function() {
  		if ( this.month == 0 ) {
        this.month = 11;
        this.year = this.year - 1;
      }
      else {
        this.month = this.month - 1;
      }
      this.build();
    }.bind(this));
    
    /*bieżący miesiąc*/
		this.bName.addEvent('click', function() {
  		if ( this.year == this.cur_year && this.month == this.cur_month ) {
        return;
      }
      this.year  = this.cur_year;
  		this.month = this.cur_month;
      this.build();
    }.bind(this));
    
    this.build();
	}, 

	setupEl: function(el){
		el.addEvent('click', function(){
			this.position(el);
			this.build(el);
		}.bind(this));
		var destroy = this.destroy.bind(this);
		this.dp.addEvent('mouseleave', destroy);
	},

	/* build the calendar */
	build: function(el){
    if ( el ) {
      this.buildEl(el);
      return;
    }
    
		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 = (date.getDay()==0) ? -5 : 2 - date.getDay();
		
		/* start creating calendar */
	  $(this.options.bName).set('html', this.options.monthNames[this.month]+' <span>'+this.year+'</span>');
		calTableTbody = $(this.options.container);
		calTableTbody.empty();
		
		/* 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 ) ? 'dzien niedziela' : 'dzien';
        if ((firstDay <= this.options.daysInMonth[this.month]) && (firstDay > 0))
        {
					this.day = firstDay;
					da = this.biezacaData();
          calDayCell = new Element('td', {'class':klasa, 'styles':{'text-align':'center'}, 'title':da, 'id':'t_'+da}).set('html', firstDay).injectInside(calDayRow);
					if (date2.getFullYear() == this.year && date2.getMonth() == this.month && date2.getDate() == firstDay) calDayCell.addClass('dzis');
				} 
        else {
					calDayCell = new Element('td', {'class':'none'}).set('html', ' ').injectInside(calDayRow);
				}
				firstDay++;
			}
		}
		
		/* pobierz zadania z danego miesiąca */
    var url  = '/ajax2/wydarzenia_w_miesiacu/' + this.biezacaData() + '.html';
    new Ajax(url, {
    		method: 'get',
				useWaiter: true,
				waiterOptions: {},
				waiterTarget: this.options.container,
    		onComplete: function(a) {
          if ( a == '' ) {
            return;
          }
					a = a.split('<p>');	/* bo 1,2,...<p><div>wyd1</div><span><div>wyd2</div><span>...*/
					// legenda
					if ( a[2] && $('kalendarium-legenda') && $('kalendarium-legenda').get('html') == '' ) {
						$('kalendarium-legenda').set('html', a[2]);
					}
          var dni   = a[0].split(',');
					var newsy = a[1].split('<span>');
          dni.each(function(d){
            this.day = d;
            var dz = this.biezacaData();
						var td = $('t_'+dz);
            if ( td )
						{
              /* dodaj tekst do tips-a*/
							var txt = '';
							for(i=0; i<newsy.length; i++) {
								if ( newsy[i].indexOf(dz) != -1 ) {
									txt += newsy[i];
                  /* dodaj kolorystyczne oznaczenie rodzaju wydarzeń */
                  var kolor = newsy[i].substring(newsy[i].indexOf('kolor="')+7, newsy[i].indexOf('kolor="')+7+6);
                  if ( kolor.test("^[A-Z0-9]{6}$") ) {
                    if ( !td.getElement('div') ) {
                      var divKolor = new Element('div', {
                        'styles': {
                          'height': '2px',
                          'background': '#' + kolor,
                          'margin': '0',
                          'border': '1px solid #' + kolor,
                          '-moz-border-radius': '3px',
                          'border-radius': '3px'
                        }
                      });
                      divKolor.inject(td, 'top');
                      td.setStyle('padding-top', 0);
                      //td.setStyle('border', '#'+ kolor +' solid 1px');
                    }
                  }
								}
							}
							td.store('tip:text', txt);
							kalendarz_tips.attach(td);
							td.removeEvent('mouseleave', td.retrieve('tip:leave') || $empty);

              /* ustaw odp. klasy, kolor itp. */
              if ( td.hasClass('niedziela') )
								td.addClass('niedziela_active');
							else
								td.addClass('day_active');
							td.setStyle('cursor', 'pointer');
							td.onclick = function(dz) {
								location.href = '/main/kalendarium,'+ this.get('id').substr(2) +'.html';
							};
						}
          }.bind(this));
        }.bind(this)    		
    	}).request();
	},	

	/** build the calendar */
	buildEl: function(el){
    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(el);
		}.bind(this));
		btnPrev.addEvent('click', function(event) {
			event.stopPropagation();
			this.prevMonth(el);
		}.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 */
		calTable = new Element('table', {'styles':{'width':'100%'}}).injectInside(this.wrapper);
		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 */
		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.DatePicker-Wrapper td.day').each(function(d){
			d.onclick = function(){
				ds = d.axis.split('-');
				el.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(el);
		}.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(el);
		}.bind(this);
		this.timer = this.show.delay(this.options.delay, this);
		
		this.wrapper.getChildren().addEvent('click', function(e) {
		 e.stopPropagation();
	  });
	},

	nextMonth: function(el){
		if ( this.month == 11 ) {
			this.month = 0;
			this.year  = this.year + 1;
		}
		else {
			this.month++;
		}
		this.active = false;
		this.build(el);
	},

	prevMonth: function(el){
		if ( this.month == 0 ) {
			this.month = 11;
			this.year  = this.year - 1;
		}
		else {
			this.month--;
		}
		this.active = false;
		this.build(el);
	},

	/* 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(el){
		this.coords = el.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;
	}
});

