/** Common Library functions **/

function Library_getInputValue(formItem, name) {
  var i;
  var ret = false;
  formItem = Library_getParentNodeByTagName(formItem, 'FORM');
  if (formItem) {
    var inputs = formItem.getElementsByTagName('INPUT');
    for (i = 0; i < inputs.length; i++) {
      if (
          (inputs[i].type != 'radio') &&
          (inputs[i].type != 'checkbox') &&
          (inputs[i].name == name)
         ) {
        ret = inputs[i].value;
        break;
      }
    }
  }

  return ret;
}

function Library_getRadioValue(formItem, name) {
  var i;
  var ret = false;
  formItem = Library_getParentNodeByTagName(formItem, 'FORM');
  if (formItem) {
    var inputs = formItem.getElementsByTagName('INPUT');
    for (i = 0; i < inputs.length; i++) {
      if (
        (inputs[i].type == 'radio') &&
        (inputs[i].checked) &&
        (inputs[i].name == name)
        ) {
        ret = inputs[i].value;
        break;
      }
    }
  }

  return ret;
}

function Library_setRadioValue(obj, value) {
  var i;
  var ret = false;
  var formItem = Library_getParentNodeByTagName(obj, 'FORM');
  var name = obj.name;
  if (formItem) {
    var inputs = formItem.getElementsByTagName('INPUT');
    for (i = 0; i < inputs.length; i++) {
      if (
        (inputs[i].type == 'radio') &&
        (inputs[i].name == name)
        ) {
          inputs[i].checked = (inputs[i].value == value);
          if (inputs[i].value == value) ret = true;
      }
    }
  }
  return ret;
}

function Library_setSelectValue(obj, value){
  if (!obj) return false;
  var index = -1;
  for (var i = 0; i < obj.options.length; i++){
    if (obj.options[i].value.toUpperCase() == value.toUpperCase()){//shoda na hodnotu
      index = i;
      break;
    }
    if ((index == -1) && (obj.options[i].innerHTML.toUpperCase() == value.toUpperCase())){ // shoda na popisek
      index = i;
    }
  }
  obj.selectedIndex = index;
  return (index != -1);
}

function Library_getFormItemValue(obj){
  var i;
  var ret = false;
  if (obj.tagName == 'INPUT'){
    switch (obj.type){
      case 'radio':
        if (!obj.name) {
            Library_debugAlert('Radio button has no name:'+obj.id);
            return null;
        } //TODO: osetrit
        return Library_getRadioValue(obj, obj.name);
      case 'checkbox':
        return obj.checked ? obj.value : null;
      case 'text':
      case 'hidden':
      default:
        return obj.value; 
    }
  } 
  if (obj.tagName == 'SELECT'){
    return obj.options[obj.selectedIndex].value;
  } 
  if (obj.tagName == 'TEXTAREA') {
    return obj.innerHTML;
  }
  Library_debugAlert('Unhandled type of object:'+obj.tagName);
  return null;
}

function Library_setValue(obj, value, onlyToEmpty){// vraci, zda-li doslo k nastaveni hodnoty
    if (!obj) return false;
    if (obj.tagName == 'INPUT'){
      switch (obj.type){
        case 'radio':
          if (!obj.name) {
            Library_debugAlert('Radio button without definition of name:'+obj.id);
            return false;
          }
          return Library_setRadioValue(obj, value);
        case 'checkbox':
          return element.checked = value ? true : false;
        case 'text':
        default:
          if (onlyToEmpty && (obj.value != '')) return false;
          obj.value = value;
          return true; 
      }
    }
    if (obj.tagName == 'SELECT'){
      if (onlyToEmpty && (obj.selectedIndex != -1) && (trim(obj.options[obj.selectedIndex].value) != '')) return false;
      return Library_setSelectValue(obj, value);
    }
    if (obj.tagName == 'TEXTAREA') {
      if (onlyToEmpty && (trim(obj.innerHTML) != '')) return false;
      obj.innerHTML = value;
      return true;
    }
    return false;
}

function Library_getFormValues(elForm, implodeUrl, filtrName, replace){
  if (!elForm) return false;
  var pars = new Object();
  var inps = elForm.elements;
  for (var i = 0; i < inps.length; i++) {
    var nam = inps[i].name;
    if (!nam || inps[i].type == 'button' || inps[i].type == 'submit' || inps[i].disabled) continue;    
    if (filtrName && nam.indexOf(filtrName) == -1) continue;
    if (replace || replace === ''){
      nam = nam.substring(0,nam.indexOf(filtrName))+replace+nam.substring(nam.indexOf(filtrName) + filtrName.length);
    }
    pars[nam] = Library_getFormItemValue(inps[i]);
  }
  if (!implodeUrl) return pars;
  else {
    var res = '';
    for (var n in pars){
      if (pars[n] !== null){
        res += '&'+n+'='+pars[n];
      }
    }
    return res;
  }
}

function Library_addClass(el, cl) {
  el.className += (el.className ? ' ' : '') + cl;
}

function Library_removeClass(el, cl) {
  var classesOld = el.className.split(' ');
  var classesNew = new Array();
  var i;
  
  for (i in classesOld) {
    if (classesOld[i] != cl) {
      classesNew.push(classesOld[i]);
    }
  }
  el.className = classesNew.join(' ');
}

function Library_hasClass(element, classes, separator){
    var sep =  separator ? separator : ' ';
    var parts = element.className.split(sep);
    if (!classes) return parts;
    for (var index in parts){
      if (parts[index] == classes) return true; 
    }
    return false;
}

function Library_getParentNodeByTagName(element, name) {
  element = element.parentNode;
  while (element && element.nodeName != name) {
    element = element.parentNode;
  }
  return element;
}

function Library_getNextSiblingByTagName(element, name, count) {
  if (!count) { count = 1; }
  do {
    element = element.nextSibling;
    if (element && element.nodeName == name) { count--; }
  } while (element && ((element.nodeName != name) || (count != 0)));
  return element;
}

function Library_getPreviousSiblingByTagName(element, name) {
  element = element.previousSibling;
  while (element && element.nodeName != name) {
    element = element.previousSibling;
  }
  return element;
}

function Library_getFirstChildByTagName(element, name) {
  element = element.firstChild;
  while (element && element.nodeName != name) {
    element = element.nextSibling;
  }
  return element;
}

function Library_getElementAttributes(element){
  var w = document.getElementById('dumpElement'+element.id);
  if (!w){
    w = document.createElement('table');
    w.setAttribute('id', 'dumpElement'+element.id);
//    element.parentNode.appendChild(w);    
    }
  w.nodeValue = '';
  var row = document.createElement('tr');
  var thD = document.createElement('th');
  var tdD = false;
  var tdC = false;
  thD.innerHTML = 'Description';
  var thC = document.createElement('th');
  thC.innerHTML = 'Contain';
  row.appendChild(thD);
  row.appendChild(thC);
  w.appendChild(row);
  for (var a in element){
    row = document.createElement('tr');
    tdD = document.createElement('td');
    tdD.innerHTML = a;
    row.appendChild(tdD);
    tdC = document.createElement('td');
    tdC.innerHTML = ''+element[a];
    row.appendChild(tdC);
    w.appendChild(row);
  }
  return w;
}

  function Library_getOffsetTop(el) {
    var offsetTop = 0;
    if (el.offsetParent) {
      offsetTop = el.offsetTop;
      el = el.offsetParent;
      while (el) {
        offsetTop += el.offsetTop;
        el = el.offsetParent;
      }
    }                                     
    return offsetTop;
  }

  function Library_getOffsetLeft(el) {
    var offsetLeft = 0;
    if (el.offsetParent) {
      offsetLeft = el.offsetLeft;
      el = el.offsetParent;
      while (el) {
        offsetLeft += el.offsetLeft;
        el = el.offsetParent;
      }
    }                                     
    return offsetLeft;
  }

  function Library_getComputedStyle(el) {
   if (window.getComputedStyle) {
     return window.getComputedStyle(el, null);
   } else {
     return el.currentStyle;
   }
  }

  function Library_isPositioned(el) {
   var position = Library_getComputedStyle(el).position;
   return (position != '') && (position != 'static');
  }

//function returns date if date is valid or false if date is invalid (czech date format)
function Library_isValidDate(string, isBirthDate) {
   var parsedDate = string.split (".");
   if (parsedDate.length != 3) return false;
   var day, month, year;
   month = (parsedDate[1]-1);
   day = parsedDate[0];
   year = parsedDate[2];

   var objDate = new Date (year,month,day);
   if (month != (objDate.getMonth())) return false;
   if (day != objDate.getDate()) return false;
   if (year != objDate.getFullYear()) return false;

   if (objDate && isBirthDate) {
     var chk = new Date();
     return (chk.getFullYear() - 100) < objDate.getFullYear();
   }

   return objDate;
}

function Library_insertAfter(newElement, targetElement) {
  var daddy = targetElement.parentNode;
  if (daddy.lastChild == targetElement) {
    daddy.appendChild(newElement);
  }
  else {
    daddy.insertBefore(newElement, targetElement.nextSibling);
  } 
}

function Library_replaceNode(new_node, old_node) {
  var daddy = old_node.parentNode;
  var next_sibling = old_node.nextSibling;
  daddy.removeChild(old_node);
  if (daddy.lastChild == old_node) {
    daddy.appendChild(new_node);
  }
  else {
  daddy.insertBefore(new_node,next_sibling);
  }
}

function Library_insertTemplateVar(string,template,temp_content) {
  return string.replace("{"+template+"}",temp_content)
}

function Library_purge(d) {
    var a = d.attributes, i, l, n;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            n = a[i].name;
            if (typeof d[n] === 'function') {
                d[n] = null;
            }
        }
    }
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            Library_purge(d.childNodes[i]);
        }
    }
}

function Library_getFormElementsByName(sName, sForm){
  if (!sForm) sForm = this;
  while (sForm && sForm.tagName != "FORM")sForm = sForm.parentNode; 
  var res = new Array();
  for (var i = 0; i < sForm.elements.length; i++){
    if (sForm.elements[i].name && sForm.elements[i].name == sName){
      res.push(sForm.elements[i]);
    }
  }
  return res;
}

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
  chars = chars || "\\s";
  return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function Library_length(ar){
  var i = 0;
  for (var k in ar){
    i++;
  } 
  return i;
}

function Library_inArray(ar, val){
  for (var k in ar){
    if (ar[k] == val) return k;
  } 
  return false;
}

function Library_join(ar, delimiter, includeZero){
  if (!delimiter) delimiter = '';
  var text = '';
  for (var i in ar){
    if (!ar[i] && (!includeZero || (ar[i] !== 0 && ar[i] !== '0' && ar[i] !== "0"))) continue;
    text += (text == '' ? '' : delimiter) + ar[i];
  }
  return text;
}

function Library_unset(ar, index){
  delete ar[index];
  return ar;
}

function Library_ReplaceHolders(value, placeHolders){
  var nVal = value;
  for (var i in placeHolders){
    var re = new RegExp("\{"+i+"\}", "g");
    nVal = nVal.replace(re, placeHolders[i]);
    re = null;
  }
  return nVal;
}

function Library_addEvent(obj, evType, fn, useCapture){
  if (obj.addEventListener){
    obj.addEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be attached");
    return false;
  }
}

function Library_debugMessage(message, delimiter){
  if (!window.debugMessageEl){
    if (!window.debugMessageId) window.debugMessageId = 'debugDiv';
    window.debugMessageEl = document.getElementById(window.debugMessageId);
    if (!window.debugMessageEl && false) {
      window.debugMessageEl = document.createElement('div');
      window.debugMessageEl.innerHTML = '';
      window.debugMessageEl.id = window.debugMessageId;
      var b = document.getElementsByTagName('body');
      b[0].appendChild(window.debugMessageEl);
    }
  }
  if (!delimiter) delimiter = "<br />";
  if (window.debugMessageEl) window.debugMessageEl.innerHTML += delimiter + message;
}

function Library_debugAlert(message, type){
  if(!type) type = "error";
  var consoleDefinition = typeof(console) != "undefined";
  if(type=="error") {
    if (!consoleDefinition) {
      if (window.debug) alert('console:'+message);
    } else {
      console.error(message);
    }
  }
  else if(type=="warning" && consoleDefinition) {
    console.warn(message);
  }
  else if(type=="info" && consoleDefinition) {
    console.info(message);
  }
  else if(type=="debug" && consoleDefinition) {
    console.debug(message);
  }
}

/*******************************************************************
 * F U N K C E  pro manipulaci s casti linku H A S H (target)      *
 *******************************************************************
 * zakazane parametry:
 * @ oddelovac parametru
 * | oddelovac prvku neidexovaneho pole
 * . v nazvu atributu adresovani objektu
 * momentalne neumi ukladat hodnotu 0, tento parametr preskakuje
 */
