/* $Id: ajax.js 368 2010-06-24 08:51:16Z lusl0338 $ */
/** odeslání XMLHttp požadavku
* @param function obsluha funkce zajišťující obsluhu při změně stavu požadavku, dostane parametr s XMLHttp objektem
* @param string method GET|POST|...
* @param string url URL požadavku
* @param string [content] tělo zprávy
* @param array [headers] pole předaných hlaviček ve tvaru { 'hlavička': 'obsah' }
* @return bool true v případě úspěchu, false jinak
* @copyright Jakub Vrána, http://php.vrana.cz
*/
function send_xmlhttprequest(obsluha, method, url, content, headers) {
  var xmlhttp = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
      xmlhttp = new XMLHttpRequest();
      if (xmlhttp.overrideMimeType) {
        xmlhttp.overrideMimeType('text/xml');
      }
    } else if (window.ActiveXObject) { // IE
      try {
        xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
      } 
      catch (e) {
        try {
          xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
        } catch (e) {}
      }
    }
    if (!xmlhttp) {
      throw('Giving up :( Cannot create an XMLHTTP instance');
      return false;
    }
    var process=obsluha;
    xmlhttp.onreadystatechange = function() {
      process.processAJAX(xmlhttp)
    };
    xmlhttp.open(method, url);
    if (headers) {
        for (var key in headers) {
            xmlhttp.setRequestHeader(key, headers[key]);
        }
    }
    if (method=='POST') {
      xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
      if (content) {
        xmlhttp.setRequestHeader('Content-length', content.length);
      }
      xmlhttp.setRequestHeader('Connection', 'close');
    }
    xmlhttp.send(content);
    return true;
}
/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/
var Url = {
        // public method for url encoding
        encode : function (string) {
                return escape(this._utf8_encode(""+string));
        },
        // private method for UTF-8 encoding
        _utf8_encode : function (string) {
                string = string.replace(/\r\n/g,"\n");
                var utftext = "";
                for (var n = 0; n < string.length; n++) {
                        var c = string.charCodeAt(n);
                        if (c < 128) {
                                utftext += String.fromCharCode(c);
                        }
                        else if((c > 127) && (c < 2048)) {
                                utftext += String.fromCharCode((c >> 6) | 192);
                                utftext += String.fromCharCode((c & 63) | 128);
                        }
                        else {
                                utftext += String.fromCharCode((c >> 12) | 224);
                                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                                utftext += String.fromCharCode((c & 63) | 128);
                        }
                }
                return utftext;
        }
}
function urlencode(str) {
  return Url.encode(str);
}
function include(filename) {
  var head = document.getElementsByTagName('head')[0];
  script = document.createElement('script');
  script.src = filename;
  script.type = 'text/javascript';
  head.appendChild(script)
}
/* Debuging */
function consoleError(a) {
  try {
    switch (arguments.length) {
      case 1: return console.error(arguments[0]);
      case 2: return console.error(arguments[0], arguments[1]);
      case 3: return console.error(arguments[0], arguments[1], arguments[2]);
      case 4: return console.error(arguments[0], arguments[1], arguments[2], arguments[3]);
      case 5: return console.error(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]);
      case 6: return console.error(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]);
      case 7: return console.error(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6]);
      case 8: return console.error(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6]);
      case 9: return console.error(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], arguments[7]);
      case 10:return console.error(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], arguments[7], arguments[8]);
    }
  } catch (e) {}
}
function consoleDebug(a) {
  try {
    switch (arguments.length) {
      case 1: return console.debug(arguments[0]);
      case 2: return console.debug(arguments[0], arguments[1]);
      case 3: return console.debug(arguments[0], arguments[1], arguments[2]);
      case 4: return console.debug(arguments[0], arguments[1], arguments[2], arguments[3]);
      case 5: return console.debug(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]);
      case 6: return console.debug(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]);
      case 7: return console.debug(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6]);
      case 8: return console.debug(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6]);
      case 9: return console.debug(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], arguments[7]);
      case 10:return console.debug(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], arguments[7], arguments[8]);
    }
  } catch (e) {}
}
/* Spouštění více onLoad funkcí */
onLoadFunctions = [];
function addOnLoadObject(func) {
  onLoadFunctions.push(func);
}
function runOnLoad() {
  for (var i=0; i<onLoadFunctions.length; i++) {
    try {
      runFunction = "onLoadFunctions["+i+"].run()";
      setTimeout(runFunction , 1);
    } catch (e) {
      consoleError('Chyba při spuštění onLoad(%d): %s', i, e);
    }
  }
}
window.onload=runOnLoad;
/* Kalendář akcí */
/**
  * Atributy
  */
