var http_request = false;
postingrequest=false;
var activehtmlarea='';
var inputcontrols;

function AJAXget(url,fdone,target) {
  if (postingrequest) return;
  postingrequest=true;
  http_request = false;
//      document.getElementById('indicator').style.visibility="visible";
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
     http_request = new XMLHttpRequest();
     if (http_request.overrideMimeType) {
        http_request.overrideMimeType('text/html');
     }
  } else if (window.ActiveXObject) { // IE
     try {
        http_request = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e) {
        try {
           http_request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
     }
  }
  if (!http_request) {
     postingrequest=false;
     alert('Cannot create XMLHTTP instance');
     return false;
  }
  SetCursor('wait');
  http_request.onreadystatechange = function () {AJAXrequestDone(fdone,target)};
  http_request.open('GET', url, true);
  http_request.send(null);
}

function AJAXpost(form,url,target,onfinish) {
  if (postingrequest) return;
  postingrequest=true;
  http_request = false;
//      document.getElementById('indicator').style.visibility="visible";
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
     http_request = new XMLHttpRequest();
     if (http_request.overrideMimeType) {
        http_request.overrideMimeType('text/html');
     }
  } else if (window.ActiveXObject) { // IE
     try {
        http_request = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e) {
        try {
           http_request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
     }
  }
  if (!http_request) {
     postingrequest=false;
     alert('Cannot create XMLHTTP instance');
     return false;
  }
  var requestbody=[];  
  AJAXgetFormValues(form.getElementsByTagName("input"),requestbody);
  AJAXgetFormValues(form.getElementsByTagName("textarea"),requestbody);
  AJAXgetFormValues(form.getElementsByTagName("select"),requestbody);
  requestbody=requestbody.join('&');
  SetCursor('wait');
  http_request.onreadystatechange = function () {AJAXrequestDone(showContent,target,onfinish);};
  http_request.open('POST', url, true);
  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http_request.setRequestHeader("Content-length", requestbody.length);
  http_request.send(requestbody);
  return true;
}

function AJAXgetFormValues(ea,requestbody) {
  var element,value;
  for (var i=0;i<ea.length;i++) {
    element=ea[i];
    if (element.attributes.name && element.attributes.name.specified && !element.disabled) {
      name=element.name;
      switch(element.type) {
        case "select": //tagName
          var options = element.options;
          for (var j=0; j < options.length; j++) {
              if (options[j].selected) {
                  value = (options[j].attributes.value && options[j].attributes.value.specified ? options[j].value : options[j].text);
                  requestbody.push(encode2(name) + '=' + encode2(value));
              }
          }
        case "select-one":
          value=element.options[element.selectedIndex].value;
          requestbody.push(encode2(name) + '=' + encode2(value));
          break;
        case "checkbox":
          if (element.checked == true) value=element.value;
          requestbody.push(encode2(name) + '=' + encode2(value));
          break;        
        case "image":
          requestbody.push(encode2(name+".x") + '=1');
          requestbody.push(encode2(name+".y") + '=1');
          break;        
        default: //"text", "textarea":
          value=element.value;
          requestbody.push(encode2(name) + '=' + encode2(value));
          break;
      }
    }
  }
  return requestbody;
}

function encode2(s) {
  return encodeURIComponent(s).replace('\'','%27');
}

function AJAXrequestDone(fdone,target,onfinish) {
  if (http_request.readyState == 4) {
    if (http_request.status == 200) {
      try {
        SetCursor('Auto');
        if (fdone) fdone(http_request.responseText,target);
        if (onfinish) onfinish(); 
//        if (SubmitFinish) alert('1');//SubmitFinish(http_request.responseText);
//        else if (fdone) alert('2'); //fdone(http_request.responseText); 
      }
      catch (e) {}
    }
    postingrequest=false;
  }
}

function Chr(CharCode){
	return String.fromCharCode(CharCode);
}

function setCookie(nazev,hodnota) {
  document.cookie=nazev+'='+hodnota;
}

function readCookie(nazev){
  var arrcookie = document.cookie.split(";");
  for (var i=0;i<arrcookie.length;i++){
    cook = arrcookie[i].split("=");
    if (Trim(cook[0]) == nazev) return cook[1];
  }
  return '';
}
  
function delCookie(name) {
  document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
} 

function LTrim(String) {
  var i = 0; var j = String.length - 1;
  if (String == null)	return (false);
  for (i = 0; i < String.length; i++) if (String.substr(i, 1) != ' ' && String.substr(i, 1) != '\t') break;
  if (i <= j) return (String.substr(i, (j+1)-i)); else return ('');
}

