
// --- Pomocne fce ------------------------

// DOM

// insertAfter:: http://www.netlobo.com/javascript-insertafter.html
function insertAfter( referenceNode, newNode )
{
  referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}

// vytvori DOM strukturu z arraye...
function json_to_element (json, el) {
  var fr, nel, nfr;
  if (!json || !json.length) return null;
  fr=document.createDocumentFragment(); 
  if (json.length)
  {
    for (var i=0; i<json.length; i=i+2)
    {
      switch (json[i])
      {
        case 'E': // element (tag)
	  nel=document.createElement(json[i+1]);
          nfr=json_to_element (json[i+2], nel);
	  if (nfr) nel.appendChild(nfr);
          fr.appendChild(nel); 
	  i++;
	  break;
        case 'T': // text
	  nel=document.createTextNode(json[i+1]);
          fr.appendChild(nel); 
	  break;
        case 'S': // styl...
	  if (el && el.nodeType==1)
	  {
	  // MSIE je uplne zrudny hovado :(
	    var stl=json[i+1];
	    switch (stl) {
	      case 'background-color':
	        el.style.backgroundColor=json[i+2];
	        break;
	      case 'background-image':
	        el.style.backgroundImage=json[i+2];
	        break;
	      case 'color':
	        el.style.color=json[i+2];
	        break;
	      case 'padding-left':
	        el.style.paddingLeft=json[i+2];
	        break;
	      case 'padding-right':
	        el.style.paddingRight=json[i+2];
	        break;
	      case 'padding-top':
	        el.style.paddingTop=json[i+2];
	        break;
	      case 'padding-bottom':
	        el.style.paddingBottom=json[i+2];
	        break;
	    }
	  }
	  i++;
	  break;
        case 'A': // atribut (nadrazeneho elementu!)
          // pouze pokud existuje nadrazeny element!
	  if (el && (el.nodeType==1))
	  {
	    var atr=json[i+1];
	 /* MSIE je TOTALNI PASKVIL! */
	   switch (atr) {
	      case 'onmousedown':
	        el.onclick=new Function('event', json[i+2]);
	        break;
	      case 'onmouseover':
	        el.onmouseover=new Function('event', json[i+2]);
		break;
	      case 'onclick':
	        el.onclick=new Function('event', json[i+2]);
		break;
	      case 'ondblclick':
	        el.ondblclick=new Function('event', json[i+2]);
		break;
	      case 'onload':
	        el.onload=new Function('event', json[i+2]);
	        break;
	      default:
	        nel = document.createAttribute(atr);
                nel.nodeValue = json[i+2];
	        el.setAttributeNode(nel);
	     }
	  }
	  i++;
	  break;
      }
    }
  }
  return fr;
}

// odstrani vsechny potomky
function removeAllChildren (el) {
  if (el && el.childNodes)
    for (var i=el.childNodes.length; i; i--)
      el.removeChild(el.childNodes[i-1]);
}

function removeById (id) {
  var el = document.getElementById(id);
  el.parentNode.removeChild(el);
}

function removeByClass (elemtype, klasa) {
  if (!document.getElementsByTagName) { return; }
  var elz = document.getElementsByTagName(elemtype);
  for (var i=0, l=elz.length; i<l; i++)
    if (elz[i] && elz[i].className == klasa)
      elz[i].parentNode.removeChild(elz[i]);
}

// --- Formulare --------------------------

// Vertikalni zmena velikosti elementu "textarea". Adaptovano z http://trac.edgewall.org/
function resizeTextArea(id, rows)
{
  var textarea = document.getElementById(id);
  var warning = document.getElementById("^warning^"+id);
  var select = document.getElementById("^rows^"+id);
  if (select && select.value) select.value = rows;
  if (!textarea || (typeof(textarea.rows) == "undefined")) return;
  if (rows == "---")
  {
    textarea.style.display = "none";
    if (warning) warning.style.display = "";
  }
  else
  {
    textarea.rows = rows;
    textarea.style.display = "";
    if (warning) warning.style.display = "none";
  }

}

// zobrazi vsechny elementy s danou tridou..
//(musi mit nastaveny "display:none" primo ve style=, nikoliv pres class !)
//
function showByClass (elemtype, klasa) {
  if (!document.getElementsByTagName) { return; }
  var elz = document.getElementsByTagName(elemtype);
  for (var i=0, l=elz.length; i<l; i++)
    if (elz[i].className == klasa)
      elz[i].style.display = "";
}

function hideByClass (elemtype, klasa) {
  if (!document.getElementsByTagName) { return; }
  var elz = document.getElementsByTagName(elemtype);
  for (var i=0, l=elz.length; i<l; i++)
    if (elz[i].className == klasa)
      elz[i].style.display = "none";
}

// ------
// nastavi focus pro objekt s nejmensim tabindexem...
//
function setFocusOnTabindex () {
  var tbel=null, tbi=99999;
  if (!document.getElementsByTagName) { return; }
  var elz = document.getElementsByTagName('input');
  for (var i=0, l=elz.length; i<l; i++)
  {
    if (elz[i].tabIndex)
    {
      if (tbi>elz[i].tabIndex)
      {
	 tbel=elz[i]; tbi=elz[i].tabIndex;
      }
    }
  }

  if (tbel) { tbel.focus(); }
}