AjaxCalendar.prototype.month;
AjaxCalendar.prototype.year;
AjaxCalendar.prototype.table;
AjaxCalendar.prototype.lang;
AjaxCalendar.prototype.daysTable;
AjaxCalendar.prototype.monthTh;
AjaxCalendar.prototype.UPA;
AjaxCalendar.prototype.DFJP;
AjaxCalendar.prototype.FES;
AjaxCalendar.prototype.FEI;
AjaxCalendar.prototype.FF;
AjaxCalendar.prototype.FCHT;
AjaxCalendar.prototype.FR;
AjaxCalendar.prototype.FZS;
/**
  * Constructor
  */
function AjaxCalendar(den, lang) {
  if (typeof(den)=='undefined') {
    date = new Date();
    this.year = date.getFullYear();
    this.month = date.getMonth();
  } else {
    this.year = parseInt(den.substring(0, 4), 10);
    this.month = parseInt(den.substring(5, 7), 10);
    if (isNaN(this.month)) {
      this.month = 0;
    } else {
      this.month = this.month - 1;
    }
  }
  if (typeof(lang)=='undefined') {
    this.lang = 'cs';
  } else {
    this.lang = lang;
  }
  include('/styles/fade.js');
}
/**
  * Runs onLoad
  */
AjaxCalendar.prototype.run = function() {
  this.table=document.getElementById('akce-kalendar-body');
  this.redrawTable();
}
/**
  * Process AJAX response
  */
