
Chiri = {version:"1.0"}

/****************************************************************
 * Chiri.Datepicker                                             *
 ****************************************************************/

var dpCounter = 0;
var dpObjects = new Object;

var defaultLocale = {
      fullMonths:["January","February","March","April","May","June","July","August","September","October","November","December"],
      monthAbbrs:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],
      fullDays:  ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],
      dayAbbrs:  ["Mo","Tu","We","Th","Fr","Sa","Su"],
      titles:    ["Previous month","Next month","Previous year","Next year", "Today", "Show Calendar", "Cw", "Week [[%0%]] of [[%1%]]", "Week", "Select a date", "Click \u0026 Drag to move", "Display \u201C[[%0%]]\u201D first", "Go to Today\u2019s date", "Disabled date"],
      imported:  false
};

Date.prototype.getWeek = function(dowOffset) {
  dowOffset = (typeof(dowOffset) == 'int') ? dowOffset : 1;
  var newYear = new Date(this.getFullYear(), 0, 1);
  var day = newYear.getDay() - dowOffset;
  day = (day >= 0) ? day : (day + 7);
  var daynum = Math.floor((this.getTime() - newYear.getTime() - (this.getTimezoneOffset() - newYear.getTimezoneOffset()) *60000) / 86400000) + 1;
  var weeknum;
  
  /* if the year starts before the middle of a week */
  if(day < 4) {
    weeknum = Math.floor((daynum + day - 1) / 7) + 1;
    if(weeknum > 52) {
      nYear = new Date(this.getFullYear() + 1, 0, 1);
      nday = nYear.getDay() - dowOffset;
      nday = (nday >= 0) ? nday : (nday + 7);
      /*if the next year starts before the middle of the week, it is week #1 of that year*/
      weeknum = nday < 4 ? 1 : 53;
    }
  }else{
    weeknum = Math.floor((daynum + day -1) / 7);
    if(weeknum == 0){
      return new Date(this.getFullYear() - 1, 11, 31).getWeek();      
    }
  }
  return weeknum;
} 