// ----- evangnet (napoveda, atd...) ---------------------
//
var evangnet = {
  // do HTML elementu "targ" prida odkaz na napovedu ve wiki ("napoveda:id")
  add_popup_help: function(targ, id) {
    if (targ) {
      zv1 = document.createTextNode('(')
      zv2 = document.createTextNode(')')
      helpa = document.createElement('a');
      helpa.href = "/napoveda:"+id;
      helpa.target = "_new";
      helpa.onclick=new Function ("return bpop_pop('/export/html/wiki/napoveda:"+id+"', 'Nápověda');");
      targ.appendChild(zv1);
      targ.appendChild(helpa);
      targ.appendChild(zv2);
    }
  }
}


// ----------------------------------------------------------------------------------
// capslock warning for password input fields
// based on this article: http://24ways.org/2007/capturing-caps-lock
//
var capslock = {
  keypress: function(e, targ) {
    var ev = e ? e : window.event;
    if (!ev) return;
    // get key pressed (MSIE vs. other browsers)
    var which = -1; if (ev.which) which = ev.which; else if (ev.keyCode) which = ev.keyCode;
    // get shift status
    var shift_status = false; if (ev.shiftKey) shift_status = ev.shiftKey; else if (ev.modifiers) shift_status = !!(ev.modifiers & 4);
    // test for capslock!
    if (((which >= 65 && which <=  90) && !shift_status) ||
        ((which >= 97 && which <= 122) && shift_status)) {
      // uppercase, no shift key
      capslock.show_warning(targ);
    } else {
      capslock.hide_warning(targ);
    }
  },
  show_warning: function(targ) {
    if (!targ.warning) {
      // create a "popup"
      targ.warning = document.createElement('div');
      if(navigator.userAgent.match(/MSIE/)) {
        targ.style.position = "relative";
      }
      targ.warning.style.position = "absolute";
      targ.warning.className = "capslockwarning";
      targ.warning.style.left = (targ.offsetLeft + targ.offsetWidth - 16) + "px";
      targ.warning.style.top = (targ.offsetTop - 27) + "px";
      targ.warning.style.zIndex = "999";

      // text of the warning...
      warning_text1 = document.createTextNode('CAPS LOCK!')
      span = document.createElement('span');
      span.style.color = "red";
      span.appendChild(warning_text1);
      targ.warning.appendChild(span);
      br = document.createElement('br');
      targ.warning.appendChild(br);
      evangnet.add_popup_help(targ.warning, 'caps_lock');
      warning_napoveda = document.createTextNode('nápověda');
      helpa.appendChild(warning_napoveda);
      document.body.appendChild(targ.warning);
  
    /* TODO TODO TODO TODO TODO */
      // now that we know how big the DIV is, we can set it's exact position...
      targ.warning.style.top = (targ.offsetTop - targ.warning.offsetHeight + 12) + "px";
    }
    // show it only for 5 seconds FROM NOW!
    clearTimeout (this.tout);
    this.delayed_hide_warning (targ, 5000);
  },
  hide_warning: function(targ) {
    if (targ && targ.warning) {
      targ.warning.parentNode.removeChild(targ.warning);
      targ.warning = null;
      this.save_targ = null;
      this.tout = null;
    }
  },
  delayed_hide_warning: function (targ, delay) {
    if (targ.warning) {
      if (!this.save_targ) this.save_targ=new Object;
      this.save_targ=targ;
      // if one clicks on the "help" field in the "popup", let him have
      // 150msec before we close the popup, so that the click is sucessfull!
      if (!this.tout) this.tout=new Object;
      this.tout = setTimeout ("capslock.hide_warning(capslock.save_targ);", delay?delay:150);
    }
  }
};


// ------ formulare: automaticke doplnovano hodnot, etc...

function form_set_on_click(idtrg, idsrc, valu) {
  trg=document.getElementById(idtrg);
  trg.value=valu;
}

function form_set_on_select(idtrg, idsrc, deflt, srcclr, srcdefclr, trgclr, trgdefclr, trgdis, trgset, arr_obj, idsave) {
  trg=document.getElementById(idtrg);
  src=document.getElementById(idsrc);
  if (src.value==deflt)
  {
    // disable (trg)
    if (trgdis) trg.disabled=false;

    // barvicky (src)
    if (srcclr)
    {
      if (srcdefclr) src.style.color=srcdefclr;
      else src.style.color="";
    }

    if (idsave)
    {
      sve=document.getElementById(idsave);
      if ((sve.value==trg.value) || (trg.value==''))
      {
        // hodnota (trg)
        if (trgset=="valclear") trg.value="";

        // barvicky (trg)
        if (trgclr)
        {
          if (trgdefclr) trg.style.color=trgdefclr;
          else trg.style.color="";
        }
      }
      sve.value=deflt;
    }
  }
  else
  {
    // disable (trg)
    if (trgdis) trg.disabled=true;

    // barvicky (src & trg)
    if (srcclr) src.style.color=srcclr;

    // hodnota (trg)
    if (trgset=="clear") trg.value="";
    else if (trgset=="zero") trg.value="0";
    else if ((trgset=="valclear") || (trgset=="val"))
    {
      if (arr_obj==null)
        chg=src.options[src.selectedIndex].text;
      else if (typeof(arr_obj)=="object")
        chg=arr_obj[src.value];
      else if (typeof(arr_obj)=="function")
        chg=arr_obj(src.value);
      else if (arr_obj=="id")
        chg=src.value;

      // ukladani hodnoty... ??!!
      if (idsave)
      {
        sve=document.getElementById(idsave);
	if ((sve.value==trg.value) || (trg.value==''))
	{
	  trg.value=chg;

          // barvicky (trg)
          if (trgclr) trg.style.color=trgclr;
	}
	sve.value=chg;
      }
      else
        trg.value=chg;
    }

  }
}