function RTrim(String) {
  var i = 0; var j = String.length - 1;
  if (String == null) return (false);
  for(j = String.length - 1; j >= 0; j--)	if (String.substr(j, 1) != ' ' &&	String.substr(j, 1) != '\t') break;
  if (i <= j)	return (String.substr(i, (j+1)-i));	else return ('');
}

function Trim(String) {
  if (String == null) return (false);
  return RTrim(LTrim(String));
}

function Len(string) {
	if (string == null)	return (false);
	return String(string).length;
}

function Left(String, Length) {
	if (String == null) return (false);
	return String.substr(0, Length);
}

function Right(String, Length) {
	if (String == null)	return (false);
  var dest = '';
  for (var i = (String.length - 1); i >= 0; i--) dest = dest + String.charAt(i);
	String = dest;
	String = String.substr(0, Length);
	dest = '';
  for (var i = (String.length - 1); i >= 0; i--) dest = dest + String.charAt(i);
	return dest;
}

function Mid(String, Start, Length) {
	if (String == null) return (false);
	if (Start > String.length) return '';
	if (Length == null || Length.length == 0) return (false);
	return String.substr((Start - 1), Length);
}

function execJS(node) {
  var bSaf = (navigator.userAgent.indexOf('Safari') != -1);
  var bOpera = (navigator.userAgent.indexOf('Opera') != -1);
  var bMoz = (navigator.appName == 'Netscape');
  var st = node.getElementsByTagName('script');
//  alert(node.innerHTML);
  var strExec; 
  for(var i=0;i<st.length; i++) {
//  alert(i);
    if (bSaf) strExec = st[i].innerHTML; 
    else 
      if (bOpera) strExec = st[i].text; 
      else 
        if (bMoz) strExec = st[i].textContent; 
        else strExec = st[i].text; 
    try {
      eval(strExec);
    } 
    catch(e) {}
  }
}
   
function AddEvent(el,evname,func) {
  if (el.addEventListener) el.addEventListener(evname, func, true);
  else 
    if (el.attachEvent) el.attachEvent("on" + evname, func);
}

function showContent(x,tname) {
  var t;
  if (!tname) {
//    t=document.getElementById('TB_ajaxContent');
//    if (!t) 
    t=document.getElementById('ajaxbox');
  }
  else t=document.getElementById(tname);
  if (t) {
    t.innerHTML=x;
//  execJS(t);
  }
  else {
    document.open(); 
    document.write(x); 
    document.close();
  }
}

function SetCursor(w) {
  if (document.body.style) document.body.style.cursor=w; 
  else 
    if (document.documentElement.style) document.documentElement.style.cursor = w; 
    else 
      if (document.getElementsByTagName('body')[0].style) document.getElementsByTagName('body')[0].style.cursor=w;
}

function AJAXopenURL(u) {
  if (document.getElementById('TB_ajaxContent'))
//    tb_show(TB_CAPTION,u + tbwindowsize(TB_PWIDTH,TB_PHEIGHT),"");
    tb_show(TB_CAPTION,u,"");
  else  
    AJAXget(u,showContent,null);
}

function AJAXopenURLinto(u,div) {
  AJAXget(u,showContent,div);
}

function OpenURL(u) {
  window.location.replace(u);
}


function CopyDivToTextArea(c) {
  var t=document.getElementById(c + '-text').innerHTML;
  t=t.replace(/<([^>]+)>/g,function(word){return word.toLowerCase();});
//  t=t.replace(/<p>/g,);
//  if(typeof CustomCopyDivToTextArea == 'function') {
  if (window.CustomCopyDivToTextArea) { 
    t=CustomCopyDivToTextArea(t);
  } 
  document.getElementById(c).value=t;
}

function CopyTextAreaToDiv(c) {
  var t=document.getElementById(c).value;
//  if(typeof CustomCopyTextAreaToDiv == 'function') {
  if (window.CustomCopyTextAreaToDiv) { 
    t=CustomCopyTextAreaToDiv(t);
  }
  document.getElementById(c + '-text').innerHTML=t;
}