Chiri.Datepicker = Class.create({
  initialize: function(element, options) {
    this.const_MONTH = 'month';
    this.const_YEAR = 'year';
    
    this.element = $(element);
    this.marks = new Object;
    this.selectedDate = null;
    
    this.options = {
        column: 1,
        timeSelect: false,
        hour: null,
        minute: null,
        startDate: null,
        endDate: null,
        blnSimulateOnChange: false
    };
    
    Object.extend(this.options, options || { });
        
    if(this.options.startDate !== null){
      this.options.startDate = new Date(this.options.startDate);
    }
    
    if(this.options.endDate !== null){
      this.options.endDate = new Date(this.options.endDate);
    }
    
    if($F(this.element).blank() == false){
      var arrDate = $F(this.element).split('.');
      //var arrDate = $F(this.element).split('/');
      if(!isNaN(arrDate[2])){
        this.date = new Date(arrDate[2], arrDate[0] - 1, arrDate[1]);        
        this.selectedDate = new Date(this.date.getFullYear(), this.date.getMonth(), this.date.getDate());
      }else{
        this.date = new Date();
      }
    }else{
      this.date = new Date();
    }
    
    this.today = new Date();
    this.today = new Date(this.today.getFullYear(), this.today.getMonth(), this.today.getDate());
    
    dpCounter++;
    this.dpCounter = dpCounter;
    
    this.initControl();
    
    dpObjects['dp'+this.dpCounter] = this;
    
    //has a locale file to load
    if(typeof(dpLocale) == 'object'){
      this.locale = {
            fullMonths      : dpLocale.fullMonths,                  
            monthAbbrs      : dpLocale.monthAbbrs,
            fullDays        : dpLocale.fullDays,
            dayAbbrs        : dpLocale.dayAbbrs,
            titles          : dpLocale.titles,
            imported        : true
      }; 
    }else{
      this.locale = defaultLocale;
    }
  },

  initControl: function(){
    var control = new Element('div', {'class': 'date-picker'});
        
    control.insert(new Element('div', {'class': 'date-picker-input'}).update($(this.element).cloneNode(true)), { position: 'bottom' });
    control.insert(new Element('div', {'class': 'date-picker-control'}).update(new Element('div', { 'class': 'date-picker-controler', 'id': 'dpc'+this.dpCounter})), { position: 'bottom' });
        
    if(this.options.timeSelect == true){
      var hasTimeSelected = (this.options.hour > 0 || this.options.minute > 0) ? true : false;
      var hourSelect = new Element('select', {'name': $(this.element).readAttribute('name') + 'Hour'});
      hourSelect.insert(new Element('option', {'value': ''}).update('- -'));
      for(h = 0; h < 24; h++){
        hDispaly = (h > 9) ? h : '0' + String(h);
        if(this.options.hour == h && hasTimeSelected){
          hourSelect.insert(new Element('option', {'value': h, 'selected': 'selected'}).update(hDispaly));
        }else{
          hourSelect.insert(new Element('option', {'value': h}).update(hDispaly));
        }        
      }
      
      var timeSelect = new Element('div', {'class': 'date-picker-time-select'}).update(hourSelect);
      timeSelect.insert(new Element('span').update(':'), { position: 'bottom' });
      
      var minSelect = new Element('select', {'name': $(this.element).readAttribute('name') + 'Minute'});
      minSelect.insert(new Element('option', {'value': ''}).update('- -'));
      for(m = 0; m < 60; m = m + 5){
        mDispaly = (m > 9) ? m : '0' + String(m);
        if(this.options.minute == m && hasTimeSelected){
          minSelect.insert(new Element('option', {'value': m, 'selected': 'selected'}).update(mDispaly));
        }else{
          minSelect.insert(new Element('option', {'value': m}).update(mDispaly));
        }
      }
      
      timeSelect.insert(minSelect, { position: 'bottom' });
      
      control.insert(timeSelect, { position: 'bottom' });
    }
    
    control.insert(new Element('div', {'class': 'clear'}), { position: 'bottom' });
        
    var dpContainer = new Element('div', {'class': 'date-picker-calendar-container dp' + this.options.column + 'col'});
        
    dpContainer.insert(new Element('div', {'class': 'date-picker-next', 'id': 'dpGetNext'+this.dpCounter}).update('<img src="/website/themes/mohrenbrauerei/images/pointer_small_right.gif"/>'));
    dpContainer.insert(new Element('div', {'class': 'date-picker-previous', 'id': 'dpGetPrevious'+this.dpCounter}).update('<img src="/website/themes/mohrenbrauerei/images/pointer_small_left.gif"/>'));
    dpContainer.insert(new Element('div', {'class': 'clear'}), { position: 'bottom' });
        
    dpContainer.insert(new Element('div', {'id': 'dpcc'+this.dpCounter}), { position: 'bottom' });
        
    control.insert(new Element('div', { 'class': 'date-picker-calendar-wrapper', 'id': 'dp'+this.dpCounter, 'style': 'display: none;'}).update(dpContainer), { position: 'bottom' });
        
    this.element.up().update(control);
    this.element = $(this.element.id);
    
    // set color to black
    $(this.element.id).setStyle({color: '#000000'});

    //get calendar
    $('dpc'+this.dpCounter).observe('click', function(event){
      this.getCalendar();
    }.bind(this));
    
    //input change
    $(this.element).observe('change', function(event){
      this.inputChange();
    }.bind(this));
    
    //get next month
    $('dpGetNext'+this.dpCounter).observe('click', function(event){
      this.getNext(this.const_MONTH);
    }.bind(this));
        
    //get previous month
    $('dpGetPrevious'+this.dpCounter).observe('click', function(event){
      this.getPrevious(this.const_MONTH);
    }.bind(this));
  },
    
  getCalendar: function(){
    if($('dpcc'+this.dpCounter).empty()){
      this.buildCalendar();
    }
    this.toggleDatePicker();
  },

  getNext: function(unittype){
    switch(unittype) {
      case this.const_MONTH:
        this.date.setDate(1);
        this.date.setMonth(this.date.getMonth() + 1);
        break;
      case this.const_YEAR:
        this.date.setDate(1);
        this.date.setFullYear(this.date.getFullYear() + 1);
        break;
    }
    this.buildCalendar();
  },
    
  getPrevious: function(unittype){
    switch(unittype) {
      case this.const_MONTH:
        this.date.setDate(1);
        this.date.setMonth(this.date.getMonth() - 1);
        break;
      case this.const_YEAR:
        this.date.setDate(1);
        this.date.setFullYear(this.date.getFullYear() - 1);
        break;
      }
    this.buildCalendar();
  },
    
  buildCalendar: function(){
    $('dpcc'+this.dpCounter).update('');
        
    this.calendar = new Object;
        
    //prepare calender data
    this.calendar['Month'] = new Object;

    for(n=1; n<=this.options.column; n++){
      var tmpDate = new Date(this.date.getFullYear(), Number(this.date.getMonth()) + (n - 1), this.date.getDate());
      var tmpMonth = tmpDate.getMonth();

      this.calendar['Month'][tmpMonth] = new Object;
      this.calendar['Month'][tmpMonth]['Week'] = new Object;
      for(i=1; i<=31; i++){
        tmpDate.setDate(i);
        if(tmpDate.getMonth() == tmpMonth){
          if(!this.calendar['Month'][tmpMonth]['Week'][tmpDate.getWeek()]){
            this.calendar['Month'][tmpMonth]['Week'][tmpDate.getWeek()] = new Object;
            this.calendar['Month'][tmpMonth]['Week'][tmpDate.getWeek()]['Day'] = [];
          }
          this.calendar['Month'][tmpMonth]['Week'][tmpDate.getWeek()]['Day'].push(tmpDate.getTime());
        }
      }
    }
    
    //now render calendar data
    for(var month in this.calendar['Month']){
      var leading = true;
      
      //create month tbody
      var mTbody = new Element('tbody');
      for(var week in this.calendar['Month'][month]['Week']){
        
        //create tr with calendar week number
        dWeek = (Number(week) > 9) ? week : '0' + String(week);
        var wTr = new Element('tr').update(new Element('td', {'class': 'cw'}).update(new Element('span').update(dWeek)));
        
        var dayInWeek = this.calendar['Month'][month]['Week'][week]['Day'].length;

        //add leading emtpy td's
        if(dayInWeek != 7 && leading == true){
          for(var l = 0; l < (7 - dayInWeek); l++) {
            wTr.insert(new Element('td').update('&nbsp;'), { position: 'bottom' });
          }                   
        }
            
        //add day
        for(var i = 0; i < dayInWeek; i++) {
          var myDate = new Date(Number(this.calendar['Month'][month]['Week'][week]['Day'][i]));
          var day = myDate.getDate();
          var isSelectable = true;
          var spanCssClass = 'selectable';
          var spanTitle = '';
          var tdCssClass = '';
        
          //check if date is selectable by startDate
          if(this.options.startDate != null && this.options.startDate.getTime() > myDate.getTime()){
            spanCssClass = 'unselectable';
            isSelectable = false; 
          }
          
          //check if date is selectable by endDate         
          if(this.options.endDate != null && this.options.endDate.getTime() < myDate.getTime()){
            spanCssClass = 'unselectable';
            isSelectable = false;
          }
          
          //check if date is a marked day
          if(this.marks[myDate.getTime()]){
            tdCssClass = this.marks[myDate.getTime()]['marker'] + ' dpmarker';
            spanTitle = this.marks[myDate.getTime()]['title'];
          }
          
          //check if date is the selected day
          if(this.selectedDate != null && myDate.getTime() == this.selectedDate.getTime()){
            tdCssClass = 'selected';
          }
          
          //check if date is today
          if(myDate.getTime() == this.today.getTime()){
            tdCssClass = tdCssClass + ' today';            
          }
        
          var dayEl = new Element('span', {'id': this.element.id+'_'+myDate.getTime() , 'class': spanCssClass, 'title': spanTitle}).update(day);
                  
          if(isSelectable === true){
            dayEl.observe('click', function(event){   
              var el = Event.element(event);
              this.selectDate(el.id);
            }.bind(this));
          }
        
          //check weekend
          if(myDate.getDay() == 6 || myDate.getDay() == 0){
            tdCssClass = tdCssClass + ' weekend';   
          }

          wTr.insert(new Element('td', {'class': tdCssClass}).update(dayEl), { position: 'bottom' });                 
        }
              
        //add closing emtpy td's
        if(dayInWeek != 7 && leading == false){
          for(var c = 0; c < (7 - dayInWeek); c++) {
            wTr.insert(new Element('td').update('&nbsp;'), { position: 'bottom' });
          }                   
        }
              
        //add week
        mTbody.insert(wTr);
        leading = false;
      }
          
      //create month header           
      var hTr = new Element('tr');
      hTr.insert(new Element('td', {'class': 'cw'}).update(this.locale.titles[6]), { position: 'bottom' });
      for(var e = 0; e < 7; e++) {
        if(e == 5 || e == 6){
          hTr.insert(new Element('td', {'class': 'weekend'}).update(this.locale.dayAbbrs[e]), { position: 'bottom' });
        }else{
          hTr.insert(new Element('td').update(this.locale.dayAbbrs[e]), { position: 'bottom' });
        }
      }
      var mThead = new Element('thead').update(hTr);
      
      //create table
      var mTable = new Element('table');
      mTable.insert(mThead, { position: 'bottom' });
      mTable.insert(mTbody, { position: 'bottom' });
      
      //create month control
      var mControl = new Element('div', { 'class': 'date-picker-calendar'});
      mControl.insert(new Element('div', { 'class': 'date-picker-month'}).update(this.locale.fullMonths[month] + ' ' + myDate.getFullYear()), { position: 'bottom' });
      mControl.insert(mTable, { position: 'bottom' });
      
      //add month to output
      $('dpcc'+this.dpCounter).insert(mControl, { position: 'bottom' });
    }
      
    //add div clear
    $('dpcc'+this.dpCounter).insert(new Element('br', {'class': 'clear'}), { position: 'bottom' });
      
    $$('.dpmarker').each(function(element){
      if(element.down().title && element.down().title != '' && typeof(Tip) != 'undefined'){
        new Tip(element, element.down().title, { className: 'tooltip1', effect: 'appear'});
        element.down().title = '';
      }
    });
  },
    
  selectDate: function(time){
    time = time.substr(this.element.id.length+1);
    
    //remove the css class 'selected' from the old selected date
    if(this.selectedDate != null && $(String(this.element.id+'_'+this.selectedDate.getTime()))){
      $(String(this.element.id+'_'+this.selectedDate.getTime())).up().removeClassName('selected');
    }
    
    //add the css class 'selected' to the selected date
    if($(this.element.id+'_'+time)){
      $(this.element.id+'_'+time).up().addClassName('selected');
    }
    
    //set new selected date
    this.selectedDate = new Date(Number(time));
    
    d = (Number(this.selectedDate.getDate()) > 9) ? String(this.selectedDate.getDate()) : '0' + String(this.selectedDate.getDate());
    m = ((Number(this.selectedDate.getMonth()) + 1) > 9) ? String(Number(this.selectedDate.getMonth()) + 1) : '0' + String(Number(this.selectedDate.getMonth()) + 1);
    Y = String(this.selectedDate.getFullYear());
    
    //dispaly new selected date
    this.element.value =  d + '.' + m + '.' + Y;
    //this.element.value =  m + '/' + d + '/' + Y;
    
    // set color to black
    $(this.element).setStyle({color: '#000000'});
    
    //toggle date picker calendar
    this.toggleDatePicker();
    
    //execute onchange function of field
    if(this.options.blnSimulateOnChange){
      $(this.element).onchange();
    }
  },
  
  inputChange: function(){
    if($F(this.element).blank() == false){
      var arrDate = $F(this.element).split('.');
      var tmpDate = new Date(Number(arrDate[2]), Number(arrDate[1] - 1), Number(arrDate[0]));
      //var arrDate = $F(this.element).split('/');
      //var tmpDate = new Date(Number(arrDate[2]), Number(arrDate[0] - 1), Number(arrDate[1]));
      
      if((Number(tmpDate.getDate()) == Number(arrDate[1]) && Number(tmpDate.getMonth() + 1) == Number(arrDate[0])) &&
         (this.options.startDate == null || this.options.startDate.getTime() <= tmpDate.getTime()) && 
         (this.options.endDate == null || this.options.endDate.getTime() >= tmpDate.getTime())){
        this.selectedDate = tmpDate;
        this.date = tmpDate;
        this.buildCalendar();
      }else if(this.selectedDate && !isNaN(this.selectedDate.getDate())){
        d = (Number(this.selectedDate.getDate()) > 9) ? String(this.selectedDate.getDate()) : '0' + String(this.selectedDate.getDate());
        m = ((Number(this.selectedDate.getMonth()) + 1) > 9) ? String(Number(this.selectedDate.getMonth()) + 1) : '0' + String(Number(this.selectedDate.getMonth()) + 1);
        Y = String(this.selectedDate.getFullYear());
        
        //dispaly new selected date
        this.element.value =  d + '.' + m + '.' + Y;
        //this.element.value = m + '/' + d + '/' + Y;
        new Effect.Highlight(this.element, {startcolor:'#ffcc00', duration: 0.25});
      }else{
        this.element.value = '';
        new Effect.Highlight(this.element, {startcolor:'#ffcc00', duration: 0.25});
      }
    }
  },
  
  addMark: function(date, marker, title){
    markerDate = new Date(date);
    
    if(!isNaN(markerDate.getDate())){
      markerDate = new Date(markerDate.getFullYear(), markerDate.getMonth(), markerDate.getDate());
      this.marks[markerDate.getTime()] = new Object();
      this.marks[markerDate.getTime()]['marker'] = marker;
      this.marks[markerDate.getTime()]['title'] = title;
    }
  },
  
  toggleDatePicker: function(){
      Effect.toggle('dp'+this.dpCounter, 'slide', {duration: 0.5});
  }
});