function UrlHash(){
    this.get = function(index){
      // pokud se pouziva zamek hashe a neni primo nastavovana location.hash
      if (this.alternativeHashSource instanceof Array){
        if (index) return this.alternativeHashSource[index] ? this.alternativeHashSource[index] : false;
        else return this.alternativeHashSource;
      }
      var a = new Array();
      var str = location.hash.toString();
      if (str && str.substring(0,1) == '#') str = str.substring(1);
      if (!str || str == this.defaultEmptyValue) return index ? false : a;
      if (str == this.lastHash) a = this.lastHashAry;
      else Library_getObjectByPath(str, this.urlByArrays, a, this.itemSeparator, this.arraySeparator, this.objectPathSeparator);
      return index ? false/*polozka nenalezena*/ : a;
    };
    this.set = function(a){
      if (!(a instanceof Array)) return false;
      this.isModifiedHash = true;
      if (this.blockSettingHash){
        this.alternativeHashSource = a;
        return true;
      }
      var h = Library_getPathByObject('', a, this.objectPathSeparator, this.itemSeparator, this.arraySeparator);
      this.isModifiedHash = false; // zmena vypropagovana->dulezite pri zamceni uprav
      if (h == this.lastHash) return false;
      if (!h) h = this.defaultEmptyValue;
      if (this.saveHistoryChangesToHash){
        // funkcionalitu pro IE je potreba realizovat skryty IFrame
        location.hash = h;
      } else {
        location.replace('#'+h); //problem s chovani v IFrame
      }
      this.lastHash = h;
      this.lastHashAry = a;
      this.setStorage(h);
      return true;
    };

    this.setStorage = function(h, skipSave/*preskok ajaxoveho ulozeni*/){
      //zajistuje ukladani hodnot do formularu a tim propagaci do historie
      if (!this.itemsStoringHash){
        this.itemsStoringHash = new Array();
        if (this.hashSourceName){
          var stor = null;
          var forms = document.getElementsByTagName('form');
          for (var iForm = 0; iForm < forms.length; iForm++){
            stor = Library_getFormElementsByName(this.hashSourceName, forms[iForm]);
            if (stor[0]) stor = stor[0];
            else {
              stor = document.createElement('input');
              stor.type = 'hidden';
              stor.name = this.hashSourceName;
              forms[iForm].appendChild(stor);
            }
            this.itemsStoringHash.push(stor);
          }
          if (this.itemsStoringHash[0] && this.ajaxActualization) {
            this.itemsStoringHash[0].actualizeHash = this.ajaxActualization;
          }
        }
      }
      // mechanizmus pro ulozeni Hash pro odesilani pres formulare
      for (var iItem in this.itemsStoringHash){
        if (this.itemsStoringHash[iItem]) this.itemsStoringHash[iItem].value = h;
      }
      if (!skipSave && this.itemsStoringHash[0] && this.itemsStoringHash[0].actualizeHash) this.itemsStoringHash[0].actualizeHash(h); // AJAXOVA REGISTRACE
      forms = null; stor = null;
      return true;
    };

    this.modify = function(key, val, plus){ // vraci, zda doslo ke zmene hash
      // Pozor: pri definovani indexu, jez jsou imlicitnimi metodami tridy array, v IE6 nedojde k jejich vraceni, napr: index => sort
      // vraci false pokud nedojde ke zmene Hash
      if (plus){
        return this.add(key, val, plus == 2);
      } else {
        return this.remove(key, val);
      }
    };
    this.add = function(key, val, replace, source){
      // vraci, zda doslo ke zmene hash
      // Pozor: pri definovani indexu, jez jsou imlicitnimi metodami tridy array, v IE6 nedojde k jejich vraceni, napr: index => sort
      // vraci false pokud nedojde ke zmene Hash
      var a = source ? source : this.get();
      if (Library_setIndexByPath(val, a, key, this.objectPathSeparator, replace)){
        return this.set(a);
      }
      return false;
    };
    this.remove = function(key, val, source){
      // pri specifikovani val hleda val v neindexovanem poli
      var a = source ? source : this.get();
      if (Library_removeIndexByPath(val, a, key, this.objectPathSeparator)){
        return this.set(a);
      }
      return false;
    };
    this.saveToHistory = function(val){
      val = !!val;
      this.saveHistoryChangesToHash = val;
    };
    this.lock = function(lockKey){ // umoznuje vicestupnove zamykani
      if (this.blockSettingHash) return false;
      this.alternativeHashSource = this.get();
      this.blockSettingHash = 'lock'+lockKey;
      this.isModifiedHash = false;
      return true;
    };
    this.unlock = function(lockKey){
      if (this.blockSettingHash != 'lock'+lockKey) return false;
      this.blockSettingHash = false;
      if (this.isModifiedHash){
        this.set(this.alternativeHashSource);
      }
      this.alternativeHashSource = false;
      return true;
    };
    this.ajaxActualizationHandler = function(hash, frame){
      // prida se k prvnimu formularovamu elementu
      // na zaklade upravy hashe provede aktualizaci historie
      if (!window.Library_ajaxRequest) return false;
      var url = '';
      if (this.ajaxUrl){
        url = this.ajaxUrl;
      } else {
        url = location.href;
        if (url.indexOf('?') != -1) url = url.substring(0, url.indexOf('?'));
      }
      var separator = (url.indexOf('?') == -1) ? '?' : '&';
      url  = url + separator + 'action=eAjaxSetTarget' +
        (frame ? '&frame='+frame : '')+
        '&'+this.hashSource+'=' +hash;
      Library_ajaxRequest('actualizeHash', url, Library_ajaxHashActualizationResultHandler, this, 0, 1);
      return true;
    };
    this.onloadPrepare = function(){
      window.urlHash.lastHash = location.hash;
      window.urlHash.lastHashAry = window.urlHash.get();
      window.urlHash.setCheckIntervalDelay(window.urlHash.checkIntervalDelay);
      if (!location.hash) return false;
      window.urlHash.setStorage(location.hash.substring(1)); // pri zadavani do linku musi dojit k automatizovanemu zpracovani
      return true;
    };
    this.modifyByHash = function(){
      if (this.changingByHash || this.blockSettingHash || !this.isChanged()) return false;
      this.changingByHash = true;
      if (this.onModifyByHashHandler){
         var hashAry = this.get();
         var appendedAry = Library_arrayMissing(this.lastHashAry, hashAry);
         var removedAry = Library_arrayMissing(hashAry, this.lastHashAry);

         if (Library_lengthNoEmpty(removedAry) + Library_lengthNoEmpty(appendedAry) > 0){
            this.onModifyByHashHandler(appendedAry, removedAry);
            this.lastHash = location.hash;
            this.lastHashAry = hashAry;
         }
      }
      this.changingByHash = false;
      return true;
    };
    this.isChanged = function(){
      var h = location.hash.toString();
      return (this.isEmpty(this.lastHash) != this.isEmpty(h)) || (this.lastHash && this.lastHash != h);
    };
    this.isEmpty = function(val){
      return (!val) || (val == '#') || (val == this.defaultEmptyValue) || (val == '#'+this.defaultEmptyValue);
    }
    this.setOnModifyByHashHandler = function(handle){
      this.onModifyByHashHandler = handle;
    };
    this.setCheckIntervalDelay = function(secs){// nulovym casem se vypne
      //if (this.checkIntervalDelay != secs && this.checkInterval) return false;
      this.checkIntervalDelay = secs;
      if (this.checkInterval) window.clearInterval(this.checkInterval);
      if (this.checkIntervalDelay) this.checkInterval = window.setInterval('window.urlHash.modifyByHash();', this.checkIntervalDelay);
      return true;
    };
/*local function for array operations*/
  function Library_getIndexByPath(ary, path, del){
    if (!del) del = '.';
    if (path.indexOf(del) >= 0){
      var key = path.substring(0, path.indexOf(del));
      if (Library_isObject(ary[key])) return Library_getIndexByPath(ary[key], path.substring(path.indexOf(del)+del.length), del);
      else return null;
    } else {
      if (Library_isDefined(ary[path])) return ary[path];
      else return null;
    }
  }

/*otazka resit vlozeni hodnoty null, "" a false jako remove ? */
  function Library_setIndexByPath(value, ary, path, del, repl){
    if (!del) del = '.';
    var change = false;
    //if (!ary) ary = new Object();
    if (path.indexOf(del) >= 0){
      var key = path.substring(0, path.indexOf(del));
      if (!Library_isObject(ary[key])) {
        ary[key] = isNaN(ary*1) ? new Object() : new Array();
      }
      change = Library_setIndexByPath(value, ary[key], path.substring(path.indexOf(del)+del.length), del, repl);
    } else {
      if (Library_isEmpty(path)) return false;
      if (Library_isEmpty(ary[path])){
        ary[path] = value;
        change = true;
      } else if(ary[path] != value){
        if (repl){
          ary[path] = value;
          change = true;          
        } else {//append
          var subcase = false;
          if (Library_isEmpty(value)) return false; //souvisi s uvodni otazkou
          if (!Library_isObject(value)) value = [value];
          if (!Library_isObject(ary[path])) ary[path] = [ary[path]];
          var saArr = Library_hasSubArray(ary[path]);
          var saVal = Library_hasSubArray(value);
          if (saArr != saVal){
            Library_debugAlert('Unknown way to merge unindexed and indexed array');
          } else if(saArr/* && saVal*/){/* pokud se merguji hluboka pole */
            for (subcase in value){
              if (Library_setIndexByPath(value[subcase], ary[path], subcase, del, repl)) change = true;
            }
          } else {
            for (subcase in value){
              if (Library_inArray(ary[path], value[subcase]) === false){
                if (Library_isEmpty(value[subcase])) continue;
                ary[path].push(value[subcase]);
                change = true;
              }
            }
          }
        }
      }
    }
    return change;
  }

  function Library_removeIndexByPath(value, ary, path, del){
    /*snazi se v poli hledat cestu,
      je-li zadana hodnota, hledaji ve vysledku, jinak odstrani vysledek */
    if (!del) del = '.';
    if (Library_isEmpty(path)) return false;
    var change = false;
    var key = path.toString();
    if (key.indexOf(del) >= 0){
      key = key.substring(0, path.indexOf(del));
      if (Library_isObject(ary[key])) {
        change = Library_removeIndexByPath(ary[key], path.substring(path.indexOf(del)+del.length), del);
      }
    } else {
      if (ary[key]){
        if (value){//hleda pouze konkretni hodnotu
          if (Library_isObject(ary[key])){
            var index = Library_inArray(ary[key], value);
            if (index !== false){
              Library_unset(ary[key], index);
              change = true;
            }
          } else if(ary[key] == value){
            ary[key] = null;
            change = true;
          }
        } else {
          ary[key] = null;
          change = true;
        }
      }
    }
    if (Library_isEmpty(ary[key]) || (Library_isObject(ary[key]) && Library_lengthNoEmpty(ary[key])==0)){
      Library_unset(ary, key); // odstraneni posledniho
    }
    return change;
  }

  function Library_getObjectByPath(path, likeAry, ary, delPar, delSplit, del){
    if (!ary) ary = new Object();
    if (!del) del = '.';
    if (!delPar) delPar = '@';
    if (!delSplit) delSplit = '|';

    if (!path) return null;
    var parts = false;
    var subparts = false;

    if (path.indexOf(delPar))
      parts = path.split(delPar);
    else
      parts = [path];

    for (var i in parts){
      if (parts[i].indexOf('=')>=0)
        subparts = parts[i].split('=', 2);
      else
        subparts = [path, true];
      var val = subparts[1];
      //TODO: problem s urceni, zda jde o retezec
      if (val && val.indexOf && val.indexOf(delSplit) >= 0){
        subparts[1] = val.split(delSplit);
      }
      if (likeAry && !(subparts[1] instanceof Array)) subparts[1] = [subparts[1]];
      Library_setIndexByPath(subparts[1], ary, subparts[0], del);
    }
    return ary;
  }

  function Library_getPathByObject(path, ary, del, delPar, delSplit){
    if (!del) del = '.';
    if (!delPar) delPar = '@';
    if (!delSplit) delSplit = '|';
    if (!path) path = '';
    var val = '';
    //if (!ary) ary = new Object();
    if (!Library_isObject(ary) || Library_lengthNoEmpty(ary) == 0) return val;
    if (!Library_hasSubArray(ary)){// pro neindexovane pole neobsahujici dalsi pole
      return path+"="+Library_join(ary, delSplit, true);
    }
    for (var a in ary){
      if (!Library_isDefined(ary[a])) continue;
      if (Library_isObject(ary[a])){
        val += (val ? delPar : '')+Library_getPathByObject(path+(path ? del : '')+a, ary[a], del, delPar, delSplit);
      } else {
        val += (val ? delPar : '')+(path ? path+del : '')+a+(ary[a] !== true ? ("="+ary[a]) : '');
      }
    }
    return val;
  }

  function Library_arrayMissing(ary1, ary2){ // vraci co chybi ary1 vuci ary2
    var missPar = [];
    if (ary1 == ary2) return missPar;
    if (!Library_isObject(ary1)){
      if (!Library_isObject(ary2)) return [ary2];
      else {
        missPar = ary2;
        var index = Library_inArray(missPar, ary1);
        if (index !== false) Library_unset(missPar, index);
        return missPar;
      }
    }
    if (Library_isObject(ary2)){
      for (var i in ary2){
        if ((i in ary1) && (ary1[i] == ary2[i])) continue;
        if (isNaN(i*1) || Library_isObject(ary2[i])){ // indexovane pole
          var ni = i in ary1 ? Library_arrayMissing(ary1[i], ary2[i]) : ary2[i];
          if (Library_lengthNoEmpty(ni)){
            missPar[i] = ni;
          }
        } else { // neindexovane pole
          if (!Library_isObject(ary2[i])){
            if (Library_inArray(ary1, ary2[i]) === false){
              missPar.push(ary2[i]);
            }
          }
        }
      }
      return missPar;
    } else return [ary2];
  }

  function Library_hasSubArray(ary){ //TODO: co s polem type reference: a[55555] = 1; ??
    if (Library_isObject(ary)){// pro neindexovane pole neobsahujici dalsi pole
      for (var a in ary){
        if (Library_isObject(ary[a]) || isNaN(a*1)){
          return true;
        }
      }
    } else {
      Library_debugAlert('This value cannot be used instead of Object in hasSubArray');
    }
    return false;
  }

  function Library_lengthNoEmpty(o){ /* pocita neprazdne prvky pole*/
    var len = 0;
    if (!Library_isObject(o)) return Library_isEmpty(o) ? 0 : 1;
    for (var i in o){
      len += Library_lengthNoEmpty(o[i]) ? 1 : 0;
    }
    return len;
  }

  function Library_isObject(val){
    return (val instanceof Object && !(val instanceof String));
  }

  function Library_isDefined(val){ // povoluje jakoukoli definovanou hodnotu
    return (typeof(val) != "undefined" && val !== null);
  }

  function Library_isFunction(val){
    return (typeof(val) == "function");
  }

  function Library_isEmpty(val){ // povazuje string 0 i cislo 0 za spravny obsah
    return (!val && val !== '0' && val !== "0" && val !== 0);
  }

  this.onModifyByHashHandler = false;
  this.checkIntervalDelay = 1000; //interval pro zjistovani zmen v Hash
  this.defaultEmptyValue = "USED";
  this.isModifiedHash = false;
  this.changingByHash = false;
  this.saveHistoryChangesToHash = false;
  this.blockSettingHash = false;
  this.hashSource = "__hashSource";
  this.hashSourceName = false; // polozky formulare pro ukladani hashe
  this.alternativeHashSource = false; //pro ukladani stavu hashe v prubehu zamceni
  this.itemsStoringHash = false; // kolekce elementu pro ukladani hashe
  this.lastHash = false;
  this.lastHashAry = false;

  this.itemSeparator = "@";
  this.arraySeparator = "|";
  this.objectPathSeparator = ".";
  this.urlByArrays = true;

  if (window.Library_prepareUrlHash) Library_prepareUrlHash(this);
  //automatic for add action onload
  Library_addEvent(window, 'load', this.onloadPrepare, false);
}