AjaxCalendar.prototype.processAJAX=function(response) {
  if ((response.readyState==4)&&(response.status==200)) {
    this.drawTable();
    data=eval('('+response.responseText+')');
    aktualniRokMesic=this.year+'-'+this.getMonth2Digit();
    for (var i=0; i<data.length; i++) {
      zacatek=data[i].zacatek.substring(0, 7);
      konec=data[i].konec.substring(0, 7);
      if ((zacatek<=aktualniRokMesic)&&(konec>=aktualniRokMesic)) {
        this.drawAkce(data[i]);
      }
    }
    fade('akce-kalendar', 300);
  }
}
AjaxCalendar.prototype.getMonth2Digit = function() {
  if (this.month<9) {
    return '0'+(this.month+1);
  }
  return ''+(this.month+1);
}
AjaxCalendar.prototype.drawAkce = function(akce) {
  if (akce.zacatek<(this.year+'-'+this.getMonth2Digit()+'-01')) {
    zacatek=1;
  } else {
    z=akce.zacatek.split('-');
    zacatek=parseInt(z[2], 10);
  }
  if (akce.konec>(this.year+'-'+this.getMonth2Digit()+'-31')) {
    konec=31;
  } else {
    k=akce.konec.split('-');
    konec=parseInt(k[2], 10);
  }
  mesic=this.year+'-'+this.getMonth2Digit();
  setMonth = false;
  for (var i=zacatek; i<=konec; i++) {
    if (typeof(this.daysTable[i])!='undefined') {
      if (this.daysTable[i].firstChild.nodeName.toUpperCase() != 'A') {
        odkaz = document.createElement('a');
        odkaz.innerHTML = this.daysTable[i].innerHTML;
        odkaz.href = '/akce.html?den='+mesic+'-'+((odkaz.innerHTML<10)?('0'+odkaz.innerHTML):odkaz.innerHTML)+this.getFakultyFilter(1);
        this.daysTable[i].className='calendar-actions calendar-actions1';
        this.daysTable[i].innerHTML = '';
        this.daysTable[i].appendChild(odkaz);
        setMonth = true;
      } else {
        switch (this.daysTable[i].className) {
          case 'calendar-actions calendar-actions1':
            this.daysTable[i].className = 'calendar-actions calendar-actions2';
            break;
          case 'calendar-actions calendar-actions2':
            this.daysTable[i].className = 'calendar-actions calendar-actions3';
            break;
        }        
      }
    }
  }
  if (setMonth && (this.monthTh.firstChild.nodeName.toUpperCase() != 'A')) {
    odkaz = document.createElement('a');
    odkaz.innerHTML = this.monthTh.innerHTML;
    odkaz.href = '/akce.html?den='+mesic+this.getFakultyFilter(1);
    this.monthTh.innerHTML = '';
    this.monthTh.appendChild(odkaz);
    this.monthTh.id = 'mesic';
  }
}
/* Vraci pole dnů */
AjaxCalendar.prototype.getDays = function() {
  day = new Date();
  day.setDate(1);
  day.setMonth(this.month);
  day.setYear(this.year);
  ret=[];
  dow=day.getDay();
  if (dow==0) {
    dow=7;
  }
  for (var i=1; i<dow; i++) {
    ret.push(null);
  }
  while (this.month == day.getMonth()) {
    den = new Date();
    ret.push(day.getDate());
    day.setDate(day.getDate()+1);
  }
  if (day.getDay()<2) {
    if (day.getDay()==0) {
      ret.push(null);
    }
  } else {
    for (var i=day.getDay(); i<=7; i++) {
      ret.push(null);
    }
  }
  return ret;
}
AjaxCalendar.prototype.eraseTable=function() {
  while (this.table.hasChildNodes()) {
    this.table.removeChild(this.table.firstChild);
  }
}
AjaxCalendar.prototype.addMonth=function() {
  this.month++;
  if (this.month>11) {
    this.month=0;
    this.year++;
  }
  this.redrawTable();
}
AjaxCalendar.prototype.subMonth=function() {
  this.month--;
  if (this.month<0) {
    this.month=11;
    this.year--;
  }
  this.redrawTable();
}
AjaxCalendar.prototype.drawTableHeader=function() {
  var thisObj=this;
  row=document.createElement('tr');
  col=document.createElement('th');
  col.innerHTML='&laquo;';
  col.className = 'zmena-mesice';
  col.onclick=function() {thisObj.subMonth(); return false;}
  row.appendChild(col);
  col=document.createElement('th');
  col.colSpan=5;
  col.innerHTML=this.getMonthName(this.month)+'&nbsp;'+this.year;
  this.monthTh = col;
  row.appendChild(col);
  col=document.createElement('th');
  row.appendChild(col);
  col.innerHTML='&raquo;';
  col.className = 'zmena-mesice';
  col.onclick=function() {thisObj.addMonth(); return false;}
  this.table.appendChild(row);
  row=document.createElement('tr');
  for (var i=1; i<=7; i++) {
    col=document.createElement('th');
    col.innerHTML=this.getDayAbbr(i);
    row.appendChild(col);
  }
  this.table.appendChild(row);
}
AjaxCalendar.prototype.redrawTable=function() {
  fade('akce-kalendar', 300);
  send_xmlhttprequest(this, 'GET', '/getajaxcalendar.json?month='+this.year+this.getMonth2Digit()+this.getFakultyFilter());
}
AjaxCalendar.prototype.drawTable=function() {
  today = new Date();
  drawToday = (((today.getYear()+1900)==this.year)&&(today.getMonth()==this.month));
  this.daysTable=new Array();
  days = this.getDays();
  week=null;
  this.eraseTable();
  this.drawTableHeader();
  for (var i=0; i<days.length; i++) {
    if ((i%7)==0) {
      if (week!=null) {
        this.table.appendChild(week);
      }
      week=document.createElement('tr');
    }
    day=document.createElement('td');
    if (days[i]==null) {
      day.innerHTML='&nbsp;';
    } else {
      if (drawToday && (today.getDate()==days[i])) {
        day.id='today';
      }
      day.innerHTML=days[i];
      this.daysTable[days[i]]=day;
    }
    week.appendChild(day);
  }
  this.table.appendChild(week);
}
AjaxCalendar.prototype.getMonthName=function(num) {
  switch (this.lang) {
    case 'cs':
      switch (num) {
        case 12:
        case 0:  return 'Leden';
        case 1:  return 'Únor';
        case 2:  return 'Březen';
        case 3:  return 'Duben';
        case 4:  return 'Květen';
        case 5:  return 'Červen';
        case 6:  return 'Červenec';
        case 7:  return 'Srpen';
        case 8:  return 'Září';
        case 9:  return 'Říjen';
        case 10: return 'Listopad';
        case 11: return 'Prosinec';
      }
    case 'en':
    default:
       switch (num) {
        case 12:
        case 0:  return 'January';
        case 1:  return 'February';
        case 2:  return 'March';
        case 3:  return 'April';
        case 4:  return 'May';
        case 5:  return 'June';
        case 6:  return 'July';
        case 7:  return 'August';
        case 8:  return 'September';
        case 9:  return 'October';
        case 10: return 'November';
        case 11: return 'December';
      }
 }
}
AjaxCalendar.prototype.getDayAbbr=function(num) {
  switch (this.lang) {
    case 'cs':
      switch (num) {
        case 7:
        case 0:  return 'Ne';
        case 1:  return 'Po';
        case 2:  return 'Út';
        case 3:  return 'St';
        case 4:  return 'Čt';
        case 5:  return 'Pá';
        case 6:  return 'So';
      }
    case 'en':
    default:
       switch (num) {
        case 7:
        case 0:  return 'Su';
        case 1:  return 'Mo';
        case 2:  return 'Tu';
        case 3:  return 'We';
        case 4:  return 'Th';
        case 5:  return 'Fr';
        case 6:  return 'Sa';
      }
 }
}
AjaxCalendar.prototype.setUPA = function (val) {
  this.UPA = val;
}
AjaxCalendar.prototype.setDFJP = function (val) {
  this.DFJP = val;
}
AjaxCalendar.prototype.setFES = function (val) {
  this.FES = val;
}
AjaxCalendar.prototype.setFEI = function (val) {
  this.FEI = val;
}
AjaxCalendar.prototype.setFF = function (val) {
  this.FF = val;
}
AjaxCalendar.prototype.setFCHT = function (val) {
  this.FCHT = val;
}
AjaxCalendar.prototype.setFR = function (val) {
  this.FR = val;
}
AjaxCalendar.prototype.setFZS = function (val) {
  this.FZS = val;
}
AjaxCalendar.prototype.getFakultyFilter = function(val) {
  filter = '';
  if ((typeof(this.UPA)!='undefined') && (this.UPA != '')) {
    filter+='&upa='+(val?val:'UPA');
  }
  if ((typeof(this.DFJP)!='undefined') && (this.DFJP != '')) {
    filter+='&dfjp='+(val?val:'DFJP');
  }
  if ((typeof(this.FES)!='undefined') && (this.FES != '')) {
    filter+='&fes='+(val?val:'FES');
  }
  if ((typeof(this.FEI)!='undefined') && (this.FEI != '')) {
    filter+='&fei='+(val?val:'FEI');
  }
  if ((typeof(this.FF)!='undefined') && (this.FF != '')) {
    filter+='&ff='+(val?val:'FF');
  }
  if ((typeof(this.FCHT)!='undefined') && (this.FCHT != '')) {
    filter+='&fcht='+(val?val:'FCHT');
  }
  if ((typeof(this.FR)!='undefined') && (this.FR != '')) {
    filter+='&fr='+(val?val:'fr');
  }
  if ((typeof(this.FZS)!='undefined') && (this.FZS != '')) {
    filter+='&fzs='+(val?val:'FZS');
  }
  if (typeof(this.UPA)!='undefined') {
    filter+='&filtrovat=1';
  }
  return filter;
}
ImageRotate.prototype.event;
ImageRotate.prototype.images;
ImageRotate.prototype.URLs;
ImageRotate.prototype.imagesAux;
ImageRotate.prototype.URLsAux;
ImageRotate.prototype.timerTimeout=10000;
ImageRotate.prototype.fadeTimeout=500;
ImageRotate.prototype.actImg='';
ImageRotate.prototype.alterLists=false;
ImageRotate.prototype.primaryList=true;
function ImageRotate(images, URLs, imagesAux, URLsAux) {
  include('/styles/fade.js');
  imgs = images.split(",");
  urls = URLs.split(",");
  this.images=new Array();
  this.URLs=new Array();
  for (var img in imgs) {
      if ((imgs[img]!=null)&&((imgs[img]!=''))) {
        this.images.push(imgs[img]);
        this.URLs.push(urls[img]);
      }
  }
  this.imagesAux=new Array();
  this.URLsAux=new Array();
  if (typeof(imagesAux)!='undefined') {
    imgsAux = imagesAux.split(",");
    urlsAux = URLsAux.split(",");
    for (var img in imgsAux) {
        if ((imgsAux[img]!=null)&&((imgsAux[img]!=''))) {
          this.imagesAux.push(imgsAux[img]);
          this.URLsAux.push(urlsAux[img]);
          this.alterLists=true;
          this.primaryList=false;
        }
    }
  }
}
ImageRotate.prototype.setEvent = function(element, url) {
  this.event = element;
  this.preloadImages(this.images);
  this.preloadImages(this.imagesAux);
  rnd=this.getRandomImage();
  if (!this.alterLists || this.primaryList) {
    this.setElement(this.images[rnd], this.URLs[rnd], 1);
  } else {
    this.setElement(this.imagesAux[rnd], this.URLsAux[rnd], 1);
  }
  this.primaryList = !this.primaryList;
}
ImageRotate.prototype.run = function() {
  if ((this.images.length>1) || this.alterLists) {
    var thisObj=this;
    setTimeout(function() {thisObj.changeTimer();}, this.timerTimeout);
  }
}
ImageRotate.prototype.preloadImages = function(list) {
  for (i=0; i<list.length; i++) {
    img=document.createElement('img');
    img.src=list[i];
    img.className='preloadedEventElement';
    img.style.opacity = '0';
    img.style.filter = 'alpha(opacity = 0)';
    this.event.appendChild(img);
  }
}
ImageRotate.prototype.clear = function() {
  while (this.event.childNodes.length>1) {
    this.event.removeChild(this.event.firstChild);
  }
}
ImageRotate.prototype.clearPreloaded = function() {
  images = this.event.getElementsByTagName("img");
  toDelete = new Array();
  for (i=0; i<images.length; i++) {
    if (images[i].className == 'preloadedEventElement') {
      toDelete.push(images[i]);
    }
  }
  while (toDelete.length>0) {
    del = toDelete.pop();
    this.event.removeChild(del);
  }
}
ImageRotate.prototype.setElement = function(imgUrl, url, visible) {
  this.actImg = imgUrl;
  img=document.createElement('img');
  img.src=imgUrl;
  appended=null;
  if (url=='') {
    appended=img;
  } else {
    a=document.createElement('a');
    a.href=url;
    a.appendChild(img);
    appended=a;
  }
  if (visible!=1) {
    this.clearPreloaded();
    var thisObj = this;
    if (this.event.childNodes.length==1) {
      this.event.firstChild.id="oldEventElement";
    }
    appended.id="newEventElement";
    this.runFade();
  }
  this.event.appendChild(appended);
}
ImageRotate.prototype.runFade = function() {
  var thisObj = this;
  fade("oldEventElement", this.fadeTimeout, function(){thisObj.oldFadedOut();});
}
ImageRotate.prototype.oldFadedOut = function() {
  this.clear();
}
ImageRotate.prototype.changeTimer = function() {
  rnd=this.getRandomImage();
  if (!this.alterLists || this.primaryList) {
    this.setElement(this.images[rnd], this.URLs[rnd]);
  } else {
    this.setElement(this.imagesAux[rnd], this.URLsAux[rnd]);
  }
  this.primaryList = !this.primaryList;
  var thisObj = this;
  setTimeout(function() {thisObj.changeTimer();}, this.timerTimeout);
}
ImageRotate.prototype.getRandomImage = function() {
  if (!this.alterLists || this.primaryList) {
    do {
      rnd = Math.floor(Math.random()*this.images.length);
    } while ((this.images.length>1)&&(this.images[rnd]==this.actImg));
  } else {
    do {
      rnd = Math.floor(Math.random()*this.imagesAux.length);
    } while ((this.imagesAux.length>1)&&(this.imagesAux[rnd]==this.actImg));
  }
  return rnd;
}