/****************************************************************
 * Chiri.Ajax.Autocompleter                                     *
 ****************************************************************/

Chiri.Autocompleter = {};        
Chiri.Autocompleter.Base = Class.create(Autocompleter.Base, {
  initialize: function() {
    this.currElementValue = '';
  },
  
  onClick: function(event) {
    var element = Event.findElement(event, 'LI');
    this.index = element.autocompleteIndex;
    this.hide();
  },
  
  onBlur: function(event) {
    setTimeout(this.hide.bind(this), 250);
    if(this.element.value != ''){
      if(this.update.firstChild && this.update.firstChild.childNodes[this.index].innerHTML != this.element.value){
        this.selectEntry();
      }else if(this.currElementValue != this.element.value){
        this.selectEntry(); 
      }
    }
    this.currElementValue = this.element.value;
    this.hasFocus = false;    
    this.active = false;
  }
});

Chiri.Ajax = {};        
Chiri.Ajax.Autocompleter = Class.create(Chiri.Autocompleter.Base, {
  initialize: function(element, update, url, options) {
    this.baseInitialize(element, update, options);
    this.options.asynchronous  = true;
    this.options.onComplete    = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;
    this.url                   = url;
  },

  getUpdatedChoices: function() {
    this.startIndicator();

    var entry = encodeURIComponent(this.options.paramName) + '=' +
      encodeURIComponent(this.getToken());

    this.options.parameters = this.options.callback ?
      this.options.callback(this.element, entry) : entry;

    if(this.options.defaultParams)
      this.options.parameters += '&' + this.options.defaultParams;

    new Ajax.Request(this.url, this.options);
  },

  onComplete: function(request) {
    this.updateChoices(request.responseText);
  }
});