window.urlHash = new UrlHash();
/*******************************
 *        datove konverze      *
 *******************************/

function Library_parseHumanDate(value, inFormat, forceValue){
  /* return res.month 1-12, res.day 1-31*/
  var res = {'year': false, 'month': false, 'day': false, 'format': false};
  var d_arr = null;
  if (!inFormat){
    if (value.indexOf(".") != -1) {
      d_arr = value.split(".");
      res.day = d_arr[0] && !isNaN(d_arr[0]*1) ? d_arr[0] : false;
      res.month = d_arr[1] && !isNaN(d_arr[1]*1) ? d_arr[1] : false;
      res.year = d_arr[2] && !isNaN(d_arr[2]*1) ? d_arr[2] : false;
      res.format =  'd.m.Y';
      res.separator = '.';
    } else if(value.indexOf("-") != -1) {
      d_arr = value.split("-");
      res.year = d_arr[0] && !isNaN(d_arr[0]*1) ? d_arr[0] : false;
      res.month = d_arr[1] && !isNaN(d_arr[1]*1) ? d_arr[1] : false;
      res.day = d_arr[2] && !isNaN(d_arr[2]*1) ? d_arr[2] : false;
      res.format =  'Y-m-d';
      res.separator = '-';    
    } else if(value.indexOf("/") != -1) {
      d_arr = value.split("/");
      res.month = d_arr[0] && !isNaN(d_arr[0]*1) ? d_arr[0] : false;
      res.day = d_arr[1] && !isNaN(d_arr[1]*1) ? d_arr[1] : false;
      res.year = d_arr[2] && !isNaN(d_arr[2]*1) ? d_arr[2] : false;
      res.format =  'm/d/Y';
      res.separator = '/';    
    } else if(value.indexOf("_") != -1) {
      d_arr = value.split("_");
      res.year = d_arr[0] && !isNaN(d_arr[0]*1) ? d_arr[0] : false;
      res.month = d_arr[1] && !isNaN(d_arr[1]*1) ? d_arr[1] : false;
      res.day = d_arr[2] && !isNaN(d_arr[2]*1) ? d_arr[2] : false;
      res.format =  'Y_m_d';      
      res.separator = '_';
    }
  } else {
    res.format = inFormat;
    var con = new Array();
    res.separator = false;
    for (var iLet = 0; iLet < inFormat.length; iLet++){ //parsovani formatu
      switch (inFormat.charAt(iLet)){
        case 'y':
        case 'Y':
          con.push('year');
          break;
        case 'm':  
        case 'M':  
          con.push('month');
          break;        
        case 'd':  
        case 'D':  
          con.push('day');
          break;        
        case '-':  
        case '/':  
        case '.':  
        case '_':  
          res.separator = inFormat.charAt(iLet);
          break;        
        default:
          break;        
      }
    }
    if (con && res.separator){ //parsovani hodnoty
      d_arr = value.split(res.separator);
      for (var i = 0; i < d_arr.length; i++){
        if (!con[i] || isNaN(d_arr[i]*1)) continue;
        res[con[i]] = d_arr[i]*1;
      }
    }
  }

  if (forceValue){
    if (forceValue.year) res.year = forceValue.year;
    if (forceValue.month || forceValue.month === 0) res.month = forceValue.month+1;/*vstup 0..11*/
    if (forceValue.day) res.day = forceValue.day;
  }
  
  if (inFormat) format = inFormat;
  if (res.year<100){// prevod year -> full Year
    if (res.year>=70) res.year += 1900;
    else res.year += 2000;
  }
  return res;
}
/* pozor na  problemy typu:
     31.5.2009 -> 1.6.2009
     10.2.2009 -> 30.4.2009  
*/
function Library_getHumanToDate(value, params){
  if (!params) params = new Array();
  var dateVal = params.defaultDate ? params.defaultDate : new Date();
  var dateAry = Library_parseHumanDate(value, params.format, params.forceValue);
  var day = dateAry.day;
  var month = dateAry.month - 1;
  var year = dateAry.year;
  var checkDate = null;

  if ((year !== false && !isNaN(year * 1) && (year > 0))
    && (month !== false && !isNaN(month * 1) && (month>=0))
    && (day !== false && !isNaN(day * 1) && (day >=0))){ // existuje-li datum zadane uplne
    
    checkDate = new Date(year, month-1, day);
    if (year == checkDate.getFullYear() && month-1 == checkDate.getMonth() && day == checkDate.getDate()){
      dateVal = Library_setDateLimits(year, month , day , dateVal, params.minimalDate, params.maximumlDate);
      return dateVal;      
    }    
  } else if ((month !== false && !isNaN(month * 1) && (month>=0))
    && (day !== false && !isNaN(day * 1) && (day >=0))){ // existuje-li datum bez specifikace roku
    checkDate = new Date(dateVal.getFullYear(), month-1, day);
    if (month-1 == checkDate.getMonth() && day == checkDate.getDate()){
      dateVal = Library_setDateLimits(dateVal.getFullYear(), month , day , dateVal, params.minimalDate, params.maximumlDate);
      return dateVal;  
    }
  }

  checkDate = new Date(dateVal);
//  checkDate.setDate(1); // viz problemy v zakladu -> vyreseno dosazenim, 31.3.09 -> false.4.09 => 31.3.09, ale nyni 31.4. = 1.5.09
  
  var useYear = false;
  var useMonth = false;
  var useDay = false;
  var checksDate = null;

  if (year !== false && !isNaN(year * 1) && (year > 0)){
    checkDate.setFullYear(year);
    useYear = true;
  }
  if (month !== false && !isNaN(month * 1) && (month>=0)){
    checksDate = new Date(checkDate);
    checksDate.setMonth(month);
    if (month*1 == checksDate.getMonth()){ // proti 13.mesici etc.
      checkDate = checksDate;
      useMonth = true;
    }
  }
  if (day !== false && !isNaN(day * 1) && (day >=0)){
    checksDate = new Date(checkDate);
    checksDate.setDate(day);
    if (day*1 == checksDate.getDate()){ // proti 30.2. etc.
      checkDate = checksDate;
      useDay = true;
    }
  }    
    
  dateVal = Library_setDateLimits(useYear ? year : false, useMonth ? month : false, useDay ? day : false, dateVal, params.minimalDate, params.maximumlDate);
  return dateVal;
}

function Library_setDateLimits(y,m,d, defaultDate, minDate, maxDate){
  var checkDate = new Date(defaultDate);
  var validSet = ['d','m','y'];
  if (minDate && checkDate < minDate) return minDate;
  if (maxDate && checkDate > maxDate) return maxDate;
  
  for (var iSet = validSet.length; iSet>0; iSet--){
    var resDate = null;
    if (iSet == validSet.length && y !== false && m !== false && d !== false){
      resDate = new Date(y,m,d);
    } else {
      resDate = new Date(defaultDate);
      for (var iDate = 0; iDate < iSet; iDate++){
        if (validSet[iDate] == 'y'){
          if (y !== false)
            resDate.setFullYear(y);
        }
        if (validSet[iDate] == 'm'){
          if (m !== false)
            resDate.setMonth(m);
        }
        if (validSet[iDate] == 'd'){
          if (d !== false)
            resDate.setDate(d);
        }
      }
    }
    for (var i = iSet; i < validSet.length; i++){ // vybalancovani do rozsahu
      if (validSet[i] == 'd'){
        if (minDate && resDate < minDate) resDate.setDate(minDate.getDate());
        else if (maxDate && resDate > maxDate) resDate.setDate(maxDate.getDate());
      }
      if (validSet[i] == 'm'){
        if (minDate && resDate < minDate){ 
          resDate.setMonth(minDate.getMonth());
          if (resDate < minDate) resDate.setMonth(minDate.getMonth()+1);
        } else if (maxDate && resDate > maxDate){
          resDate.setMonth(maxDate.getMonth());
          if (resDate > maxDate) resDate.setMonth(maxDate.getMonth()-1);
        }
      }
      if (validSet[i] == 'y'){
        if (minDate && resDate < minDate){ 
          resDate.setMonth(minDate.getFullYear());
          if (resDate < minDate) resDate.setFullYear(minDate.getFullYear()+1);
        } else if (maxDate && resDate > maxDate){
          resDate.setMonth(maxDate.getFullYear());
          if (resDate > maxDate) resDate.setFullYear(maxDate.getFullYear()-1);
        }
      }
    }
    if ((!minDate || resDate >= minDate) && (!maxDate || resDate <= maxDate)) return resDate;
  }
  return false;
}

function Library_checkHumanDate(value, params){ // pokud je v poradku, vrati true, jinak vraci navrhovanou opravu
  if (!params) params = new Array();
  var dateVal = Library_getHumanToDate(value, params); // vcetne aplikace ohraniceni
  var dateAry = Library_parseHumanDate(value, params.format, params.forceValue);

  var day = dateAry.day;
  var month = dateAry.month - 1;
  var year = dateAry.year;

  if (year === false || isNaN(year * 1) || (year < 0) || year != dateVal.getFullYear()){
    return Library_getDateToHuman(dateVal, dateAry.format);
  }
  if (month === false || isNaN(month * 1) || (month < 0) || month != dateVal.getMonth()){
    return Library_getDateToHuman(dateVal, dateAry.format);
  }
  if (day === false || isNaN(day * 1) || (day < 0) || day != dateVal.getDate()){
    return Library_getDateToHuman(dateVal, dateAry.format);
  }    
  return false;
}

function Library_getDateToHuman(dat, format){
  if (!format) format = 'd.m.Y';
  if (!(dat instanceof Date)) return '';
  var res = '';
  var oper = '';
  var last = false;
  for (var i = 0; i < format.length; i++){
    oper = format.substring(i,i+1);
    if (oper == last) continue;
    switch (oper){
      //cas
      case 'h': res += dat.getHours() % 12; break;// 0-12
      case 'H': res += dat.getHours(); break;// 0-23
      case 'i': res += dat.getMinutes(); break;
      case 's': res += dat.getSeconds(); break;
      case 'a': res += dat.getHours()<12 ? 'am' : 'pm'; break;
      case 'A': res += dat.getHours()<12 ? 'AM' : 'PM'; break;
      //datum
      case 'Y': res += dat.getFullYear(); break;
      case 'y': res += dat.getYear(); break;
      case 'm': res += (dat.getMonth() < 9 ? '0' : '')+(dat.getMonth()+1); break;
      case 'j': res += dat.getMonth()+1; break;
      case 'd': res += (dat.getDate() < 10 ? '0' : '')+dat.getDate(); break;
      case 'n': res += dat.getDay(); break;
      case 'w': res += dat.getDay(); break;
      default: res += oper;
    }
    last = oper;
  }
  return res;
}

function Library_compareDates(part, date1, date2, supposedVal, isGreater){
  var today = new Date(date1);
  var secDate = new Date(date2);
  if (!part) part = '';
  switch (part.toUpperCase()){
    case 'Y':
      Library_resetTime(secDate, 'Y');
      Library_resetTime(today, 'Y');
      if (supposedVal || supposedVal !== 0) today.setFullYear(supposedVal);
    break;
    case 'M':
       Library_resetTime(secDate, 'M');
       Library_resetTime(today, 'M');
       if (supposedVal || supposedVal !== 0) today.setMonth(supposedVal);
    break;
    case 'D':
    case '':
       Library_resetTime(secDate, 'D');
       Library_resetTime(today, 'D');
       if (supposedVal || supposedVal !== 0) today.setDate(supposedVal);
    break;
    case 'Y-M-D':
    case 'D.M.Y':
       var separ = false;
       if (part.toUpperCase() == 'Y-M-D') separ = '-';
       if (part.toUpperCase() == 'D.M.Y') separ = '.';
       Library_resetTime(secDate, 'D');
       Library_resetTime(today, 'D');
       if (supposedVal) {
          supposedVal = supposedVal.split(separ);
          if ((supposedVal.length != 3) || isNaN(1*supposedVal[0]) || isNaN(1*supposedVal[1]) || isNaN(1*supposedVal[2])){
            Library_debugAlert('bad type for new Enter of date for compare');
            return false;
          } else {
            today.setFullYear(supposedVal[0]);
            today.setMonth(supposedVal[1]);
            today.setDate(supposedVal[2]);
          }
       }
    break;
    default:
      Library_debugAlert('unrecognized part of date for compare:'+part);
      return false;
    break;
  }
  return isGreater ? today > secDate : today < secDate;
}

function Library_resetTime(date, part){
  date.setHours(0, 0, 0, 0);
  if (!part || part == "D") return date;
  date.setDate(1);
  if (part == "M") return date;
  date.setMonth(1);
  return date;
}

/********************/
function Library_getStyle(x,styleProp)
{
	if (x.currentStyle)
		var y = x.currentStyle[styleProp];
	else if (window.getComputedStyle)
		var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
	return y;
}
/** Ajax Library functions **/

var LibraryVar_ajaxRequests = new Array();
var LibraryVar_ajaxRequestsObjects = new Array();
var LibraryVar_ajaxRequestsPostData = new Array();

function Library_ajaxRequest(type, url, handler, element, delay, post) {
  var httpRequest = false;
  post = post ? 1 : 0;
  var postData = null;

  if (post) {
    var urlDataStart = url.indexOf('?');
    if (urlDataStart > -1) {
      postData = url.substring(urlDataStart + 1, url.length);
      url = url.substring(0,urlDataStart);
    }
  }

  if (window.XMLHttpRequest) {
    httpRequest = new XMLHttpRequest();
    if (httpRequest.overrideMimeType) {
      httpRequest.overrideMimeType('text/xml');
    }
  } else if (window.ActiveXObject) { 
    try {
      httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
        alert('Problem with generating ajax request');
      }
    }
  }
  if (httpRequest) {
    var ident = Math.random();
    LibraryVar_ajaxRequests[type] = ident;
    LibraryVar_ajaxRequestsObjects[type] = httpRequest;
    LibraryVar_ajaxRequestsPostData[ident] = postData;
    httpRequest.onreadystatechange = function () { handler(httpRequest, type, ident, element); };
    httpRequest.open(post ? 'POST' : 'GET', url, true);
    if (!delay) {
      Library_ajaxRequestSend(httpRequest, post, postData);
    } else {
      window.setTimeout("Library_ajaxRequestDelayed('"+ type +"','"+ ident +"',"+ post +");", delay);
    }
    return ident;
  }
  return false;
}