function form_changeclr_on_compare(idsave, idsrc, clrsame, clrdiff, clrdefl, deflt) {
  src=document.getElementById(idsrc);
  sve=document.getElementById(idsave);
  if (src.value=="")
  {
    src.value=sve.value;
    if (clrsame && sve.value) src.style.color=clrsame;
  }
  else if (deflt && (sve.value==deflt))
  {
    if (clrdefl) src.style.color=clrdefl;
    else src.style.color="";
  }
  else if (sve.value!=src.value)
  {
    if (clrdiff) src.style.color=clrdiff;
    else src.style.color="";
  }
  else
  {
    if (clrsame) src.style.color=clrsame;
    else src.style.color="";
  }
}

function form_ajax_list_add (idtrg, idmy, idsrc) {
  trg=document.getElementById(idtrg);
  src=document.getElementById(idsrc);
  if (trg.value)
    trg.value=trg.value+', '+src.value;
  else
    trg.value=src.value;
}

function new_xml_http_req () {
  var http_request=false;
  if (window.XMLHttpRequest) { 
    http_request = new XMLHttpRequest();
  } else if (window.ActiveXObject) { 
  try {
    http_request = new ActiveXObject("Msxml2.XMLHTTP");
   } catch (eror) {
    http_request = new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
  return http_request;
}

function form_fetchelem_on_select(idtrg, idsrc, deflt, url, urlsuff, childload) {
  var trg=document.getElementById(idtrg);
  var src=document.getElementById(idsrc);
  if (src.value==deflt)
  {
    removeAllChildren(trg);
    trg.appendChild(json_to_element(['T', '-'], null));
  }
  else
  {
    removeAllChildren(trg);
    var jsins=['T', 'načítám...', 'A', 'value', ''];
    if (childload) jsins=['E', childload, jsins];
    trg.appendChild(json_to_element(jsins, null));
    if (!trg.loading)
    {
      trg.loading=1;
      trg.originalclass=trg.className;
      trg.className="loading";
      trg.disabled=true;
    }

    trg.xtmr=new_xml_http_req();
    trg.xtmr.onreadystatechange = function() { form_fetchelem_fetch (trg.xtmr, trg, childload); };

    var urls=''; if (urlsuff!=null) urls=urlsuff; // bug workaround... !?
    trg.xtmr.open('GET', url+src.value+urls, true);
    trg.xtmr.send(null);
  }
}

function form_fetchelem_fetch(http_request, trg, childload) {
  if (http_request.readyState==4)
  {
    if (http_request.status==200)
    {
      if (http_request.responseText.length>0)
      { // nacteno neco
        eval("var json = "+http_request.responseText);
        removeAllChildren(trg);
        trg.appendChild(json_to_element(json, null));
        trg.loading=0;
        trg.className=trg.originalclass;
	trg.disabled=false;
      }
      else
      { // načteno nic
        removeAllChildren(trg);
        var jsins=['T', '\u2014', 'A', 'value', ''];
        if (childload) jsins=['E', childload, jsins];
        trg.appendChild(json_to_element(jsins, null));
        trg.loading=0;
        trg.className=trg.originalclass;
	trg.disabled=true;
      }
    }
    else
    { // pri nacitani nastala chyba!
      removeAllChildren(trg);
      var jsins=['T', 'chyba při načítání!', 'A', 'value', ''];
      if (childload) jsins=['E', childload, jsins];
      trg.appendChild(json_to_element(jsins, null));
      trg.className="loadingerror";
      trg.disabled=true;
    }
  }
}

function form_fetchvar_on_select(idtrg, idsrc, deflt, url, promenna) {
    var trg=document.getElementById(idtrg);
    var src=document.getElementById(idsrc);

    bgcolorok=src.style.backgroundColor;
    src.style.backgroundColor='#ff9898';

    trg.xtmr=new_xml_http_req();
    trg.xtmr.onreadystatechange = function() { form_fetchvar_fetch (trg.xtmr, promenna, src, trg, bgcolorok); };
    trg.xtmr.open('GET', url+src.value, true);
    trg.xtmr.send(null);
}

function form_fetchvar_fetch(http_request, promenna, src, trg, bgcolorok) {
  if (http_request.readyState == 4)
  {
    if (http_request.status == 200)
    {
      json=http_request.responseText;
//      alert("var "+promenna+" = "+json);
      eval(" "+promenna+" = "+json);
      trg.onchange();
      src.style.backgroundColor=bgcolorok;
    }
    else
    {
//      alert('chyba');
      src.value='chyba';
    }
  }
}


/*
 * Pro "vlozene" (ajaxove) formulare: odeslat button s ID idtrg a ne
 *   cely velky formular...
 * Spoustet z daneho elementu:  onkeypress="return form_submit_for (event, '__id__');"
 */
function form_submit_for (e, idtrg) {
  var ev = e ? e : window.event;
  if (!ev) return false;
  // get key pressed (MSIE vs. other browsers)
  var which = -1; if (ev.which) which = ev.which; else if (ev.keyCode) which = ev.keyCode;
  if (which!=13) return true;

  // now, ENTER was pressed!
  trg=document.getElementById(idtrg);
  trg.click();
  return false;
}

/*
 *  TEST (hlavne MSIE!)
 */
function test_push_element (idtrg, html) {
  trg=document.getElementById(idtrg);
  trg.innerHTML=html;

  trg.outerHTML=trg.outerHTML;
}


function show_popup_info  (targ, urlpref, hashref) {
    if (!targ.tle) {
      targ.tle=(targ.title.length>0)?targ.title:targ.innerHTML;
      targ.tle=targ.tle.replace('&nbsp;', ' ');
      targ.removeAttribute("title");
    }
    if (!targ.tuultip) {
      // create a "popup"
      targ.tuultip = document.createElement('div');
      if(navigator.userAgent.match(/MSIE/)) {
        targ.style.position = "relative";
      }
      targ.tuultip.style.position = "absolute";
      targ.tuultip.className = "popuplink";

      // zjistit polohu elementu...
      var ofX, ofY, ofW, ofH, ttt;
      ttt=targ;
      while (!ofX && !ofY) {
         ofX=ttt.offsetLeft; ofY=ttt.offsetTop;
         ofW=ttt.offsetWidth; ofH=ttt.offsetHeight;
	 ttt=ttt.parentNode;
	 if (!ttt) break;
      }

      // text of the tuultip...
      tuultip_text1 = document.createTextNode(targ.ajaxinfo?targ.ajaxinfo[0]:targ.tle);
      span = document.createElement('span'); // h2 ???
      span.className = "popuplink_hdr";
      span.style.color = "green";
      span.style.fontWeight = "bold";
      span.appendChild(tuultip_text1);
      targ.tuultip.appendChild(span);

      br = document.createElement('br');
      targ.tuultip.appendChild(br);

      if (targ.href && targ.href.length)
      {
        tuultip_text2 = document.createTextNode(targ.href);
        span2 = document.createElement('a');
        span2.target="_new";
        span2.href=targ.href;
        span2.appendChild(tuultip_text2);
        targ.tuultip.appendChild(span2);

        br2 = document.createElement('br');
        targ.tuultip.appendChild(br2);
      }

      divinfo = document.createElement('div');
      divinfo.className = "popuplink_info";
      divinfo.innerHTML=targ.ajaxinfo?targ.ajaxinfo[1]:"(<i>nahrávám informace</i>)";
      targ.tuultip.appendChild(divinfo);

      if (!targ.ajaxinfo)
      {
        targ.xtmr=new_xml_http_req();
        targ.xtmr.onreadystatechange = function() { fetch_popup_info (targ.xtmr, targ, span, divinfo); };
	// FIXME: escape() vs. urlencode(): http://cass-hacks.com/articles/discussion/js_url_encode_decode/
        targ.xtmr.open('GET', urlpref+(hashref?targ.href:escape(targ.innerHTML)), true);
        targ.xtmr.send(null);
      }

      document.body.appendChild(targ.tuultip);
  
      // Napozicujeme menu
      // FIXME FIXME FIXME!!!!!!!!!!
      //// targ.tuultip.style.left = (ofX + ofW/2 ) + "px";
      targ.tuultip.style.left = (ofX + 12) + "px";
      targ.tuultip.style.top = (ofY + ofH - 5) + "px";
      targ.tuultip.style.zIndex = "999";

      // FIXME: now that we know how big the DIV is, we can set it's exact position...
      //    targ.tuultip.style.top = (targ.offsetTop - targ.tuultip.offsetHeight + 12) + "px";
    }
    // show it only for 5 seconds FROM NOW!
//    clearTimeout (this.tout);
//    this.delayed_hide_tuultip (targ, 5000);
}

function hide_popup_info(targ) {
  if (targ && targ.tuultip) {
    targ.tuultip.parentNode.removeChild(targ.tuultip);
    targ.tuultip = null;
  }
}

function fetch_popup_info (http_request, targ, nadpis, komentar) {
  if (http_request.readyState == 4)
  {
    if (http_request.status == 200)
    {
      targ.ajaxinfo=eval(http_request.responseText);
      if (targ.tuultip)
      {
        if (targ.ajaxinfo[0].length && nadpis) nadpis.innerHTML=targ.ajaxinfo[0];
	else targ.ajaxinfo[0]=targ.tle;
        if (targ.ajaxinfo[1].length && komentar) komentar.innerHTML=targ.ajaxinfo[1];
      }
    }
    else
    {
      if (komentar) komentar.innerHTML='[chyba...]';
    }
  }
}

/*
 * NEFUNGUJE poradne v MSIE :-(
 * jine reseni: http://siderite.blogspot.com/2007/10/absolute-position-of-html-elements-in.html
 */
function getAbsolutePosition(element) {
  var r = { x: element.offsetLeft, y: element.offsetTop };
  if (element.offsetParent) {
    var tmp = getAbsolutePosition(element.offsetParent);
    r.x += tmp.x;
    r.y += tmp.y;
  }
  return r;
};

function findChildByClass (element, className) {
  if (!element || !element.childNodes || !element.childNodes.length) return null;
  for (var i=0; i<element.childNodes.length; i++)
    if (element.childNodes[i].className==className) return element.childNodes[i];
  return null;
}

function tabulka_rozbal_sbal (e, id, ajaxurl) {
  e = (e) ? e : window.event;
/////  var element = (e.target) ? e.target: e.srcElement;

  var td = document.getElementById(id);
  var bgim=td.style.backgroundImage;

  // vybrat JENOM kliknuti do oblasti "fajfek":
  // rx: reativni offset od zacatku <td>
  // rxx: odsazeni v tomto <td> (tj. x-velikost oblasti fajfek)

  var rx,rxx,pos;
  // srv.: http://acko.net/blog/mouse-handling-and-absolute-positions-in-javascript
  if (!window.opera && typeof e.offsetX != 'undefined')
  { // MSIE...
    rx=e.offsetX;
  }
  else
  { // ostatni prohlizece...
    pos=getAbsolutePosition(td);
    rx=e.pageX-pos.x;
  }

  rxx=td.style.paddingLeft;
  rxx=rxx.replace(/px/, "");

  // jenom oblast fajfek
  if (rx<=rxx)
  {
    // priprava na sbalovani/rozbalovani/pridavani...
    var tr=td.parentNode;
    do tr = tr.nextSibling; while (tr && tr.nodeType != 1);
    var lll=bgim.length;
    var tdd,ll;

    if (bgim.search(/p.png/)!=-1)
    { // rozbalit
      td.style.backgroundImage=bgim.replace(/p\.png/, 'm.png');

      var shouldload=false;
      while (tdd=findChildByClass(tr,'forumlist'))
      {
        ll=tdd.style.backgroundImage.length;
        if (ll<=lll) break;

	if (tr.olddisplay) tr.style.display=tr.olddisplay.pop();
        do tr = tr.nextSibling; while (tr && tr.nodeType != 1);
	shouldload=true;
      }

      if (!shouldload)
      { // FIXME FIXME FIXME: nahrat novy obsah pres AJAX...
          var newTR = json_to_element(
	    [ 'E', 'tr', [
	       'A', 'class', 'loading',
	       'E', 'td', [
	         'A', 'colspan', '2',
		 'E', 'i', ['T', 'Nahrávám...']]] ], null);

	  newTR.childNodes[0].loading=true;
	  insertAfter( td.parentNode, newTR );
	  if (!ajaxurl)
	  {
            alert("AJAX-url not found!\nKill the developer!!!");
	  }
	  else
	  {
            td.xtmr=new_xml_http_req();
            td.xtmr.onreadystatechange = function() { tabulka_fetchrows (td.xtmr, td.parentNode, td.parentNode.nextSibling); };
            td.xtmr.open('GET', ajaxurl, true);
            td.xtmr.send(null);
	  }
      }

    }
    else if (bgim.search(/m.png/)!=-1)
    { // sbalit
      td.style.backgroundImage=bgim.replace(/m\.png/, 'p.png');

      while (tdd=findChildByClass(tr,'forumlist') || tr.loading)
      {

        // odstranit pripadne nahravane objekty pres AJAX (FIXME, zastavit xmlrequest!!!)
        if (tr.loading)
	{
	  tr1=tr;
          do tr = tr.nextSibling; while (tr && tr.nodeType != 1);
          tr1.parentNode.removeChild(tr1);
          continue;
	}

        ll=tdd.style.backgroundImage.length;
        if (ll<=lll) break;

        if (!tr.olddisplay) tr.olddisplay=new Array();
	tr.olddisplay.push(tr.style.display);
	tr.style.display="none";
        do tr = tr.nextSibling; while (tr && tr.nodeType != 1);
      }
    }
    return false;
  }
  return true;
}

function tabulka_fetchrows(http_request, trg, newtr) {
  if (http_request.readyState==4)
  {
    if (http_request.status==200)
    {
      if (http_request.responseText.length>0)
      { // nacteno neco
        eval("var json = "+http_request.responseText);
	insertAfter( trg, json_to_element(json, null));
	newtr.parentNode.removeChild(newtr);
      }
      else
      { // načteno nic
	newtr.parentNode.removeChild(newtr);
      }
    }
    else
    { // pri nacitani nastala chyba!
      insertAfter( trg, json_to_element( [ 'E', 'tr', [ 'A', 'class', 'loading',
	       'E', 'td', [ 'A', 'colspan', '2', 'E', 'i', ['T', 'Chyba!']]] ], null));
      newtr.parentNode.removeChild(newtr);
    }
  }
}
function tabulka_rozbal_kurzor (e, id) {
  e = (e) ? e : window.event;
  var td = document.getElementById(id);
  var bgim=td.style.backgroundImage;
  var rx,rxx,pos;

  // srv.: http://acko.net/blog/mouse-handling-and-absolute-positions-in-javascript
  if (!window.opera && typeof e.offsetX != 'undefined')
  { // MSIE...
    rx=e.offsetX;
  }
  else
  { // ostatni prohlizece...
    pos=getAbsolutePosition(td);
    rx=e.pageX-pos.x;
  }

  rxx=td.style.paddingLeft;
  rxx=rxx.replace(/px/, "");

  // jenom oblast fajfek
  if (rx<=rxx)
  {
    if (bgim.search(/[mp].png/)!=-1)
    {
      if (navigator.userAgent.search(/MSIE/)!=-1)
      { td.style.cursor="hand"; }
      else
      { td.style.cursor="pointer"; }
    }
  }
  else
  {
    td.style.cursor="";
  }
}

function tabulka_sbal (id) {
  var td = document.getElementById(id);
  var bgim=td.style.backgroundImage;

  var ll, tr1;
  var tr=td.parentNode;
  var lll=bgim.length;

  do tr = tr.nextSibling; while (tr && tr.nodeType != 1);
  td.style.backgroundImage=bgim.replace(/m\.png/, 'p.png');

  while (tdd=findChildByClass(tr,'forumlist'))
  {
    ll=tdd.style.backgroundImage.length;
    if (ll<=lll) break;

    if (!tr.olddisplay) tr.olddisplay=new Array();
    tr.olddisplay.push(tr.style.display);
    tr.style.display="none";
    do tr = tr.nextSibling; while (tr && tr.nodeType != 1);
  }
}

function evangnet_add_popups () {
  if (!document.getElementsByTagName) { return; }

  // 1) linky...
  var elz = document.getElementsByTagName('a');
  for (var i=0, l=elz.length; i<l; i++)
  {
    var ee=elz[i];
    if ((ee.className != "ext") && (ee.className != "noext") && (ee.target == "_new" || ee.target == "_blank"))
    {
      ee.onmouseover=new Function('show_popup_info(this, "/export/ajax/url?url=", true);');
      ee.onmouseout=new Function('hide_popup_info(this);');
    }

    // odkaz na biblicky oddil...
    //if (ee.className == "biblnk")
    //{
    //  ee.onmouseover=new Function('show_popup_info(this, "/export/ajax/bc?bc=", false);');
    //  ee.onmouseout=new Function('hide_popup_info(this);');
    //}
  }

  // 2) abbr...
  var elz = document.getElementsByTagName('abbr');
  for (var i=0, l=elz.length; i<l; i++)
  {
    var ee=elz[i];
    if (ee.className == "biblnk")
    {
      ee.onmouseover=new Function('show_popup_info(this, "/export/ajax/bc?bc=", false);');
      ee.onmouseout=new Function('hide_popup_info(this);');
    }
    else
    {
      ee.onmouseover=new Function('show_popup_info(this, "/export/ajax/zkratky?z=", false);');
      ee.onmouseout=new Function('hide_popup_info(this);');
    }
  }
}

// nastavit TI
function TIset (myid, hisid) {
  if (document.getElementById(myid).checked)
    document.getElementById(hisid).checked=1; 
  else
    document.getElementById(hisid).checked=0;
}

function TIunset (myid, hisid) {
  if (!document.getElementById(myid).checked)
    document.getElementById(hisid).checked=0;
}

// TODO: just for testing purp. !!!!!
// http://btmp.evangnet.cz/test/json2el
function tst_append_json_to_el (jsonid, id) {
  var json = document.getElementById(jsonid).value;
  if (!json) return;
  json = eval(json);
  var el = document.getElementById(id);
  el.appendChild(json_to_element(json), null);
  
}


/* ------------------- kalendarik --------------------- */

function kalendarik_clear() {
  var kal = document.getElementById('kalendarik');
  if (kal && kal.mdselect)
  {
    var jd;
    for (jd=kal.jd1; jd<=kal.jd2; jd++)
    {
      trgchlv = document.getElementById('kalendarik_'+jd);
      if (trgchlv.oldcls) trgchlv.className=trgchlv.oldcls;
    }
    kal.mdselect=null;
  }
}

function kalendarik_out(e) {
  var ev = e ? e : window.event;

  // zjistime pozici kurzoru mysi
  //  viz http://www.howtocreate.co.uk/tutorials/javascript/eventinfo
  var x,y;
  if (typeof(ev.pageX) == "undefined")
  { x=ev.clientX; y=ev.clientY; } // MSIE...
  else
  { x=ev.pageX; y=ev.pageY; }

  // zjistime pozici kalendariku
  var kal = document.getElementById('kalendarik');
  var pozice=getAbsolutePosition(kal); // MSIE = fuj...

  // otestujeme, zda-li jsme prave "vypluli" z kalendariku VEN...
  if ((x<=pozice.x) || (x>=(pozice.x+kal.offsetWidth)) ||
      (y<=pozice.y) || (y>=(pozice.y+kal.offsetHeight))  ) 
    kalendarik_clear();

  var testsel = document.getElementById('testsel');
  if (testsel)
  {
    var ss;
    ss ='(x: '+x+', y:'+y+') ';
    ss+='(poz.x: '+pozice.x+', poz.y:'+pozice.y+') ';
    ss+='(offsetWidth: '+kal.offsetWidth+', offsetHeight:'+kal.offsetHeight+') ';
    testsel.innerHTML=ss;
  }

}

function kalendarik_down(jdd, dtst, jd1, jd2) {
  var kal = document.getElementById('kalendarik');
  kal.mdselect=1;
  kal.jdd=jdd; kal.jd1=jd1; kal.jd2=jd2;
  kal.dtst=dtst;
  var mee = document.getElementById('kalendarik_'+jdd);
  if (!mee.oldcls) mee.oldcls=mee.className;
  mee.className="select";
  return false;
}

function kalendarik_up(jdu, dtst, q) {
  var kal = document.getElementById('kalendarik');
  if (kal.mdselect)
  {
    var days=jdu-kal.jdd;
    var dst=(days>=0)?kal.dtst:dtst;
    days=(days<0)?1-days:days+1;
    if (days>99) days=99;

    var dd=(days==1)?'den':(days+'dni');
    var url='/kalendar/'+dd+'/'+dst+q;
    location.href=url;
    return false;
  }
}

function kalendarik_over(jdo, jd1, jd2) {
  var kal = document.getElementById('kalendarik');
  if (kal.mdselect)
  {
    var jd, jds, jde;
    var trgchlv;

    if (kal.jdd<jdo)
    {
      jds=kal.jdd; jde=jdo;
    }
    else
    {
      jde=kal.jdd; jds=jdo;
    }

    for (jd=kal.jd1; jd<=kal.jd2; jd++)
    {
      trgchlv = document.getElementById('kalendarik_'+jd);
      if (jd>=jds && jd<=jde)
      {
        if (!trgchlv.oldcls) trgchlv.oldcls=trgchlv.className;
        trgchlv.className="select";
      }
      else
      {
        if (trgchlv.oldcls) trgchlv.className=trgchlv.oldcls;
      }
    }
  }
}

/* ==============================================================================
 *         editace stitku...
 */
    function tags_remove_li (ulid, inpid, val) {
      var ul = document.getElementById(ulid);
      for (var i=ul.childNodes.length; i; i--)
        if (ul.childNodes[i-1].hodnota==val)
	  ul.removeChild(ul.childNodes[i-1])
      tags_update (ulid, inpid);
    }

    function tags_update (ulid, inpid) {
      var ul = document.getElementById(ulid);
      var inp = document.getElementById(inpid);
      var tx='', nfs=0, i=0;
      var ln=ul.childNodes.length;
      for (i=0; i<ln; i++)
        if (ul.childNodes[i].hodnota)
        {
    	  if (nfs) tx=tx+', ';
    	  nfs=1;
    	  tx=tx+ul.childNodes[i].hodnota;

          // korektne nastavit class podle pozice <li>
	  if (i==0)
	    ul.childNodes[i].className='first';
	  else if (i==ln-1)
	    ul.childNodes[i].className='last';
	  else
	    ul.childNodes[i].className=null;
        }
      inp.value=tx;
    }

    function tags_check4val (ulid, val) {
      var ul = document.getElementById(ulid);
      for (var i=ul.childNodes.length; i; i--)
        if (ul.childNodes[i-1].hodnota==val)
	  return true;
      return false;
    }

    function tags_add_li (ulid, inpid, val, text, entname) {
      if (!val || val==null) return false;

      // pokud uz tag existuje: skoncit...
      if (tags_check4val(ulid, val))
      {
        alert(entname+" '"+text+"' je již na seznamu!");
        return false;
      }

      var ul = document.getElementById(ulid);
      var li, txt, txt2, img, a;

      li=document.createElement('li');
      txt=document.createTextNode(text+'\u00A0(');
      txt2=document.createTextNode(')');
      img=document.createElement('img');
      img.onclick=new Function ("tags_remove_li('"+ulid+"', '"+inpid+"', '"+val+"');");
      img.src="/img/icons/remove.gif";
      img.alt="x";
      img.title="odstranit";
      li.appendChild(txt);
      li.appendChild(img);
      li.appendChild(txt2);
      li.hodnota=val;
      ul.appendChild(li);
    }

    function form_add_tag_on_select (inpid, selid, ulid, selval, entname) {
      var stir, text;
      var sel = document.getElementById(selid);
      var cls = sel.options[sel.selectedIndex].className;
      var val= sel.options[sel.selectedIndex].value;
      if (selval=='inner')
        text= sel.options[sel.selectedIndex].innerHTML;
      else
        text= val;

      sel.selectedIndex=0;

      if (val=='$ADD$')
      {
        stir='';
        do {
          stir=prompt('Vložte nový štítek:', stir);
	  if (stir && stir.indexOf(',')!=-1)
	    alert('Štítek nesmí obsahovat čárku!');
	} while (stir && stir.indexOf(',')!=-1)
	text=stir;
      }
      else if (val!='$TITLE$' && cls!='opt_title')
      {
        stir=val;
      }
      else
        return ;

      tags_add_li (ulid, inpid, stir, text, entname);
      tags_update (ulid, inpid);
    }

    function get_select_value (sel, val) {
      for (var i=sel.childNodes.length; i; i--)
        if (sel.childNodes[i-1].value==val)
	   return sel.childNodes[i-1].innerHTML;
      return val;
    }

    function tags_load_from_input (ulid, inpid, selid) {
      var sel;
      if (selid!=null) sel= document.getElementById(selid);
      var inp = document.getElementById(inpid);
      var val=inp.value, arr, v, tx;
      if (!inp) return false;
      arr=val.split(',');
      var ln=arr.length;
      for (var i=0; i<ln; i++)
      {
	v=arr[i].replace(/^\s+/, '').replace(/\s+$/, '');
	if (v && v!="") {
	  if (selid==null)
	    tx=v;
	  else
	    tx=get_select_value(sel, v);
	  tags_add_li (ulid, inpid, v, tx, "");
	}
      }

      tags_update (ulid, inpid);
    }


// ================ BIG POPUP =======================================================

 function remove_bpop() {
   removeByClass('div', 'bpop');
   removeByClass('div', 'bpop_back');
   document.onmousemove=null;
   document.onmouseup=null;
 }

 function stick_bpop() {
   removeByClass('div', 'bpop_back');
 }

 function bpop_ifocus () {
   var cnt=document.getElementById('bpop_content').contentDocument; /// .body;/////.childNodes[0];
   /// alert(cnt);
   cnt.body.focus();

   cnt.onkeydown=function(e) { 	
     if (e==null) { keycode=event.keyCode; } else { keycode=e.which; }
  
     if(keycode==27)
     {
       remove_bpop();
     }
   }	

   /*
   cnt.style.color='red';
   */
 }

// EXAMPLE...
 function bpop_darken(trg, opa, maxo, step, wait) {
   var el=document.getElementById(trg);
   opa=opa+step;
   if (opa<maxo) setTimeout('bpop_darken("'+trg+'", '+opa+', '+maxo+', '+step+', '+wait+')', wait);
   el.style.opacity=opa/100;
 }

 function bpop_mousedown (e) {
   if (!e) var e = window.event;
   var m=document.getElementById('bpop_main');
   var n=document.getElementById('bpop_nudle');
   var b=document.getElementById('bpop_back');
   m.style.cursor='move';
   n.style.backgroundColor='#f3d579';
   if (b!=null) b.style.cursor='move';
   m.evgdragging=1;
   m.evgdragX=e.clientX;
   m.evgdragY=e.clientY;
   m.evgdragY=e.clientY;
   if (m.evgdragLast !=1)
   {
     m.evgdragLX=-330;
     m.evgdragLY=-200;
   }
   return false;
 }

 function bpop_mouseup (e) {
   if (!e) var e = window.event;
   var m=document.getElementById('bpop_main');
   var n=document.getElementById('bpop_nudle');
   var b=document.getElementById('bpop_back');
   if (m.evgdragging==1)
   {
     m.style.cursor='auto';
     n.style.backgroundColor='';
     if (b!=null) b.style.cursor='auto';
     m.evgdragging=0;
     m.evgdragLast=1;
     m.evgdragLX=m.evgdragLX+e.clientX-m.evgdragX;
     m.evgdragLY=m.evgdragLY+e.clientY-m.evgdragY;
   }
   return false;
 }

 function bpop_mousedrag (e) {
   if (!e) var e = window.event;
   var m=document.getElementById('bpop_main');
   if (m.evgdragging)
   {
     var ndl=document.getElementById('bpop_nudle');
     m.style.left=(m.evgdragLX+e.clientX-m.evgdragX)+'px';
     m.style.top= (m.evgdragLY+e.clientY-m.evgdragY)+'px';
   }
   return false;
 }

 function bpop_pop(url, nadpis, linkz) {

   remove_bpop(); // pouze jedno okno na stranku...

   var trg=document.getElementById('footer-container');

   var floutek=new Array('A', 'class', 'floutek');

   var elm;
   if (linkz!=null && linkz.length>0)
     for (var i=0; i<linkz.length; i++) {
       var lk=linkz[i];
       if (lk[1]==null) { elm='span'; } else { elm='a'; }
       floutek=floutek.concat(['E', elm, ['A', 'class', lk[2], 'A', 'href', lk[1], 'A', 'target', lk[3], 'T', lk[0]] , 'T', '\u00A0| ']);
   }

   // nakonec link na zavreni okna...
/// TEST   floutek=floutek.concat(['E', 'a', ['A', 'class', 'add', 'A', 'href', '#', 'A', 'onclick', 'stick_bpop();', 'T', 'stick'], 'T', '\u00A0| ']);
   floutek=floutek.concat(['E', 'a', ['A', 'class', 'remove', 'A', 'href', '#', 'A', 'onclick', 'remove_bpop();', 'T', 'zavřít']]);

   insertAfter (trg, json_to_element(
       [ 'E', 'div', [ 'A', 'class', 'bpop_back', 'A', 'id', 'bpop_back'],
         'E', 'div', [ 'A', 'class', 'bpop', 'E', 'div', [ 'A', 'id', 'bpop_main',
	   'E', 'div', [ 'A', 'id', 'bpop_nudle', 'A', 'class', 'nudle', 
	     'E', 'span', floutek,
	     'E', 'span', ['A', 'class', 'header',  'T', nadpis]
	   ],
	   // MSIE delal problemy s vytvarenim framu... :-((
	   /// 'E', 'iframe', [ 'A', 'id', 'bpop_content' , 'A', 'onload', 'bpop_ifocus();', 'A', 'class', 'content', 'A' , 'name', 'bpop_frame' , 'A', 'src', url , 'A', 'frameborder',  '0', 'T', '(iframe)' ]
	 ]]
       ], null));

//   setTimeout('bpop_darken("bpop_back", 0, 60, 7, 50)', 50);

   var frm=document.getElementById('bpop_main');
   var frin = document.createElement('iframe');
   frin.setAttribute('class', 'content');
   frin.setAttribute('frameborder', 0);
   frin.setAttribute('name', 'bpop_frame');
   frin.setAttribute('width', '100%');
   frin.setAttribute('height', '375px;');
   frin.setAttribute('id', 'bpop_content');
   frin.setAttribute('src', url);
   frin.onload=new Function('event', 'bpop_ifocus();');

   var ndle=document.getElementById('bpop_nudle');
   var bcak=document.getElementById('bpop_back');
   ndle.onmousedown=new Function('event', 'return bpop_mousedown(event);');

   ndle.onmouseup=new Function('event', 'return bpop_mouseup(event);');
   bcak.onmouseup=new Function('event', 'return bpop_mouseup(event);');
   document.onmouseup=new Function('event', 'return bpop_mouseup(event);');

   frin.onmouseover=new Function('event', 'return bpop_mouseup(event);');

   ndle.onmousemove=new Function('event', 'return bpop_mousedrag(event);');
   bcak.onmousemove=new Function('event', 'return bpop_mousedrag(event);');
   document.onmousemove=new Function('event', 'return bpop_mousedrag(event);');

   frm.appendChild(frin);

   document.onkeydown=function(e) { 	
     if (e==null) { keycode=event.keyCode; } else { keycode=e.which; }
  
     if(keycode==27)
     {
       remove_bpop();
     }
   }	

   return false;
 }
