/*
 *  Datumovnik, vytvori objekt datumovnik, ktery vyplni nejaky input type="text"
 *  vybranym datem z kalendare
 *
 *  btw. tenhle soubor rozhodne neni chraneny jakymikoli pravy ci cimkoli jinym,
 *  jenom si nepreju, aby s nim jakkoli manipuloval anebo nakladal, jakysi
 *  peta (tusim, ze se jmenuje Petr Milch) vyskytujici se na diskusi jakpsatweb
 *  
 *  venca
 *  
 *  instacni datumovniku vytvorite nasledovne:
 *  
 *  datumovnik = new Tdatumovnik('idElementuInput');   
 *
 *  kde idElementuInput je id elementu input, do ktereho se bude vkladat
 *  vybrane datum. Davejte pozor aby jste instanci vytvareli az nekde pod tim
 *  elementem, aby se nestelo, ze se pokusite kolem inputu neco vlozit do
 *  dokumentu (tlacitko v contructoru) a pritom zadny input jeste nebude 
 *  existovat.    
 * 
 *  co potrebujete nastavit, je vlastnos:
 *
 *  tableClass - coz je trida stylu tabulky datumovniku
 * 
 *  a pokud chcete jiny, hezci tlacitko, tak v conructoru najdete vlastnost:
 *  
 *  this.buttonId
 *    
 *  a upravte jeji vlastnosti, treba na .type='image' prihodte jeste 
 *   .src='mujobrazek' a mate hezke obrazkove tlacitko
 */    

/* globalni promenna, zahrnujici objekty datumovniku */
if (!Objekty) {var Objekty = [];};