function Library_ajaxRequestDelayed(type, ident, post) {
  if (LibraryVar_ajaxRequests[type] == ident) {
    Library_ajaxRequestSend(LibraryVar_ajaxRequestsObjects[type], post, LibraryVar_ajaxRequestsPostData[ident]);
  }
}

function Library_ajaxRequestSend(httpRequest, post, postData) {
  httpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");/* usable for debug infos */
  if (post) {
    httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    httpRequest.setRequestHeader("Content-length", postData.length);
    httpRequest.setRequestHeader("Connection", "close");
  }
  httpRequest.send(postData);
}

function Library_ajaxUrlEncode(val) {
  var ret = val.toString();
  return encodeURIComponent(ret);
}

function Library_ajaxHashActualizationResultHandler(httpRequest, type, ident, element) {
  if (httpRequest.readyState == 4 && LibraryVar_ajaxRequests[type] == ident) {
    if (httpRequest.status == 200) {
      var errors = httpRequest.responseXML.getElementsByTagName('error');
      if (errors.length) {
        for (var i = 0; i < errors.length; i++){
          alert(errors[i].nodeValue);
        }
      }
      
      LibraryVar_ajaxRequests[type] = null;
      LibraryVar_ajaxRequestsObjects[type] = null;  
    }
  }
}



// ---modules/Hotels.SetDateButtons---
// MODULE HOTELS - SETDATEBUTTONS

if (!window.HotelDetails)
window.HotelDetails = new Object;

function AO3searchFormHotelsSetDateButtonsHandlerAdd() {
//  AO3searchFormHotelRoomInfoButtonsHandlerAdd();
  AO3searchFormHotelInfoButtonsHandlerAdd(); //-->konverze musi predejit destinationhandleradd

  if (window.showNavigPageAddHandler){ // rozjeti JS navigatoru
    showNavigPageAddHandler('hotelPage');
  }

  if (window.HotelDetails && (window.HotelDetails.blockShort || window.HotelDetails.forceChangeDate)){
    AO3searchFormHotelsDestinationHandlerAdd();
    AO3stepOne2setTimeHandlerAdd();
    AO3stepOne2buttDestinationHandlerAdd();
    AO3stepOne2FormOnsubmitHandlerAdd();
  }
}

/* ????? */
function AO3searchFormHotelRoomInfoButtonsHandlerAdd(){
  var inps = document.getElementsByTagName('TD');
  for (var i = 0; i<inps.length; i++){
    if (Library_hasClass(inps[i], 'basicRoomInfo')){
      inps[i].onclick = AO3searchFormHotelInfoButtonHandler;
      var id = inps[i].id.substring(7); // infoRef
      inps[i].targetDiv = document.getElementById('roomDetail'+id);
      inps[i].targetDiv.displayStyle = 'table-row';
      inps[i].onclick();
    }
  }
}
/*
function AO3searchFormHotelInfoButtonHandler(e){
  if (this.targetDiv.style.display == 'none'){
    this.targetDiv.style.display = this.targetDiv.displayStyle;
  } else {
    this.targetDiv.style.display = 'none';
  }
  return false;
}
*/function AO3searchFormHotelInfoButtonHandler(e){
  if (this.targetDiv){
    if (Library_hasClass(this.targetDiv, 'simpleHotelDetail')) { window.scrollTo(getPageXOffset(),Library_getOffsetTop(this.parentNode.parentNode.parentNode) - 10); }
    this.targetDiv.style.display = 'block';
  }
  if (this.oldDiv){
    this.oldDiv.style.display = 'none';
  }
  return false;
}

function AO3relatedShowFullListButtonHandler(e) {
 document.location.href = this.lastHref;
 return false;
}

function replaceTextByInputButton(a){
  var inp = document.createElement('input');
  var type = a.className.indexOf('Choose') ? 'submit' : 'button';
  inp.type = type;
  inp.value = a.innerHTML;
  inp.className = a.className + (type == 'submit' ? ' buttonContinue inputSubmit' : '');
  inp.lastHref = a.href;
  inp.id = a.id;
  a.id = '';
  a.parentNode.insertBefore(inp, a);
  inp.parentNode.removeChild(a);
  return inp;
}

function AO3searchFormHotelInfoButtonsHandlerAdd(){
  var inps = document.getElementsByTagName('A');
  window.HotelDetails.changeDateButtons = new Array();
  for (var i = inps.length-1; i >= 0; i--){
    if (Library_hasClass(inps[i], 'buttonCheckAvailability') ){
      var but = replaceTextByInputButton(inps[i]);
      but.way = 'hotel';
      but.hotelId = but.id.substring(28);//hotelCheckAvailabilityButton#num
      var spans = but.parentNode.parentNode.parentNode.getElementsByTagName('SPAN');
      for (var k = 0; k<spans.length; k++){
        if (Library_hasClass(spans[k], 'hotelName')){
          but.locLabel = spans[k].innerHTML;
        }
      }
      window.HotelDetails.changeDateButtons[but.id] = but;
    }

    if (Library_hasClass(inps[i], 'buttonChangeDate') ){
      var but = replaceTextByInputButton(inps[i]);
      but.way = 'hotel';
      but.hotelId = but.id.substring(21);//hotelChangeDateButton#num
      var spans = but.parentNode.parentNode.parentNode.getElementsByTagName('SPAN');
      for (var k = 0; k<spans.length; k++){
        if (Library_hasClass(spans[k], 'hotelName')){
          but.locLabel = spans[k].innerHTML;
        }
      }
      window.HotelDetails.changeDateButtons[but.id] = but;
    }

    if (Library_hasClass(inps[i], 'buttonCheckAvailability_short') ){
      var but = replaceTextByInputButton(inps[i]);
      but.way = 'hotel';
      but.hotelId = but.id.substring(34);//hotelCheckAvailability_shortButton#num
      var spans = but.parentNode.parentNode.parentNode.getElementsByTagName('SPAN');
      for (var k = 0; k<spans.length; k++){
        if (Library_hasClass(spans[k], 'hotelName')){
          but.locLabel = spans[k].innerHTML;
        }
      }
      window.HotelDetails.changeDateButtons[but.id] = but;
    }

    if (Library_hasClass(inps[i], 'buttonChangeDate_short') ){
      var but = replaceTextByInputButton(inps[i]);
      but.way = 'hotel';
      but.hotelId = but.id.substring(27);//hotelChangeDate_shortButton#num
      var spans = but.parentNode.parentNode.parentNode.getElementsByTagName('SPAN');
      for (var k = 0; k<spans.length; k++){
        if (Library_hasClass(spans[k], 'hotelName')){
          but.locLabel = spans[k].innerHTML;
        }
      }
      window.HotelDetails.changeDateButtons[but.id] = but;
    }

    if (Library_hasClass(inps[i], 'buttonChoose') ){
      var but = replaceTextByInputButton(inps[i]);
      but.way = 'hotel';
      but.hotelId = but.id.substring(17);//hotelChooseButton#num
      but.name = 'data[hotels][dbId'+but.hotelId+']';
    }

    if (Library_hasClass(inps[i], 'buttonChoose_short') ){
      var but = replaceTextByInputButton(inps[i]);
      but.way = 'hotel';
      but.hotelId = but.id.substring(23);//hotelChooseButton_short#num
      but.name = 'data[hotels][dbId'+but.hotelId+']';
    }
//zobrazit | skryt
    if (Library_hasClass(inps[i], 'buttonDetail') ){
      var but = replaceTextByInputButton(inps[i]);
      var id = but.id.substring(17);//hotelDetailButton#num
      but.targetDiv = document.getElementById('hotelDetail'+id);
      but.oldDiv = document.getElementById('hotelShort'+id);
      but.onclick = AO3searchFormHotelInfoButtonHandler;
      if (window.HotelDetails && window.HotelDetails.blockShort){
      //  but.onclick();
      }
      var searchShort = document.getElementById('hotelShortButton'+id);
      var searchDetailDiv = document.getElementById('hotelDetailButtons'+id);
      if (!searchShort && searchDetailDiv){ // nema - li parovy prepinac, doplni jej
        var d = document.createElement('div');
        d.className = "hotelShortButtonDiv bCloseHotelInformationsDiv";
        var el = document.createElement('input');
        el.type = 'button';
        el.value = window.parametr.hotelShort;
        el.id = 'hotelShortButton'+id;
        el.className = 'buttonShort bCloseHotelInformations';
        el.targetDiv = document.getElementById('hotelShort'+id);
        el.oldDiv = document.getElementById('hotelDetail'+id);
        el.onclick = AO3searchFormHotelInfoButtonHandler;
        searchDetailDiv.insertBefore(d, searchDetailDiv.firstChild);
        d.appendChild(el);
      }
    }
    if (Library_hasClass(inps[i], 'buttonShort') ){
      var but = replaceTextByInputButton(inps[i]);
      var id = but.id.substring(16);//hotelShortButton#num
      but.targetDiv = document.getElementById('hotelShort'+id);
      but.oldDiv = document.getElementById('hotelDetail'+id);
      but.onclick = AO3searchFormHotelInfoButtonHandler;

      if (window.HotelDetails && window.HotelDetails.blockShort){
      } else {
        inps[i].onclick();
      }


    }
   if (Library_hasClass(inps[i], 'relatedShowFullListButton')) {
     var but = replaceTextByInputButton(inps[i]);
     but.onclick = AO3relatedShowFullListButtonHandler;
   }
  }
}

/*********************************************************/
/*                                                       */
/*                                                       */
/*              F O R    N O   D A T E                   */
/*                                                       */
/*                                                       */
/*********************************************************/



function AO3searchFormHotelsDestinationHandlerAdd(){
  var targetForm = document.getElementById('AO3searchHotelFormDiv');
  if (targetForm){
    targetForm.mouseOver = false;
    targetForm.mouseDown = false;
    targetForm.style.display = 'none';
    targetForm.style.zIndex = 20;
    targetForm.targetInput = document.getElementById('AO3_HotelsStepOne_HotelDbId');
    targetForm.targetText = document.getElementById('AO3_HotelsStepOne_HotelName');
    targetForm.service = document.getElementById('AO3_HotelsStepOne_serviceDiv');
    targetForm.locDesc = document.getElementById('AO3_HotelsStepOne_DescrHotelName');
    targetForm.locStep = document.getElementById('AO3_HotelsStepOne_buttonContinue');
    targetForm.targetText.parentNode.style.display = 'block';

    targetForm.onmouseover = AO3searchFormDestinationDivOverHandler;
    targetForm.onmouseout = AO3searchFormDestinationDivOutHandler;

    targetForm.onmouseup = AO3searchFormDestinationDivMouseUpHandler;
    targetForm.onmousedown = AO3searchFormDestinationDivMouseDownHandler;
    targetForm.onmousemove = AO3searchFormDestinationDivMouseMoveHandler;

    var sel = targetForm.getElementsByTagName('select');
    for (var i in sel){
      sel[i].onmousedown = AO3searchFormDestinationSelectMouseDownHandler;
      sel[i].targetForm = targetForm;
    }

    var bhf = document.getElementById('buttonHideForm');
    if (bhf){
      bhf.onclick = AO3searchFormDestinationDivHideHandler;
    }
    for (var i in window.HotelDetails.changeDateButtons){
      var bHand = window.HotelDetails.changeDateButtons[i];
      if (!bHand.id) continue;
      bHand.onclick = AO3searchFormDestinationButtonClickHandler;
      bHand.onmouseover = AO3searchFormDestinationButtonOverHandler;
      bHand.onmouseout = AO3searchFormDestinationButtonOutHandler;
      bHand.targetDiv = targetForm;
      bHand.destination = bHand.hotelId; //LinkToLocation
    }
    var inp = document.getElementById('AO3chooseHotelAvailabilityButton');
    if (inp){
      var pars = inp.lastHref;
      if (pars.indexOf('destination=')>0){
        pars = pars.substring(pars.indexOf('destination=')+12);
        pars = (pars.indexOf('&') > 0 ? pars.substring(0, pars.indexOf('&')) : pars);
      }
      var but = inp;//      var but = replaceTextByInputButton(inp);
      but.destination = pars;
      but.way = 'location';
      but.locLabel = window.HotelDetails.mainDestination;
/*   //provede jiny filtr
      but.onclick = AO3searchFormDestinationButtonClickHandler;
      but.onmouseover = AO3searchFormDestinationButtonOverHandler;
      but.onmouseout = AO3searchFormDestinationButtonOutHandler;
      but.targetDiv = targetForm;
*/    }
  }
}

function AO3searchFormDestinationButtonOverHandler(e){
  this.mouseOver = true;
  if (this.active && window.hideForm){
     window.clearTimeout(window.hideForm);
  }
}

function AO3searchFormDestinationDivOverHandler(e){
  this.mouseOver = true;
  if (window.hideForm){
    window.clearTimeout(window.hideForm);
  }
}

function AO3searchFormDestinationButtonOutHandler(e){
  this.mouseOver = false;
  if (this.active && !this.targetDiv.mouseOver){
//    window.hideForm = window.setTimeout('AO3searchFormDestinationDivHideHandler()', 500);
  }
}

function AO3searchFormDestinationDivOutHandler(e){
  this.mouseOver = false;
  this.mouseDown = false;
  if (!this.targetA.mouseOver){
//     window.hideForm = window.setTimeout('AO3searchFormDestinationDivHideHandler()', 500);
  }
}

function AO3searchFormDestinationDivHideHandler(){
  var targetForm = document.getElementById('AO3searchHotelFormDiv');
  if (targetForm){
    targetForm.targetA.active = false;
    targetForm.style.display = 'none';
  }
  return false;
}

function AO3searchFormDestinationDivMouseMoveHandler(e){
  if (!e) e = window.event;
  if (this.mouseDown){
    var x = this.style.left.substring(0, this.style.left.length -2) * 1;
    var y = this.style.top.substring(0, this.style.top.length -2) * 1;

    if (this.lastX){
      this.style.left = (x - (this.lastX - e.clientX)) + 'px';
    }
    if (this.lastY){
      this.style.top = (y - (this.lastY - e.clientY)) + 'px';
    }

    this.lastX = e.clientX;
    this.lastY = e.clientY;
    this.style.cursor = 'move';
  }
  return false;
}

function AO3searchFormDestinationDivMouseUpHandler(e){
  this.mouseDown = false;
  this.lastX = 0;
  this.lastY = 0;
  this.style.cursor = 'default';
  return false;
}