function ShowHTMLtoolbar(c,e) {
//aktualni
//tinyMCE.init({mode : "none",theme : "advanced",plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount",theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",theme_advanced_toolbar_location : "top",theme_advanced_toolbar_align : "left",theme_advanced_statusbar_location : "bottom",theme_advanced_resizing : true,content_css : "css/content.css",template_external_list_url : "lists/template_list.js",external_link_list_url : "lists/link_list.js",external_image_list_url : "lists/image_list.js",media_external_list_url : "lists/media_list.js",	template_replace_values : {	username : "Some User",	staffid : "991234"}});
//tinyMCE.execCommand('mceAddControl', false, c+'-text');

//var mcee=new tinymce.Editor(c,{mode : "none",theme : "advanced",plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount",theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",theme_advanced_toolbar_location : "top",theme_advanced_toolbar_align : "left",theme_advanced_statusbar_location : "bottom",theme_advanced_resizing : true,content_css : "css/content.css",template_external_list_url : "lists/template_list.js",external_link_list_url : "lists/link_list.js",external_image_list_url : "lists/image_list.js",media_external_list_url : "lists/media_list.js",	template_replace_values : {	username : "Some User",	staffid : "991234"}});
// mcee.id=c;
 //mcee.render();
  var i;
  var d=document.getElementById('T22htmltoolbar');
  if (d.style.display!='block') {
    d.style.display='block';
    var h=d.getBoundingClientRect().bottom-d.getBoundingClientRect().top;  
      if (!d.forcebodymargin) { 
        d.oldbodymargin=document.body.style.marginTop;
      }
      d.forcebodymargin=true;
      document.body.style.marginTop=h + 'px';
  }
  if (c) {
    var ctextarea=document.getElementById(c);
    var cdiv=document.getElementById(c+'-text');
    if (activehtmlarea!=c) {
      activehtmlarea=c;
    }
    if (cdiv.style.visibility!='hidden') {
      if (e!=cdiv) cdiv.focus();
      for (var i=0;i<inputcontrols.length;i++) {
        e=document.getElementById(inputcontrols[i]);
        if (e.className=='htmltextarea') {
          ToggleHTMLarea(true,inputcontrols[i],false);
        }
      }
    }  
    else {
      if (e!=ctextarea) ctextarea.focus();
    }
  }
}

function HideHTMLtoolbar() {
  var d=document.getElementById('T22htmltoolbar');
  d.style.display='none';
  if (d.forcebodymargin) { 
    document.body.style.marginTop=d.oldbodymargin;
    d.oldbodymargin=null;
    d.forcebodymargin=false;
  }
}

function ToggleHTMLarea(on,c,f) {
  var d,e;
  if (on) {
    e=document.getElementById(c);
    e.style.left='-5000px';
    e.style.top='0px';
    d=document.getElementById(c+'-text');
    d.style.visibility='visible';
    if (f) d.focus();
  }
  else {
    document.getElementById(c + '-text').style.visibility='hidden';
    d=document.getElementById(c);
    d.style.display='block';
    var e=document.getElementById(c+'-text');
//    d.style.left=e.getBoundingClientRect().left+f_scrollLeft()+'px';
    d.style.left=e.getBoundingClientRect().left-e.offsetParent.getBoundingClientRect().left+f_scrollLeft()+'px';
    var h=d.getBoundingClientRect().bottom-d.getBoundingClientRect().top;
//    d.style.top=e.getBoundingClientRect().top+f_scrollTop()+'px';
    d.style.top=e.getBoundingClientRect().top-e.offsetParent.getBoundingClientRect().top+f_scrollTop()+'px';
    if (f) d.focus();  
  }
}

// Open Color Dialog to Set ForeColor or BackColor
var Color;              // ForeColor|BackColor
var FGInitColor = null; // Flag for dialog display
var BGInitColor = null; // Flag for dialog display
var FGChosenColor;      // Color chosen from dialog
var BGChosenColor;      // Color chosen from dialog
var TempString;         // 
var SelectRange;        // Text Range made from selection

function SetColor()
{
	if (Color == "ForeColor") 
	{
		// Display color dialog
		if (FGInitColor == null) {
			FGChosenColor = FGCOLORDIALOG.ChooseColorDlg();
		} else {
			FGChosenColor = FGCOLORDIALOG.ChooseColorDlg(FGInitColor);
		};
		
		// Change decimal to hex
		FGChosenColor = FGChosenColor.toString(16);
		
		// Add extra zeroes if hex number is less than 6 digits
		if (FGChosenColor.length < 6) {
  		TempString = "000000".substring(0,6-FGChosenColor.length);
  		FGChosenColor = TempString.concat(FGChosenColor);
		};
		
		// Make range from selection and apply color
		SelectRange = document.selection.createRange();
		SelectRange.execCommand(Color,false,FGChosenColor);
		
		// Set the initialization color to the chosen color
		FGInitColor = FGChosenColor;
		
		// Set color on button icon
		//FGColorBar.style.backgroundColor = FGChosenColor
	};
	
	if (Color == "BackColor") 
	{
		// Display color dialog
		if (BGInitColor == null) {
			BGChosenColor = BGCOLORDIALOG.ChooseColorDlg();
		} else {
			BGChosenColor = BGCOLORDIALOG.ChooseColorDlg(BGInitColor);
		};
		
		// Change decimal to hex
		BGChosenColor = BGChosenColor.toString(16);
		
		// Add extra zeroes if hex number is less than 6 digits
		if (BGChosenColor.length < 6) {
  			TempString = "000000".substring(0,6-BGChosenColor.length);
  			BGChosenColor = TempString.concat(BGChosenColor);
		};
		
		// Make range from selection and apply color
		SelectRange = document.selection.createRange();
		SelectRange.execCommand(Color,false,BGChosenColor);
		
		// Set the initialization color to the chosen color
		BGInitColor = BGChosenColor;
		
		// Set color on button icon
		//BGColorBar.style.backgroundColor = BGChosenColor
	};
}