/* objekt Tdatumovnik */
function Tdatumovnik(linkElementId)
{
  /* properties */
  this.linkElementId = linkElementId; // id input type text prvku na ktery bude datumovnik nalepeny
  this.id = 0; // id datumovniku v seznamu objektu 'Objekty'

  this.tableClass = 'datumovnik'; // class stylu tabulky datumovniku

  this.today = new Date();

  this.currentDay = this.today.getDate(); // aktualni den v mesici 1-31
  this.currentWeekDay = this.today.getDay(); // aktualni den v tydnu 0-6
  this.currentMonth = this.today.getMonth(); // aktualni mesic 0-11
  this.currentYear = this.today.getFullYear(); // aktualni rok
  
  this.nDays = new Array('Pondělí', 'Úterý', 'Středa', 'Čtvrtek', 'Pátek', 'Sobota', 'Neděle');
  this.nShDays = new Array('Po', 'Út', 'St', 'Čt', 'Pá', 'So', 'Ne');
  this.nMonths = new Array('Leden', 'Únor', 'Březen', 'Duben', 'Květen', 'Červen', 'Červenec', 'Srpen', 'Září', 'Říjen', 'Listopad', 'Prosinec');

  this.show = false; // pokud je true, datumovnik se zobrazi
  
  this.tableId = null; // id zobrazene tabulky, drzim ho abych ji mohl pripadne zrusit
  this.buttonId = null; // tlacitko zobrazujici a skryvajici kalendar
  
  /* constructor */
  this.constructor = function()
  {
    this.id = Objekty.length;
    Objekty[this.id] = this;
    
    //vytvoreni tlacitka
    this.buttonId = document.createElement('input');
    this.buttonId.type='button';
    this.buttonId.value='Kalendář';
    this.buttonId.style.width='70px';
    this.buttonId.style.margin='0px 0px 0px 5px';
    this.buttonId.clickFunc = 'Objekty['+this.id+'].showHide(this);';
    this.buttonId.onclick = function() {eval(this.clickFunc)}
        
    // appendovani tlacitka do dokumentu
    var masterId=document.getElementById(this.linkElementId);
    if(masterId)
      this.insertAfter(masterId, this.buttonId);
/*      masterId.parentNode.appendChild(this.buttonId);*/
    else
      document.body.appendChild(this.buttonId);

  }
  
  /* zobrazi skryje datumovnik */
  this.showHide = function()
  {
    if(this.show)
      this.show = false;
    else
      this.show = true;
  
    this.refresh();
  }

  /* vrati nasledujiciho potomka */
  this.insertAfter = function( child, insert)
  {
    var parent = child.parentNode;
    if (parent.hasChildNodes())
    {
      var children = parent.childNodes;
      var found = child;
      var f = false;
      for (var i = 0; i < children.length; i++) 
      {
        if (f) found = children[i];
        if ((children[i]==child)&&(i != children.length-1)) f = true; 
      };
    }  
    
    // pokud najdeme dalsi dite, vlozime pred nej, jinak za nej
    if(f)
    {
      parent.insertBefore(insert, found);    
    } else
    {
      parent.appendChild(insert);    
    }
    
  }


  /* vrati pole dni v mesici, slouzi potom pro vykresleni tabulky */
  this.getMonthArr = function()
  {
    var result = new Array();
  
    // zjistime kolikaty den v tydnu je prvni den v mesici
    var datum = new Date();
    datum.setYear(this.currentYear); 
    datum.setMonth(this.currentMonth);
    datum.setDate(1); // prvni den
    // kolikaty v tydnu, pokud je napriklad paty, musime pridat ctyri prazdna policka
    var offset = (datum.getDay()); 
    if (offset==0) offset=7; //nedele
    for(var i=1;i<offset;i++)
    {
      result.push('');
    }
    
    // procestujeme vsechny dny v danem mesici
    for(var i=0;i<31;i++)
    {
      datum.setDate(i+1);
      if(this.currentMonth==datum.getMonth()) result.push(datum.getDate());
    }
  
    // pridam na konec pole zaznamy, pro doplneni tydne
    while(result.length%7 != 0)
    {
      result.push('');
    }

    return result;
  
  }

  /* zmeni mesic vybrany v selectu */
  this.changeMonth = function(obj)
  {
    for(i=0; i<obj.length; i++)
    {
      if(obj.options[i].selected)
        var val = obj.options[i].value;
    }
    this.currentMonth = val;
    this.refresh();
//    alert(val);
  }

  /* vrati dropdown menu se seznamem mesicu */
  this.getDDMonths = function()
  {
    var result = document.createElement('select');
  
    var opt;
    var textNode;
    
    for(var i=0;i<this.nMonths.length;i++)
    {
      opt=document.createElement('option');
      opt.value=i;
      textNode=document.createTextNode(this.nMonths[i]);
      if(this.currentMonth==i) opt.selected=true;
      opt.appendChild(textNode);
      result.appendChild(opt);
    }
    
    // po vyberu mesice nastavime promennou
    result.changeFunc = 'Objekty['+this.id+'].changeMonth(this);';
    result.onchange = function() {eval(this.changeFunc)}
    
    return result;
    
  }

  /* zmeni rok po zadani do inputu */
  this.changeYear = function(obj)
  {
    // pouze ctyrmistny format roku
    if (obj.value.length == 4)
    {
      this.currentYear = obj.value;
      this.refresh();
    }
  }

  /* vrati input por zadani roku */
  this.getINYears = function()
  {
    var result = document.createElement('input');
    result.type='text';
    result.value=this.currentYear;   
    
    // po vyberu mesice nastavime promennou
    result.changeFunc = 'Objekty['+this.id+'].changeYear(this);';
    result.onchange = function() {eval(this.changeFunc)}
    result.maxlength = '4';
    result.size = '4';
    return result;
  }

  /* po najeti mysi na bunku zvyraznit */
  this.hoverOverTd = function(obj)
  {
    obj.className += 'hover';  
  }

  /* po odjeti mysi z bunky vratit zpet */
  this.hoverOutTd = function(obj)
  {
    obj.className = obj.className.replace( 'hover', '' );  
  }

  /* po kliku vyplnim input prislusnou hodnotou */
  this.clickTd = function(day)
  {
    document.getElementById(this.linkElementId).value=day+'.'+eval( this.currentMonth+' + 1')+'.'+this.currentYear;
    this.showHide();
//    alert(day+'.'+eval( this.currentMonth+' + 1')+'.'+this.currentYear);  
  }


  /* vykresli datumovnik, podle aktulniho data, etc. */
  this.write = function()
  {
    if (this.show)
    {
      var tr;
      var td;
      var th;
      var textNode;
      var i;
      var j;

      // vytvorime rozkosnou tabulku
      var table = document.createElement('table');
      this.tableId = table;
      table.cellSpacing="0";
      table.className = this.tableClass;
      // vytvorime zlou hlavicku tabulky
      var thead = document.createElement('thead');
      table.appendChild(thead);
      // ... prni radek tabulky
      var trH = document.createElement('tr');
      thead.appendChild(trH);
      // ... zkratky dni od pondelka do nedele 
      for(i=0;i<this.nShDays.length;i++)
      {
        th = document.createElement('th');
        th.title=this.nDays[i];
        textNode = document.createTextNode(this.nShDays[i]);
        th.appendChild(textNode);
        trH.appendChild(th);
      }

    
      // telo tabulky
      // vytvorime radky jednotlivych tydnu a vyplnime je cisly dni
      var tbody = document.createElement('tbody');
      var monthArr = this.getMonthArr();
      // tydny
      var tydny = monthArr.length / 7;
      for(i=0;i<tydny;i++)
      {
        tr = document.createElement('tr');
        // dny
        for(j=0;j<7;j++)
        {
          td = document.createElement('td');
          // po najeti mysi zmenime barvu
          if (monthArr[(i*7+j)])
          {
            td.hoverOverFunc = 'Objekty['+this.id+'].hoverOverTd(this);';
            td.onmouseover = function() {eval(this.hoverOverFunc)}
            td.hoverOutFunc = 'Objekty['+this.id+'].hoverOutTd(this);';
            td.onmouseout = function() {eval(this.hoverOutFunc)}
            td.clickFunc = 'Objekty['+this.id+'].clickTd('+monthArr[(i*7+j)]+');';
            td.onclick = function() {eval(this.clickFunc)}
          }
          
          textNode = document.createTextNode(monthArr[(i*7+j)]);
          td.appendChild(textNode);    
          tr.appendChild(td);
        }
        tbody.appendChild(tr);
      }
      table.appendChild(tbody);
    
    
    
      // paticka tabulky
      var tfoot = document.createElement('tfoot');
      tr = document.createElement('tr');
      tfoot.appendChild(tr);
      //mesice
      td = document.createElement('td');
//    td.setAttribute('colspan','4');
      td.colSpan='4';
      td.appendChild(this.getDDMonths());
      tr.appendChild(td);
      //roky
      td = document.createElement('td');
//    td.setAttribute('colspan','3');
      td.colSpan='3';
      td.appendChild(this.getINYears());
      tr.appendChild(td);
    
      table.appendChild(tfoot);    
    
      // appendovani tabulky do dokumentu
      var masterId=document.getElementById(this.linkElementId);
      if(masterId)
        this.insertAfter(this.buttonId, table);
      else
        document.body.appendChild(table);
    }

  }

  /* odstrani datumovnik */
  this.clear = function()
  {
    if (this.tableId)
    {
      // odstraneni tabulky z dokumentu
      var masterId=document.getElementById(this.linkElementId);
      if(masterId)
        masterId.parentNode.removeChild(this.tableId);
      else
        document.body.removeChild(this.tableId);
    
      this.tableId = null;
    }
  }

  /* prekresleni tabulky */
  this.refresh = function()
  {
    this.clear();
    this.write();
  }

// zavolani construtoru
this.constructor();

}