function AO3searchFormDestinationSelectMouseDownHandler(e){
  this.targetForm.selectMouseDown = true;
}

function AO3searchFormDestinationDivMouseDownHandler(e){
  if (this.selectMouseDown){
    this.selectMouseDown = false;
    return true;
  } else {
    this.mouseDown = true;
    return false;
  }
}

function AO3searchFormDestinationButtonClickHandler(e){
  this.active = true;
  if (window.hideForm){
    window.clearTimeout(window.hideForm);
  }
  if (this.targetDiv){
    this.targetDiv.mouseOver = true;
    this.targetDiv.style.display = 'block';
    this.targetDiv.style.position = 'absolute';
//    this.targetDiv.style.top = this.parentNode.offsetTop+'px';
    this.targetDiv.style.left = this.parentNode.offsetLeft+'px';
    this.targetDiv.targetA = this;
    this.targetDiv.targetInput.value = this.destination;

    this.targetDiv.targetText.value = unHTMLize(this.locLabel);

    if (this.way == 'hotel'){
      this.targetDiv.targetInput.name = 'data[hotelDbId]';
      this.targetDiv.targetText.name = 'data[hotelName]';
      this.targetDiv.locDesc.innerHTML = window.parametr.hotelName;
      this.targetDiv.locStep.name = 'data[stepChooseHotelAndRooms]';
      this.targetDiv.locStep.value = window.parametr.roomFind;
      this.targetDiv.style.left = Library_getOffsetLeft(this)+'px';
      this.targetDiv.style.top = (Library_getOffsetTop(this)-164)+'px';
      if (this.targetDiv.service) this.targetDiv.service.style.display = 'none';
    }

    if (this.way == 'location'){
      this.targetDiv.targetInput.name = 'data[location]';
      this.targetDiv.targetText.name = 'data[locationSearch]';
      this.targetDiv.locDesc.innerHTML = window.parametr.location;
      this.targetDiv.locStep.name = 'data[stepChooseHotel]';
      this.targetDiv.locStep.value = window.parametr.hotelFind;
      this.targetDiv.style.top = (Library_getOffsetTop(this)+this.offsetHeight)+'px';
      if (this.targetDiv.service) this.targetDiv.service.style.display = 'block';
    }
  }
  return false;
}

function AO3stepOne2buttDestinationHandlerAdd(){
  var wayType = ['location'];
  for (var wayIndex in wayType){
    var way = wayType[wayIndex];
    var el = document.getElementById('AO3_HotelsStepOne_'+way+'Button');
    if (el && !el.onclick){
      el.onclick = AO3stepOne2buttonDestinationHandler;
    }

  }
}

function AO3stepOne2buttonDestinationHandler(e){
  if (!e) { e = window.event; }
   var b = document.getElementById('AO3_HotelsStepOne_buttonContinue');
   b.name=this.name;
   window.notCheck = true;
   b.click();
}

/** Nastaveni casu **/
function AO3stepOne2setTimeHandlerAdd(){
  var wayType = ['start', 'end'];
  for (var wayIndex in wayType){
    var way = wayType[wayIndex];
//    alert(way);
    var elDay = document.getElementById('AO3_HotelsStepOne_'+way+'Day');
    elDay.onchange = AO3stepOne2checkTimeHandler;
    var elMonth = document.getElementById('AO3_HotelsStepOne_'+way+'Month');
    elMonth.onchange = AO3stepOne2checkTimeHandler;
    var elCal = document.getElementById('AO3_HotelsStepOne_'+way+'Calendar');
    elCal.style.display = 'inline';
    elCal.way = way;
    elCal.onclick = AO3stepOne2getCalendarHandler;
    elMonth.onchange();
  }
}

function AO3stepOne2getCalendarHandler(e){
  if (!e) { e = window.event; }
//id ... [arrival|departure]
  var params = new Array();
  params['elDay'] = document.getElementById('AO3_HotelsStepOne_'+this.way+'Day');
  params['elMonthYear'] = document.getElementById('AO3_HotelsStepOne_'+this.way+'Month');
  ShowCalendar(params);
  return false;
}

function AO3stepOne2checkTimeHandler(e){
  if (!e) { e = window.event; }
  var params = new Array();
  var lastCheck = 'toDay';
  params['elFromDay'] = document.getElementById('AO3_HotelsStepOne_startDay');
  switch (lastCheck){
    case 'toDay':
      params['elToDay'] = document.getElementById('AO3_HotelsStepOne_endDay');
    case 'toMonth':
      params['elToMonth'] = document.getElementById('AO3_HotelsStepOne_endMonth');
    case 'fromDay':
      params['elFromDay'] = document.getElementById('AO3_HotelsStepOne_startDay');
    case 'fromMonth':
      params['elFromMonth'] = document.getElementById('AO3_HotelsStepOne_startMonth');
    default:
    break;
  }
  params['keepInterval'] = 3600*24*window.parametr.defaultEndDateDelta;
  params['allowWrongDate'] = true;//'future';
  params['autoModify'] = 'from';//'both';

  params['caller'] = this;
  var lastParams = params;
  ergonomicTimeAdjustment(params);
  ergonomicTimeAdjustment(lastParams); // this is not bug !
}
// overovani formulare pred odeslani

function AO3stepOne2FormOnsubmitHandlerAdd(){
  var forms = document.getElementsByTagName('FORM');
  for (var i=0; i< forms.length; i++){
    if (Library_hasClass(forms[i], 'ao3StepOne') ||
        Library_hasClass(forms[i], 'ao3StepChooseHotelsByService')) {
      forms[i].onsubmit = AO3stepOne2FormOnsubmitHandler;
    }
  }
}

function AO3stepOne2FormOnsubmitHandler(){
  //fareDisplayWithFlightUnion
//  alert(window.notCheck);
  if (window.notCheck){ window.notCheck = false; return true;}
  //povinne udaje

  var HotDes = document.getElementById('AO3_HotelsStepOne_HotelName');
  if (HotDes && HotDes.value){

  } else {
    var hotelLoc = document.getElementById('AO3_HotelsStepOne_location');
    if (hotelLoc){
      var val = '';
      if (hotelLoc.tagName == 'INPUT') val = hotelLoc.value;
      if (hotelLoc.tagName == 'SELECT') val = hotelLoc.options[hotelLoc.selectedIndex].value;
      if (val == ''){
        alert (window.parametr.noLocationFilled);
        return false;
      }
      var sBut = document.getElementById('AO3_HotelsStepOne_buttonContinue');
      sBut.name = 'data[stepChooseHotel]';
    }
  }

  var params = new Array();
  var lastCheck = 'toDay';
  switch (lastCheck){
    case 'toDay':
      params['elToDay'] = document.getElementById('AO3_HotelsStepOne_endDay');
    case 'toMonth':
      params['elToMonth'] = document.getElementById('AO3_HotelsStepOne_endMonth');
    case 'fromDay':
      params['elFromDay'] = document.getElementById('AO3_HotelsStepOne_startDay');
    case 'fromMonth':
      params['elFromMonth'] = document.getElementById('AO3_HotelsStepOne_startMonth');
    default:
    break;
  }

  switch (onSubmitCalendarData(params)){
    case 'INVALID_FROM':
    case 'INVALID_TO':
      alert(window.parametr.invalidDate);
      return false;
    case 'LESS_FROM':
    case 'LESS_TO':
      alert(window.parametr.lessDate);
      return false;
    case 'CROSS_DATES':
      alert(window.parametr.crossDates);
      return false;
    default:
    break;
  }

  var startDay = document.getElementById('AO3_HotelsStepOne_startDay');
  var endDay = document.getElementById('AO3_HotelsStepOne_endDay');
  var startMonth = document.getElementById('AO3_HotelsStepOne_startMonth');
  var endMonth = document.getElementById('AO3_HotelsStepOne_endMonth');
  if (startDay && startMonth && endDay && endMonth){
    var val = '';
    if (startMonth.value +'-'+ startDay.value == endMonth.value +'-'+ endDay.value)
    alert (window.parametr.minimalDurationExceeded);
//    return false;
  }
  return true;
}

function unHTMLize(str) {
  return str.replace('&amp;', '&');
}
// ---GuiSearchFormHotels2---
function getDivFormButton(trida){
    var divs = document.getElementsByTagName('div');
    if (!trida)trida = 'formButtons';
    var pred = null;
    for(var i=0;i<divs.length;i++){
      if (Library_hasClass(divs[i], trida)) pred = divs[i];
    }
    return pred;
  }

  function getPageXOffset() {
    var x;
    if (self.pageXOffset) { // all except Explorer
      x = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
      x = document.documentElement.scrollLeft;
    } else if (document.body) { // all other Explorers
      x = document.body.scrollLeft;
    }
    return x;
  }

  function AO3searchFormHotels2HandlerAdd(){
  }
// ---GuiSearchFormHotels2StepChooseHotelsByService---
function AO3searchFormHotels2stepChooseHotelsByServiceHandlerAdd() {
  if (window.AO3searchFormHotelsSetDateButtonsHandlerAdd) AO3searchFormHotelsSetDateButtonsHandlerAdd();
  //pokud obshuje module GalleryForImages
  if (window.AO3searchFormHotelImageGalleryButtonNavigHandlerAdd) AO3searchFormHotelImageGalleryButtonNavigHandlerAdd();
  AO3stepOne2FormChooseRegionHandlerAdd();
  AO3stepOne2FormChooseRegionByHashHandler();
}

function AO3stepOne2FormChooseRegionByHashHandler() {
  var rid = window.urlHash.get("sub");
  if (rid) {
    var inp = document.getElementById('linkRegion'+rid);
//odkomentovat pokud se to ma vracet na cely stat, ne na subregion
//    inp.onclick();
  }
}

function AO3stepOne2FormChooseRegionHandlerAdd(){
  if (!window.hotelByService) window.hotelByService = new Object();
  if (!window.hotelByService.destinations) window.hotelByService.destinations = new Array();
  if (!window.hotelByService.regions) window.hotelByService.regions = new Array();
//  window.hotelByService.regions = new Array();
  for (var did in window.hotelByService.destinations){
    if (did == 'length') continue;
    var d = document.getElementById('fiDestination_'+did+'Div');
    if (d) window.hotelByService.destinations[did] = d;
    else alert('not found destination '+did);
  }
  for (var rid in window.hotelByService.regions){
    if (rid == 'length') continue;
    for (var hid in window.hotelByService.regions[rid]){
      if (hid == 'length') continue;
      var h = document.getElementById('linkHotel'+hid);
      if (h){
        h.destination = window.hotelByService.regions[rid][hid].destination;
        h.region = rid;
        window.hotelByService.regions[rid][hid] = h;// pro pristup k elementu
      }
    }
    var r = document.getElementById('linkRegion'+rid);
    if (r){
      r.oblast = rid;
      r.onclick = AO3stepOne2FormChooseRegionHandler;
    } else {
     // console.log('not found region '+rid);
     alert('not found region '+rid);
    }
  }
  // all regions
  var r = document.getElementById('linkRegion');
  if (r){
    r.oblast = '';
    r.onclick = AO3stepOne2FormChooseRegionHandler;
  }
  window.hotelByService.navigationLabel = document.getElementById('NavigationList');

/*  var inps = document.getElementsByTagName('DIV');
  for (i = 0; i<inps.length; i++){
    if (inps[i].id.substring(0, 10) == 'linkRegion'){
      inps[i].oblast = inps[i].id.substring(10);
      for (var j in window.hotelByService.regions){
        if (inps[i].id.substring(10, 10 + j.length) == j){
          window.hotelByService.regions[j].push(inps[i]);
        }
      }
    }
  }*/
}

function AO3stepOne2FormChooseRegionHandler(){
  var selectedDis = true;
  var otherDis = (this.oblast == '');
  for (var j in window.hotelByService.destinations){
    if (j == 'length') continue;
    window.hotelByService.destinations[j].counter = 0;
  }
  for (var j in window.hotelByService.regions){
    if (j == 'length') continue;
    for (var i in window.hotelByService.regions[j]){
      if (i == 'length') continue;
      var obj = window.hotelByService.regions[j][i];
      if ((this.oblast == j) ? selectedDis : otherDis){
        window.hotelByService.destinations[window.hotelByService.regions[j][i].destination].counter ++;
        if (window.hotelByService.regions[j][i].style)
        obj.style.display = 'block';
      } else {
        if (window.hotelByService.regions[j][i].style)
        obj.style.display = 'none';
      }
    }
  }
  for (var j in window.hotelByService.destinations){
    if (j == 'length') continue;
    window.hotelByService.destinations[j].style.display = (window.hotelByService.destinations[j].counter == 0) ? 'none' : 'block';
  }

  if (window.hotelByService.navigationLabel){
    window.hotelByService.navigationLabel.innerHTML = this.innerHTML;
  }
  return false;
}
// ---modules/Hotels.GalleryForDetail---
window.imageCollection = new Array();

function AO3searchFormHotelLogoDescriptionHandlerAdd(){
  var spans = document.getElementsByTagName('DIV');
  for (var i = 0; i < spans.length; i++){
    if (Library_hasClass(spans[i], 'hotelLogo')){
      spans[i].description = window.parametr[spans[i].className.substring(10)];// bez casti s logem
      spans[i].AO3searchFormHotelLogoDescriptionMouseOverHandler = AO3searchFormHotelLogoDescriptionMouseOverHandler;
      spans[i].AO3searchFormHotelLogoDescriptionMouseOutHandler = AO3searchFormHotelLogoDescriptionMouseOutHandler;
      spans[i].onmouseover = spans[i].AO3searchFormHotelLogoDescriptionMouseOverHandler;
      spans[i].onmouseout = spans[i].AO3searchFormHotelLogoDescriptionMouseOutHandler;
      spans[i].id = "logoForDescription"+i;
      spans[i].activeDiv = false;
      spans[i].descriptionDiv = false;
    }
  }
}

function AO3searchFormHotelLogoDescriptionMouseOverHandler(){
  if (!this.activeDiv){
    if (this.timer){
      window.clearTimeout(this.timer);
    }
    this.activeDiv = true;
    this.timer = window.setTimeout('AO3searchFormHotelLogoDescriptionShowHandler("'+this.id+'")', 200);
//    return false;
  }
}

function AO3searchFormHotelLogoDescriptionDivMouseOverHandler(){
  if (!this.targetEl.activeDiv){
    if (this.targetEl.timer){
      window.clearTimeout(this.targetEl.timer);
    }
    this.targetEl.activeDiv = true;
//    return false;
  }
}