function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function ZvyrazniRadek(r) {
  var rows=document.getElementsByName(r);
  for (var i=0;i<rows.length;i++){
    rows[i].classNameold=rows[i].className;
    rows[i].className=rows[i].className + " highlighted";
  }
}

function OdvyrazniRadek(r) {
  var rows=document.getElementsByName(r);
  for (var i=0;i<rows.length;i++){
//      rows[i].className="";
    rows[i].className=rows[i].classNameold;
  }
}

function winH() {
   if (window.innerHeight)
      /* NN4 a kompatibilní prohlížeče */
      return window.innerHeight;
   else if
   (document.documentElement &&
   document.documentElement.clientHeight)
      /* MSIE6 v std. režimu - Opera a Mozilla
      již uspěly s window.innerHeight */
      return document.documentElement.clientHeight;
   else if
   (document.body && document.body.clientHeight)
      /* starší MSIE + MSIE6 v quirk režimu */
      return document.body.clientHeight;
   else
      return null;
}

function winW() {
   if (window.innerWidth)
      /* NN4 a kompatibilní prohlížeče */
      return window.innerWidth;
   else if
   (document.documentElement &&
   document.documentElement.clientWidth)
      /* MSIE6 v std. režimu - Opera a Mozilla
      již uspěly s window.innerHeight */
      return document.documentElement.clientWidth;
   else if
   (document.body && document.body.clientWidth)
      /* starší MSIE + MSIE6 v quirk režimu */
      return document.body.clientWidth;
   else
      return null;
}

function DisplayHTMLtoolbarTabID(s,i,e) {
  var d=document.getElementById('T22htmlToolbarTab'+i);
  if (d) {
    if (e.value==0) e.value=i;
    if (s==i) {
      d.style.display='';
      document.getElementById('T22htmlToolbarHeader'+i).className='';
      return true;
    } else {
      d.style.display='none';
      document.getElementById('T22htmlToolbarHeader'+i).className='inactive';
      return false;
    }
  }
  return false;
}

function DisplayHTMLtoolbarTab(s) {
  if (isNaN(s)) s=1;
  var r;
  var e = new intObject();
  e.value=0;
  r=false;
  for (var i=1;i<=20;i++) r=r | DisplayHTMLtoolbarTabID(s,i,e);
  if (!r) DisplayHTMLtoolbarTabID(e.value,e.value,e);
//  setCookie(viewname+'tab',s);  
}

function SetHTMLtoolbarSize() {
  var d,maxw=0,maxh=0,w,h;
  for (var i=1;i<=20;i++) {
    d=document.getElementById('T22htmlToolbarTab'+i);
    if (d) {
      w=d.offsetWidth;
      if (w>maxw) maxw=w;
      h=d.offsetHeight;
      if (h>maxh) maxh=h;
    }
  }
//  alert (maxw + ' ' + maxh);
  for (var i=1;i<=20;i++) {
    d=document.getElementById('T22htmlToolbarTab'+i);
    if (d) {
      d.style.width=maxw + 'px';
      d.style.height=maxh + 'px';
    }
  }
}

function intObject() {
  this.value;
  return this;
}

function WhatElement(e) {
  e = e || window.event;
  return e.target || e.srcElement;
}

function showBlur(ev) {
   var target = ev.explicitOriginalTarget||document.activeElement;
   document.getElementById("focused").value = 
      target ? target.id||target.tagName||target : '';
}

function FormatBlock(f) {
  if (f!='') {
    document.execCommand('FormatBlock',false,f);
  } else {
//    document.execCommand('FormatBlock',false,'');
    document.execCommand('RemoveFormat');
  }
  document.getElementById(activehtmlarea+'-text').focus();
  CopyDivToTextArea(activehtmlarea);
}

// function tbwindowsize(w,h) {
//   if (w && h)
//     return ('&width=' + w + '&height=' + h);
//   else
//     return ('&width=' + Math.round(winW()*0.9) + '&height=' + Math.round(winH()*0.85));
// }