function AO3searchFormHotelLogoDescriptionDivMouseOutHandler(){
  if (this.targetEl){
    return this.targetEl.onmouseout();
  }
  return true;
}

function AO3searchFormHotelLogoDescriptionMouseOutHandler(){
  if (this.activeDiv){
    if (this.timer){
      window.clearTimeout(this.timer);
    }

    this.activeDiv = false;
    this.timer = window.setTimeout('AO3searchFormHotelLogoDescriptionHideHandler("'+this.id+'")', 200);
//    return false;
  }
}

function AO3searchFormHotelLogoDescriptionShowHandler(id){
  var el = document.getElementById(id);
  if (el){
//    document.getElementById('header').innerHTML += el.active'; ';
    if (!el.activeDiv || el.descriptionDiv) return false;

    var div = document.createElement('DIV');
    div.innerHTML = el.description;
    div.className = "hotelLogoDescription";
    div.id = el.id+'Div';
    div.style.position = 'absolute';
    div.style.left = Math.round(el.offsetWidth/4)+'px';
    div.style.top = (el.offsetHeight/2)+'px';
    div.style.zIndex = 100;
    div.targetEl = el;
    div.onmouseover = AO3searchFormHotelLogoDescriptionDivMouseOverHandler;
    div.onmouseout = AO3searchFormHotelLogoDescriptionDivMouseOutHandler;
    el.appendChild(div);
    el.descriptionDiv = div;
  }
  return true;
}

function AO3searchFormHotelLogoDescriptionHideHandler(id){
  var el = document.getElementById(id);
  if (el){
    if (el.activeDiv) return false;
    var elDiv = el.descriptionDiv;
    if (elDiv){
      elDiv.parentNode.removeChild(elDiv);
      el.descriptionDiv = false;
    }
  }
  return true;
}

function AO3searchFormHotelImageGalleryButtonNavigHandlerAdd(){
  for (var i in window.imageCollection){
    if (i.substring(0,6) != 'imgcol') continue;
    var id = i.substring(6);
//    alert (id);
    window.imageCollection[i].photo = document.getElementById('bigPhoto'+id);
    window.imageCollection[i].counter = document.getElementById('photoCounter'+id);
    var buttonUp = document.getElementById('imageUp'+id);
    if (buttonUp){
      buttonUp.imageId = id;
      buttonUp.way = 'up';
      buttonUp.title = window.parametr.imageForGalleryNext;
      buttonUp.onclick = AO3searchFormHotelImageGalleryButtonNavigHandler;
      buttonUp.onmouseover = AO3searchFormHotelImageGalleryMouseOverHandler;
      buttonUp.onmouseout = AO3searchFormHotelImageGalleryMouseOutHandler;
      window.imageCollection[i].buttonUp = buttonUp;

    }
    else Library_debugAlert('imageUp'+id);

    var buttonDown = document.getElementById('imageDown'+id);
    if (buttonDown){
      buttonDown.imageId = id;
      buttonDown.way = 'down';
      buttonDown.title = window.parametr.imageForGalleryPrevious;
      buttonDown.onclick = AO3searchFormHotelImageGalleryButtonNavigHandler;
      buttonDown.onmouseover = AO3searchFormHotelImageGalleryMouseOverHandler;
      buttonDown.onmouseout = AO3searchFormHotelImageGalleryMouseOutHandler;
      window.imageCollection[i].buttonDown = buttonDown;
    }
    else Library_debugAlert('imageDown'+id);

    var backBigDiv = document.getElementById('bigPhotoBackground'+id);
    if (backBigDiv){
      if (window.imageCollection[i].maxWidth) backBigDiv.style.width = window.imageCollection[i].maxWidth+'px';
      if (window.imageCollection[i].maxHeight) backBigDiv.style.height = window.imageCollection[i].maxHeight+'px';
    }
    var biDiv = document.getElementById('hotelBigImageDiv'+id);
    if (biDiv){
      biDiv.style.display = 'block';
    }

//set Links
    window.imageCollection[i].thumbs = new Array();
    for (var cnt = 0; cnt < window.imageCollection[i].amount; cnt++){
      if ( window.imageCollection[i].sources[cnt]){
        window.imageCollection[i].sources[cnt].detail.src = window.imageCollection[i].sources[cnt].detail.quickSrc; // oprava linku
      }
      // hotel detail mini
      var imageLnk = document.getElementById('imageForGallery_' + id + '_' + cnt);
      if (imageLnk){
        imageLnk.imageId = id;
        imageLnk.way = cnt;
        if (!imageLnk.title) imageLnk.title = window.parametr.imageForGalleryTitle + ' - ' + cnt;
        imageLnk.onclick = AO3searchFormHotelImageGalleryButtonNavigHandler;
        imageLnk.onmouseover = AO3searchFormHotelImageGalleryMouseOverHandler;
        imageLnk.onmouseout = AO3searchFormHotelImageGalleryMouseOutHandler;
        window.imageCollection[i].thumbs[cnt] = imageLnk; // pro pripad zameru nastylovat vybranou fotku
      }
      // hotel choose
      var imageShort = document.getElementById('shortImage' + id + '_' + cnt);
      if (imageShort){
        imageShort.imageId = id;
        imageShort.way = cnt;
        if (!imageShort.title) imageShort.title = window.parametr.imageForGalleryTitle + ' - ' + cnt;
        imageShort.targetDiv = document.getElementById('hotelDetail'+id);
        imageShort.oldDiv = document.getElementById('hotelShort'+id);
        imageShort.onclick = AO3searchFormHotelImageGalleryButtonNavigHandler;
        imageShort.onmouseover = AO3searchFormHotelImageGalleryMouseOverHandler;
        imageShort.onmouseout = AO3searchFormHotelImageGalleryMouseOutHandler;
      }
    }
    window.imageCollection[i].link = document.getElementById('hrefBigPhoto'+id);
//end set links
  }
  AO3searchFormHotelLogoDescriptionHandlerAdd();
  if (id == 'QQQ') {
    AO3searchFormHotelImageGalleryChangeImg(id,'none');
  }
}

function AO3searchFormHotelImageGalleryMouseOverHandler(e){
  self.status = window.parametr.imageForGalleryStatus + " " + this.title;
//  alert(self.status);
  return true;
}

function AO3searchFormHotelImageGalleryMouseOutHandler(e){
  self.status = self.defaultStatus;
  return true;
}

function AO3searchFormHotelImageGalleryButtonNavigHandler(){
  AO3searchFormHotelImageGalleryChangeImg(this.imageId , this.way);
  if (this.targetDiv){
    this.targetDiv.style.display = 'block';
    if (Library_hasClass(this.targetDiv, 'simpleHotelDetail')) { window.scrollTo(getPageXOffset(),Library_getOffsetTop(this.parentNode.parentNode.parentNode) - 10); }
  }
  if (this.oldDiv){
    this.oldDiv.style.display = 'none';
  }
  return false;
}

function AO3searchFormHotelImageGalleryShortHandler(){
  AO3searchFormHotelImageGalleryChangeImg(this.imageId , this.way);
  return false;
}

function AO3searchFormHotelImageGalleryChangeImg(id , way){
  var ic = window.imageCollection['imgcol'+id];
  var activ = ic.active;
  if (isNaN(way)){
    if (way == 'down'){ activ--; }
    if (way == 'up'){ activ++; }
  } else {
    activ = way;
  }

/*  if (activ < 0) activ = 0;
  if (activ >= ic.amount) activ = ic.amount;
  if (activ <= 0) ic.buttonDown.disabled = 'disabled';
  else ic.buttonDown.disabled = '';
  if (activ >= ic.amount-1) ic.buttonUp.disabled = 'disabled';
  else ic.buttonUp.disabled = '';
*/
  if (activ < 0) activ = ic.amount-1;
  if (activ >= ic.amount) activ = 0;

  if (ic.counter) ic.counter.innerHTML = activ+1;
  if (ic.sources[activ]){
    var activSource = ic.sources[activ].detail;
    ic.photo.src = activSource.src;
    ic.photo.alt = activSource.alt.replace(/&amp;/g,'&');
    var title = activSource.title ? activSource.title : activSource.alt;
    ic.photo.title = title;              /* velky obrazek */
    ic.photo.nextSibling.title = title;  /* transparentni vrstva */
    var width = activSource.width;
    var height = activSource.height;
    var maxH = window.imageCollection["imgcol"+id].maxHeight;
    var maxW = window.imageCollection["imgcol"+id].maxWidth;
    try{
        var expand = window.imageCollection["imgcol"+id].expand;
    } catch (err) {
        var expand = true;
    }
    if (maxH == undefined) { maxH = 350; }
    if (maxW == undefined) { maxW = 428; }
    if ((width <= maxW) || (height <= maxH)) {
        if (expand) {
            if (width <= maxW) {
                height = maxW / width * height;
                width = maxW;
            } else if (height <= maxH) {
                width = maxH / height * width;
                height = maxH;
            }
        }
    } else if ((width > maxW) && (height>maxH)) {
      if ((width/maxW) > (height/maxH)) {
       width = maxH / height * width;
       height = maxH;
      } else {
       height = maxW / width * height;
       width = maxW;
      }
    }
    ic.photo.width = width;
    ic.photo.height = height;
    ic.active = activ;
  }

  if (ic.link && ic.sources[activ].big){
    ic.sources[activ].big.src = ic.sources[activ].big.quickSrc;
    ic.link.href = ic.sources[activ].big.quickSrc;// + "&frame=photoPrew";
  }
}
// ---modules/ForAll.Calendar---
/** Datove fce **/

/**
* ShowCalendar(hash);
*
* Argumenty:
*   hash::elFromDay
*   hash::elFromMonth
*   hash::elFromTime (nepovinny)
*
*   hash::elToDay
*   hash::elToMonth
*   hash::elToTime (nepovinny)
*
*   hash::autoModify (none|from|to|both pri krizeni datumu provadeni automatickych oprav daneho datumu - from - mensi prilet na vetsi, Less povoluje datum pred aktualnim datem)
*   hash::allowWrongDate (true|false|future pro povoleni zadani neexistujiciho datumu - true , future - v budoucnu)
*
*   hash::keepInterval
*   - interval, ktery ma byt v pripade, ze se ma provest uprava datumu 'od' a 'do' dodrzet (delta)
*
*   hash::caller
*   - html element, ktery spousti funkci ergonomicTimeAdjustment, nutne to musi byt
*    jeden z elFrom* nebo elTo*
*   - podle nej se poznava, ktery datum ('od' nebo 'do') klient manualne nastavuje a ktery
*     ma byt automaticky prizpusoben
*
* nepovinne :
*   hash::windowWidth
*   hash::windowHeight
*   hash::months (default ... 1)
*/
function ergonomicTimeAdjustment(hash){
  /**
  * Argumenty:
  *   hash::elMonth... select-box `mesic`
  *   hash::elDay... select-box `den`
  *   hash::elTime... select-box `cas' (nepovinny)
  * Vraci:
  *   - objekt Date s datumem odpovidajicim hodnotam ve vstupnich polich
  *   - false v pripade, ze vstupni pole obsahuji nespravna data (napr. 31. zari)
  */

/*
  setDateOptionsStyle(hash);
  parseDate(hash);
  getRightDate(hash, delta);
  chooseSelectOption(elSelect, optionValue);
  __onDateValid(hash);
  __onDateInvalid(hash);
  saveDate(hash);
  getCurrentDate();
*/
  function setDateOptionsStyle(hash){
    //  - podbarvuje den dle validnich moznosti
    //  - predpokladany format vstupu ze select-boxu:
    //    - dny... D (cislo dne v mesici)
    //    - mesic, rok... parsovat z retezce YYYY-MM
    var strMonthYear = hash['elMonth'].value;
    var year = parseInt(strMonthYear.substring(0, 4), 10);
    var month = parseInt(strMonthYear.substring(5, 7), 10)-1;
    var day = parseInt(hash['elDay'].value, 10);
    var today = getCurrentDate();
//    var checkDate = new Date(year, month, day);
//    alert(hash['elDay'].id+'*'+hash['elDay'].options.length+' in '+year+'/'+month);
    for (var i = 0; i < hash['elDay'].options.length; i++){
      var dayCheck = parseInt(hash['elDay'].options[i].value, 10);
      var checkDate = new Date(year, month, dayCheck);// pri nastaveni dvou dnu nad limit by posunul mesic o 2
      var cn = 'rightDate';
      if (checkDate.getDate() != dayCheck) cn = 'inputError wrongDate';
      if (checkDate < today) {
       cn = 'inputError lowDate';
      }
      hash['elDay'].options[i].className = cn;
    }

    for (var i = 0; i < hash['elMonth'].options.length; i++){
      var cn = 'rightDate';
      // Kontrola relevance mesice
      if (i == hash['elMonth'].selectedIndex || false){ // at se ostatni mesice tvari jako OK
        var strMonthYearCheck = hash['elMonth'].options[i].value;
        var yearCheck = parseInt(strMonthYearCheck.substring(0, 4), 10);
        var monthCheck = parseInt(strMonthYearCheck.substring(5, 7), 10)-1;
        var checkDate = new Date(yearCheck, monthCheck, day);// pri nastaveni dvou dnu nad limit by posunul mesic o 2
        if (checkDate.getDate() != day) cn = 'inputError wrongDate';
        if (checkDate < today) {
         cn = 'inputError lowDate';
        }
      }
      hash['elMonth'].options[i].className = cn;
    }
  }

  function parseDate(hash){
    //  - predpokladany format vstupu ze select-boxu:
    //    - hodiny... HH:MM
    //    - dny... D (cislo dne v mesici)
    //    - mesic, rok... parsovat z retezce YYYY-MM
    var hour = 0; var minute = 0;

    if(hash['elTime']){
      var strTime = hash['elTime'].value;

      hour = parseInt(strTime.substring(0, 2), 10);
      if(!hour) hour = 0;

      minute = parseInt(strTime.substring(3), 10);
      if(!minute) minute = 0;
    }

    var day = parseInt(hash['elDay'].value, 10);

    var strMonthYear = hash['elMonth'].value;
    var year = parseInt(strMonthYear.substring(0, 4), 10);
    var month = parseInt(strMonthYear.substring(5, 7), 10)-1;

    var result = new Date(year, month, day, hour, minute);

    //  - test validity datumu (den v mesici)
    if (result.getDate() != day/* (result < new Date())*/)
      return false;
    else
      return result;
  }

  function getRightDate(hash, delta){
    if (!delta) delta = 0;
    //  - predpokladany format vstupu ze select-boxu - nespravne datum:
    var hour = 0; var minute = 0;

    if(hash['elTime']){
      var strTime = hash['elTime'].value;

      hour = parseInt(strTime.substring(0, 2), 10);
      if(!hour) hour = 0;

      minute = parseInt(strTime.substring(3), 10);
      if(!minute) minute = 0;
    }

    var day = parseInt(hash['elDay'].value, 10);

    var strMonthYear = hash['elMonth'].value;
    var year = parseInt(strMonthYear.substring(0, 4), 10);
    var month = parseInt(strMonthYear.substring(5, 7), 10)-1;

    var result = new Date(year, month, day, hour, minute);
    var currentDate = new Date();
    //  - test validity datumu (den v mesici)
    if (result < currentDate){
      result.setYear(currentDate.getYear() < 1900 ? currentDate.getYear()+1900 : currentDate.getYear());
      result.setMonth(currentDate.getMonth());
      result.setDate(currentDate.getDate());
      result.setMonth(currentDate.getDate());
      result.setHours((result.getMinutes() ? 1 : 0) + result.getHours());
      result.setMinutes(0);
      result.setSeconds(delta);
    }
    return result;
  }

  /**
  * Argumenty:
  *   elSelect... objekt Select, kteremu chci nastavit hodnotu option na `selected`
  *   optionValue... hodnota (option.value) optionu, ktery ma byt nastaven na `selected`
  */
  function chooseSelectOption(elSelect, optionValue){
    for(var i=0; i < elSelect.options.length; i++){
      if(elSelect.options[i].value == optionValue){
//        elSelect.options[i].selected = true;
//    /*
        elSelect.selectedIndex = i;
        break;
// */
      }
    }
  }

  /**
  * Udalost, ktera je vyvolana v pripade, ze datum ulozene v elementech
  * hash::elMonth, hash::elDay, hash::elTime je validni.
  *
  * Argumenty:
  *   hash::elMonth
  *   hash::elDay
  *   hash::elTime
  */
  function __onDateValid(hash){
    //  -TODO: doplnit telo... uprava stylu select-boxu
    // Library_debugAlert('datum OK');
    Library_removeClass(hash['elMonth'], 'inputError');
    Library_removeClass(hash['elDay'], 'inputError');
    setDateOptionsStyle(hash);
  }

  /**
  * Udalost, ktera je vyvolana v pripade, ze datum ulozene v elementech
  * hash::elMonth, hash::elDay, hash::elTime NENI validni.
  *
  * Argumenty:
  *   hash::elMonth
  *   hash::elDay
  *   hash::elTime
  */
  function __onDateInvalid(hash){
    //  -TODO: doplnit telo... uprava stylu select-boxu hash::elMonth, hash::elDay... atd.
    // Library_debugAlert('datum BAD');
    Library_addClass(hash['elMonth'], 'inputError');
    Library_addClass(hash['elDay'], 'inputError');
    setDateOptionsStyle(hash);
  }

  function getCurrentDate(){
    var d = new Date();
    d.setHours(0);
    d.setMinutes(0);
    d.setSeconds(0);
    d.setMilliseconds(0);
    return d;
  }

  /**
  * Nastavi elementy hash::elMonth, hash::elDay a hash::elTime tak, aby zobrazovaly
  * datum hash::date.
  *
  * Argumenty:
  *   hash::elMonth
  *   hash::elDay
  *   hash::elTime
  *   hash::date
  */
  function saveDate(hash){
    if(hash['elMonth']){
      // format YY-mm
      //  - bug v js... problem s Y2K (neni opraven ve vsech prohlizecich: IE ano, Firefox ne...)
      var strYear = hash['date'].getYear();
      if(strYear < 1900) strYear+= 1900;
      var month = hash['date'].getMonth() + 1;
      var strMonth = (month < 10)?('0' + month):(month);
      var s = strYear + '-' + strMonth;

      chooseSelectOption(hash['elMonth'], s);
    }

    if(hash['elDay']){
      var strDay = hash['date'].getDate();
      chooseSelectOption(hash['elDay'], strDay);
    }

    if(hash['elTime']){
      strHour = (hash['date'].getHours() < 10)?('0' + hash['date'].getHours()):(hash['date'].getHours());
      strMinute = (hash['date'].getMinutes() < 10)?('0' + hash['date'].getMinutes()):(hash['date'].getMinutes());
      var s = strHour + ':' + strMinute;

      chooseSelectOption(hash['elTime'], s);
    }

    setDateOptionsStyle(hash);
  }

// Hlavni vetev zpracovani

  if (!hash['allowWrongDate'] && hash['allowWrongDate']!== false) hash['allowWrongDate'] = true;//'future';
  if (!hash['autoModify']) hash['autoModify'] = 'from';//'both';


  var _caller = hash['caller'];

  //  - rozhodnuti, ktere hodnoty se budou prizpusobovat, zda hodnoty 'od' nebo 'do'
  //  - defaultne se predpoklada prizpusobovani 'do'
  //  - autoModify urcuje vztah prizpusobovani
  var toAdjust = 'to';
  if ((
      ((hash['elToTime']) && (hash['elToTime'] == _caller))
      ||
      hash['elToDay'] == _caller
      ||
      hash['elToMonth'] == _caller
  )
  || (
      ((hash['elToTime']) && (hash['elToTime'] == hash['elToTime'].id == _caller.id))
      ||
      hash['elToDay'].id == _caller.id
      ||
      hash['elToMonth'].id == _caller.id
   )){
    toAdjust = 'from';
  }
  var flagDateInvalid = false;

  //  - parsovani data 'od'
  var paramsFrom = new Array();
  paramsFrom['elTime'] = hash['elFromTime'];
  paramsFrom['elDay'] = hash['elFromDay'];
  paramsFrom['elMonth'] = hash['elFromMonth'];
  __onDateValid(paramsFrom);
  __onDateInvalid(paramsFrom);

  var fromDate = parseDate(paramsFrom);
  if (fromDate){
    __onDateValid(paramsFrom);
  } else {
    if (!hash['allowWrongDate']){
      paramsFrom['date'] = getRightDate(paramsFrom);
      saveDate(paramsFrom);
    } else {
      __onDateInvalid(paramsFrom);
      flagDateInvalid = true;
    }
  }

  //  - parsovani data 'do'
  var paramsTo = new Array();
  paramsTo['elTime'] = hash['elToTime'];
  paramsTo['elDay'] = hash['elToDay'];
  paramsTo['elMonth'] = hash['elToMonth'];
  __onDateValid(paramsTo);
  __onDateInvalid(paramsTo);

  var toDate = parseDate(paramsTo); // vraci pouze existujici datumy (v porovnani dnu)
  if (toDate){
    __onDateValid(paramsTo);
  } else {
    if (!hash['allowWrongDate']){
      paramsTo['date'] = getRightDate(paramsTo, hash['keepInterval']);
      saveDate(paramsTo);
    } else {
      __onDateInvalid(paramsTo);
      flagDateInvalid = true;
    }
  }

  //  - LOGIKA: osetreni datumu, ktery je v minulosti
  var currentDate = getCurrentDate();
  if (fromDate && fromDate < currentDate){
    if (!hash['allowWrongDate'] || hash['allowWrongDate'] != 'future'){ // neopravovat
      __onDateInvalid(paramsFrom);
      flagDateInvalid = true;
    } else {
      //  - hodnoty select-boxu pro cas maji tvar HH:00, minuty se proto musi
      //    nastavit tak, aby z objektu Date bylo mozne zrekonstruovat
      //    atribut select::options[]::value
      var newDate = new Date;
//      fromDate.setYear(currentDate.getYear() < 1900 ? currentDate.getYear()+1900 : currentDate.getYear());
//      fromDate.setMonth(currentDate.getMonth());
//      fromDate.setDate(currentDate.getDate());
      newDate.setHours(fromDate ? (fromDate.getMinutes() ? 1 : 0) + fromDate.getHours() : 0);
      newDate.setMinutes(0);
      newDate.setSeconds(0);
      fromDate = newDate;

      var params = new Array();
      if(hash['elFromMonth']) params['elMonth'] = hash['elFromMonth'];
      if(hash['elFromDay']) params['elDay'] = hash['elFromDay'];

      //  - pouze pokud zakaznik specifikuje cas, mohu cas modifikovat
      if(hash['elFromTime'])
        if(hash['elFromTime'].value)
          params['elTime'] = hash['elFromTime'];
      params['date'] = fromDate;
      saveDate(params); // oprava datumu pred aktualnim casem
    }
  }

  if (toDate && toDate < currentDate){// necha se zpracovat from
    if (!hash['allowWrongDate'] || hash['allowWrongDate'] != 'future'){ // neopravovat
      __onDateInvalid(paramsTo);
      flagDateInvalid = true;
    } else {
      var newDate = new Date;
//      toDate.setYear(currentDate.getYear() < 1900 ? currentDate.getYear()+1900 : currentDate.getYear());
//      toDate.setMonth(currentDate.getMonth());
//      toDate.setDate(currentDate.getDate());
      newDate.setHours(toDate ? (toDate.getMinutes() ? 1 : 0) + toDate.getHours() : 0);
      newDate.setMinutes(0);
      newDate.setSeconds(hash['keepInterval']);
      toDate = newDate;

      var params = new Array();
      if(hash['elToMonth']) params['elMonth'] = hash['elToMonth'];
      if(hash['elToDay']) params['elDay'] = hash['elToDay'];

      //  - pouze pokud zakaznik specifikuje cas, mohu cas modifikovat
      if(hash['elToTime'])
        if(hash['elToTime'].value)
          params['elTime'] = hash['elToTime'];
      params['date'] = toDate;
      saveDate(params);
    }
  }

  if(flagDateInvalid) return false; //neposouvat hodnoty vuci neplatnemu datumu

  //  - LOGIKA: prekrizeni datumu
  if(fromDate > toDate){
    if(toAdjust == 'to'){
      if (Library_inArray(['from', 'both'], hash['autoModify'])){
        //  - vychazim z data 'od' a podle nej prizpusobuji datum 'do'
        toDate = new Date(fromDate);
        toDate.setSeconds(fromDate.getSeconds() + hash['keepInterval']);

        var params = new Array();
        if(hash['elToMonth']) params['elMonth'] = hash['elToMonth'];
        if(hash['elToDay']) params['elDay'] = hash['elToDay'];
        //  - pokud zakaznik zadal cas 'od', predpoklada se, ze pozaduje
        //    i zadani casu 'do' (probehne automaticky)
        if(hash['elToTime'])
          if(hash['elFromTime'].value)
            params['elTime'] = hash['elToTime'];
        params['date'] = toDate;
        saveDate(params);
      }
    } else {
      if (Library_inArray(['to', 'both'], hash['autoModify'])){
        //  - vychazim z data 'do' a podle nej prizpusobuji datum 'od'
        //  - je treba resit i situaci, kdy by upraveni casu 'od' zpet
        //    zpusobilo skok do minulosti
        if((_caller == hash['elToDay']) || (_caller.id == hash['elToDay'].id)){
          //  - LOGIKA: prekrizeni datumu, ktere bylo zpusobeno zmenou dne v mesici
          //  - uzivatel pravdepodobne zamysli nastavit 'do' na nektery z nasledujicich
          //    mesicu
          //  - nastavuji mu mesic select-boxu o jeden dopredu
          toDate.setMonth(toDate.getMonth()+1);

          var params = new Array();
          if(hash['elToMonth']) params['elMonth'] = hash['elToMonth'];
          if(hash['elToDay']) params['elDay'] = hash['elToDay'];
          //  - pokud zakaznik zadal cas 'od', predpoklada se, ze pozaduje
          //    i zadani casu 'do' (probehne automaticky)
          if(hash['elToTime'])
            if(hash['elFromTime'].value)
              params['elTime'] = hash['elToTime'];
          params['date'] = toDate;
          saveDate(params);
          hash['elToMonth'].onchange();
        } else {
          var currentDate = new Date();

          fromDate = new Date(toDate);
          fromDate.setSeconds(toDate.getSeconds() - hash['keepInterval']);

          if(fromDate < currentDate) fromDate = currentDate;

          var params = new Array();
          if(hash['elFromMonth']) params['elMonth'] = hash['elFromMonth'];
          if(hash['elFromDay']) params['elDay'] = hash['elFromDay'];

          //  - pouze pokud zakaznik specifikuje cas, mohu cas modifikovat
          if(hash['elFromTime'])
            if(hash['elFromTime'].value)
              params['elTime'] = hash['elFromTime'];

          params['date'] = fromDate;
          saveDate(params);
        }
      }
    }
  }

  return true;
}

function onSubmitCalendarData(hash){
  function parseDate(hash){
    //  - predpokladany format vstupu ze select-boxu:
    //    - hodiny... HH:MM
    //    - dny... D (cislo dne v mesici)
    //    - mesic, rok... parsovat z retezce YYYY-MM
    var hour = 0; var minute = 0;

    if(hash['elTime']){
      var strTime = hash['elTime'].value;

      hour = parseInt(strTime.substring(0, 2), 10);
      if(!hour) hour = 0;

      minute = parseInt(strTime.substring(3), 10);
      if(!minute) minute = 0;
    }

    var day = parseInt(hash['elDay'].value, 10);

    var strMonthYear = hash['elMonth'].value;
    var year = parseInt(strMonthYear.substring(0, 4), 10);
    var month = parseInt(strMonthYear.substring(5, 7), 10)-1;

    var result = new Date(year, month, day, hour, minute);

    //  - test validity datumu (den v mesici)
    if (result.getDate() != day/* (result < new Date())*/)
      return false;
    else
      return result;
  }

  function getRightDate(hash, delta){
    if (!delta) delta = 0;
    //  - predpokladany format vstupu ze select-boxu - nespravne datum:
    var hour = 0; var minute = 0;

    if(hash['elTime']){
      var strTime = hash['elTime'].value;

      hour = parseInt(strTime.substring(0, 2), 10);
      if(!hour) hour = 0;

      minute = parseInt(strTime.substring(3), 10);
      if(!minute) minute = 0;
    }

    var day = parseInt(hash['elDay'].value, 10);

    var strMonthYear = hash['elMonth'].value;
    var year = parseInt(strMonthYear.substring(0, 4), 10);
    var month = parseInt(strMonthYear.substring(5, 7), 10)-1;

    var result = new Date(year, month, day, hour, minute);
    var currentDate = new Date();
    //  - test validity datumu (den v mesici)
    if (result < currentDate){
      result.setYear(currentDate.getYear() < 1900 ? currentDate.getYear()+1900 : currentDate.getYear());
      result.setMonth(currentDate.getMonth());
      result.setDate(currentDate.getDate());
      result.setMonth(currentDate.getDate());
      result.setHours((result.getMinutes() ? 1 : 0) + result.getHours());
      result.setMinutes(0);
      result.setSeconds(delta);
    }
    return result;
  }

  function getCurrentDate(){
    var d = new Date();
    d.setHours(0);
    d.setMinutes(0);
    d.setSeconds(0);
    d.setMilliseconds(0);
    return d;
  }

  //  - parsovani data 'od'
  var paramsFrom = new Array();
  paramsFrom['elTime'] = hash['elFromTime'];
  paramsFrom['elDay'] = hash['elFromDay'];
  paramsFrom['elMonth'] = hash['elFromMonth'];
  var fromDate = parseDate(paramsFrom);
  if (!fromDate){
    return 'INVALID_FROM';
  }

  if (hash['elToMonth']){ // pokud kontroluji jen jedno datum
    //  - parsovani data 'do'
    var paramsTo = new Array();
    paramsTo['elTime'] = hash['elToTime'];
    paramsTo['elDay'] = hash['elToDay'];
    paramsTo['elMonth'] = hash['elToMonth'];
    var toDate = parseDate(paramsTo);
    if (!toDate){
      return 'INVALID_TO';
    }
  }
  //  - LOGIKA: osetreni datumu, ktery je v minulosti
  var currentDate = getCurrentDate();
  if (fromDate < currentDate){
    return 'LESS_FROM';
  }

  if (hash['elToMonth']){ // pokud kontroluji jen jedno datum
    if (toDate < currentDate){
      return 'LESS_TO';
    }

    if(fromDate > toDate){
      return 'CROSS_DATES';
    }
    if(fromDate.getTime() == toDate.getTime()){
      return 'EQUAL_DATES';
    }
  }
  return false;
}

function onReceiveCalendarData(hash){
  /**
  * Argumenty:
  *   elSelect... objekt Select, kteremu chci nastavit hodnotu option na `selected`
  *   optionValue... hodnota (option.value) optionu, ktery ma byt nastaven na `selected`
  */
  function chooseSelectOption(elSelect, optionValue){
    for(var i=0; i < elSelect.options.length; i++){
      if(elSelect.options[i].value == optionValue) elSelect.options[i].selected = true;
    }
  }

  /**
  * Nastavi elementy hash::elMonth, hash::elDay a hash::elTime tak, aby zobrazovaly
  * datum hash::date.
  *
  * Argumenty:
  *   hash::elMonth
  *   hash::elDay
  *   hash::elTime
  *   hash::date
  */
  function saveDate(hash){
    if(hash['elMonth']){
      //  - bug v js... problem s Y2K (neni opraven ve vsech prohlizecich: IE ano, Firefox ne...)
      var strYear = hash['date'].getYear();
      if(strYear < 1900) strYear+= 1900;
      var month = hash['date'].getMonth() + 1;
      var strMonth = (month < 10)?('0' + month):(month);
      var s = strYear + '-' + strMonth;

      chooseSelectOption(hash['elMonth'], s);
    }

    if(hash['elDay']){
      var strDay = hash['date'].getDate();
      chooseSelectOption(hash['elDay'], strDay);
    }

    if(hash['elTime']){
      strHour = (hash['date'].getHours() < 10)?('0' + hash['date'].getHours()):(hash['date'].getHours());
      strMinute = (hash['date'].getMinutes() < 10)?('0' + hash['date'].getMinutes()):(hash['date'].getMinutes());
      var s = strHour + ':' + strMinute;

      chooseSelectOption(hash['elTime'], s);
    }
  }

  var params = new Array();
  params['elMonth'] = hash['elMonthYear'];
  params['elDay'] = hash['elDay'];
  params['date'] = new Date(
    hash['selectedYear'],
    hash['selectedMonth']-1,
    hash['selectedDay'],
    0, 0, 0
  );
  saveDate(params);
//  if (hash['caller'] != hash['elMonthYear'])
    hash['elMonthYear'].onchange();
}

/**
* Argumenty:
*   hash::url
*   hash::windowWidth
*   hash::windowHeight
*   hash::windowXCoord
*   hash::windowYCoord
*
*/

function ShowCalendar(hash){
  var popHeight = 220;

  if(!hash['months']) hash['months'] = 2;
  if(!hash['windowWidth']) hash['windowWidth'] = 220;
  if(!hash['windowHeight']) hash['windowHeight'] = 220 + 152*(hash['months']-1);
  if(!hash['windowXCoord']) hash['windowXCoord'] = 0;
  if(!hash['windowYCoord']) hash['windowYCoord'] = 0;
  hash['maxMonth'] = hash['maxMonth'] ? ('&maxMonth='+hash['maxMonth']) : '';
  if (/*!hash['url']*/true) hash['url'] = window.parametr.url+'?action=eCalendarData&frame=calendar&months='+hash['months']+'&defDay='+hash['elDay'].value+'&defMonth='+hash['elMonthYear'].value+hash['maxMonth'];

  window.open(hash['url'], "", "toolbar=no,scrollbars=no,location=no,status=no,width=" + hash['windowWidth'] + ",height=" + hash['windowHeight'] + ",resizable=0,screenX=" + hash['windowXCoord'] + ",screenY=" + hash['windowYCoord']);
  window.showCalendarParams = hash;
  window.onReceiveCalendarData = onReceiveCalendarData;
}
// ---modules/ForAll.ImageFading---
function setOpacity(obj, opacity) {
  opacity = (opacity == 100) ? 99.999 : opacity;

  // IE/Win
  obj.style.filter = "alpha(opacity:"+opacity+")";

  // Safari<1.2, Konqueror
  obj.style.KHTMLOpacity = opacity/100;

  // Older Mozilla and Firefox
  obj.style.MozOpacity = opacity/100;

  // Safari 1.2, newer Firefox and Mozilla, CSS3
  obj.style.opacity = opacity/100;
}
// ---GuiSearchFormDestinationsStepViewDestinationWithRelated---
if (!window.DestinationView)
  window.DestinationView = new Object();
  // nastaveni
  window.DestinationView.fadingInterval = 100; // jak dlouho trva jeden fadovaci krok
  window.DestinationView.destinationInterval = 8000 + 2000 *3;// za jak dlouho se prejde na obrazky dalsi destinace
  window.DestinationView.fadingStep = 10; // o kolik procent se zmeni pruhlednost pri fadovani
  window.DestinationView.slotInterval = 2000;       // za jak dlouho po prvnim se zacne menit druhy
  window.DestinationView.allSlotsInterval = 6000;  // za jak dlouho po prvnim se zacne znovu menit prvni (minimalne vsak slotInterval*pocetSlotu)
  // polozky nastavene inicializaci
  window.DestinationView.bigImg = new Array();
  window.DestinationView.bigImgCounter = 0;
  window.DestinationView.availIndex = new Array();
  // dynamicke parametry
  window.DestinationView.interval = 0; // doba od posledni zmeny obrazku (meni se dynamicky, nutna pro prechod na dalsi destinaci)
  window.DestinationView.locationIATA = ''; // IATA kod destinace, jejiz obrazky se prave zobrazuji
  window.DestinationView.locationIndex = 0;
  window.DestinationView.locationRemain = 0;
  window.DestinationView.slotIndex = -1;

function AO3searchFormDestinationsstepViewDestinationWithRelatedHandlerAdd() {
  AO3searchFormDestinationViewWithImageShowDescHandlerAdd();
  if (!window.DestinationView.storno)
   AO3searchFormDestinationViewWithRelatedHandlerAdd()
}

function AO3searchFormDestinationViewWithImageShowDescHandlerAdd() {
  var InfoButton = document.getElementById('destinationInfoButton');
  var Description = document.getElementById('destinationDescription');
  var DescriptionButton = document.getElementById('buttonHideDescription');
  if (InfoButton && Description) {
      InfoButton.style.display = 'block';
      Description.style.display = 'none';
      DescriptionButton.parentNode.style.visibility = 'visible';
      InfoButton.onclick = AO3searchFormDestinationViewWithImageShowDescHandler;
      DescriptionButton.onclick = AO3searchFormDestinationViewWithImageShowDescHandler;
  }
}

function AO3searchFormDestinationViewWithImageShowDescHandler() {
  var Description = document.getElementById('destinationDescription');
  var InfoButton = document.getElementById('destinationInfoButton');
  if (Description) {
    Description.style.display = (Description.style.display == 'none')?'block':'none';
    InfoButton.setAttribute('class',(Description.style.display == 'none')?'unchecked':'checked');
  }
}


function AO3searchFormDestinationViewWithRelatedHandlerAdd(){
  var inps = document.getElementsByTagName('A');
  var counter = 0;
  for (var i = 0; i<inps.length; i++){
    if (Library_hasClass(inps[i], 'destinationImage')){
      var key = inps[i].id;
      var hotelImgs = inps[i].getElementsByTagName('IMG');
/*      for (var j = 0; j < hotelImgs.length; j++){
        inps[i].fadingImage = hotelImgs[j];
//        inps[i].style.width = (inps[i].fadingImage.offsetWidth-2)+'px';
//        inps[i].style.height = (inps[i].fadingImage.offsetHeight-2)+'px';
      }
*/
      inps[i].fadingImage = hotelImgs[0];
      var backImage = new Image();
      inps[i].index = counter;
      inps[i].location = '';
//      inps[i].style.position = 'relative';
//        inps[i].style.float = 'left';
//        inps[i].style.cssFloat = 'left';
//        inps[i].style.clear = 'right';

      inps[i].backImage = backImage;
      inps[i].appendChild(backImage);
      inps[i].style.display = 'block';
//      backImage.style.visibility = 'hidden';
      backImage.style.position = 'absolute';
//      backImage.style.top = (Library_getOffsetTop(inps[i])+3)+"px";
//      backImage.style.left = (Library_getOffsetLeft(inps[i])+3)+"px";
      backImage.style.top = "3px";
      backImage.style.left = "3px";
      backImage.style.paddingLeft="0px";
      backImage.style.paddingTop="0px";
      backImage.style.zIndex = 0;
      if (inps[i].fadingImage){
          inps[i].fadingImage.style.position = 'absolute';
          inps[i].fadingImage.style.top = backImage.style.top;
          inps[i].fadingImage.style.left = backImage.style.left;
          inps[i].fadingImage.style.paddingLeft="0px";
          inps[i].fadingImage.style.paddingTop="0px";

//          inps[i].style.display = 'block';

          inps[i].fadingImage.style.zIndex = 1;
          backImage.src = inps[i].fadingImage.src;
      }
      window.DestinationView.bigImg[counter] = inps[i];
      counter++;
    }
  }
  window.DestinationView.bigImgCounter = counter;
  AO3searchFormDestinationViewWithImagesChangeImageHandler();
}

function isAcceptableImage(x) {
 for (var i = 0; i < window.DestinationView.bigImg.length; i++) {
  if (window.DestinationView.bigImg[i].backImage.src==window.DestinationView.loc[window.DestinationView.locationIATA].im[x].src) {
   return false;
  }
 }
 return true;
}

function AO3searchFormDestinationViewWithImagesChangeImageHandler() {


 window.DestinationView.slotIndex++;
 if (window.DestinationView.slotIndex >= window.DestinationView.bigImg.length) {
   window.DestinationView.slotIndex = 0;
 }

 if ((window.DestinationView.locationRemain -= window.DestinationView.interval)<=0) {
   window.DestinationView.locationRemain=window.DestinationView.destinationInterval;
   window.DestinationView.locationIndex++;
   if (window.DestinationView.locationIndex>=window.DestinationView.locations.length) window.DestinationView.locationIndex = 0;
   window.DestinationView.locationIATA = window.DestinationView.locations[window.DestinationView.locationIndex];
 }

 if (!window.DestinationView.locationIATA) { return false; }
 var x;
 var retry = 9;
 while (! isAcceptableImage(x = Math.round(Math.random() * (window.DestinationView.loc[window.DestinationView.locationIATA].im.length-1))) && retry) retry--;
 window.DestinationView.bigImg[window.DestinationView.slotIndex].location = window.DestinationView.locationIATA;
 window.DestinationView.bigImg[window.DestinationView.slotIndex].index = x;
 window.setTimeout('window.DestinationView.bigImg['+window.DestinationView.slotIndex+'].backImage.src = "'+window.DestinationView.loc[window.DestinationView.locationIATA].im[x].src+'";',100);
 var altTitle = window.DestinationView.loc[window.DestinationView.locationIATA].im[x].alt;
 var images=window.DestinationView.bigImg[window.DestinationView.slotIndex].fadingImage.parentNode.getElementsByTagName('IMG');
 for (var i = 0; i<images.length; i++) { images[i].alt = altTitle; images[i].title = altTitle; }
 if (window.DestinationView.slotIndex == window.DestinationView.bigImg.length-1) {
  window.DestinationView.interval = window.DestinationView.allSlotsInterval - (window.DestinationView.slotIndex*window.DestinationView.slotInterval);
 } else { window.DestinationView.interval = window.DestinationView.slotInterval; }
 window.setTimeout('AO3searchFormDestinationViewWithImagesChangeImageHandler()', window.DestinationView.interval);
 AO3searchFormDestinationViewWithImagesFadeOut(window.DestinationView.slotIndex, 100)
}

function AO3searchFormDestinationViewWithImagesFadeOut(part, opacity) { // staremu obrazku se snizuje pruhlednost, v pozadi je novy
  var obj = window.DestinationView.bigImg[part].fadingImage;
  if (obj){
      if (opacity >= 0) {
        setOpacity(obj, opacity);
        obj.style.visibility = 'visible';
        opacity -= window.DestinationView.fadingStep;
        window.DestinationView.bigImg[part].timer = window.setTimeout("AO3searchFormDestinationViewWithImagesFadeOut("+part+","+opacity+")", window.DestinationView.fadingInterval);
      } else {
        obj.style.visibility = 'hidden';
        obj.src = window.DestinationView.bigImg[part].backImage.src;//stary nahradi novy
        setOpacity(obj, 100);
      }
  }
}