var dialogArgumentsForChild = null;
var ModalDialog = new Object();
ModalDialog.value = null;

var isIE6 = false, isIE7 = false, isIE8 = false, isIE9 = false, isFF2 = false, isFF3 = false, isFF4 = false, isFF5 = false, isChrome12 = false;
if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
  var ffversion = new Number(RegExp.$1); // capture x.x portion and store as a number
  if (ffversion >= 5) isFF5 = true;
  else if (ffversion >= 4) isFF4 = true;
  else if (ffversion >= 3) isFF3 = true;
  else if (ffversion >= 2) isFF2 = true;
} else if (/Chrome[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { //test for Chrome/x.x or Chrome x.x (ignoring remaining digits);
  var chromeversion = new Number(RegExp.$1); // capture x.x portion and store as a number
  if (chromeversion >= 12) isChrome12 = true;
} else if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
  var ieversion = new Number(RegExp.$1); // capture x.x portion and store as a number
  if (ieversion >= 9) isIE9 = true;
  else if (ieversion >= 8) isIE8 = true;
  else if (ieversion >= 7) isIE7 = true;
  else if (ieversion >= 6) isIE6 = true;
}
var isIE9OrHigher = isIE9;
var isIE8OrHigher = isIE9OrHigher || isIE8;
var isIE7OrHigher = isIE8OrHigher || isIE7;
var isIE = isIE7OrHigher || isIE6;
var isFF5OrHigher = isFF5;
var isFF4OrHigher = isFF4 || isFF5OrHigher;
var isFF3OrHigher = isFF3 || isFF4OrHigher;
var isFF = isFF3OrHigher || isFF2;
var isChrome12OrHigher = isChrome12;
var isChrome = isChrome12OrHigher; 

// uprava cesty volane stranky relativne k volane strance bez ohledu na aktualni kontext v ceste. 
//
// Mozne zadani url:
// 1) Absolutne: "/stranka.aspx", "http://www.gordic.cz/..." 
// 2) Absolutne vuci rootu aplikace: "~/HlavniStranka.aspx"
// 3) Relativne vuci volane strance: "../DetailSpisu.aspx?...."
// 4) Soucasnou stranku s jinymi parametry: "?param=hodnota"
function TranslateUrlForCall(url) {
    if (url.indexOf("~/") == 0) {
        url = Gordic_General_WebApplication_AppPath+url.substr(2);
    } else if (url.indexOf("?") == 0) {
        url = window.location.pathname + url;
    } else if (url.indexOf("://") < 0 && url.indexOf("/") != 0) {
        var pathname = window.location.pathname; 
        var index = pathname.lastIndexOf("/");
        if (index >= 0) 
            pathname = pathname.substr(0, index+1);
        url = pathname + url;
    }   
    return url; 
}

// pretizeni metody window.close(), nutne pro FF, protoze zavolanim window.close() na strance v IFRAME se nezpusobi zavreni okna, kde IFRAME lezi
var closeFceBackup = window.close; 
window.close = function () {
    // pro FF se musi navratova hodnota predat do volajiciho okna, protoze jinak neni vracena
    if (isFF2===true) {
        if (window.top.opener && window.top.opener.ModalDialog) window.top.opener.ModalDialog.value = window.returnValue;
    } else if (isFF3OrHigher===true || isChrome) {
        window.top.returnValue = window.returnValue; // je treba naplnit returnValue skutecne volaneho okna (ModalWindow.htm). Naplnit returnValue v iframu nestaci
    }    
    // vyvolani window.close() na FF nezpusobi zavreni okna, protoze se close() vola na iframu a ne na okne
    if (window.top.close != window.close)
        window.top.close();
    else 
        closeFceBackup();
}

// Funkce pro vyvolani modalniho okna
function ShowModalWindowEx(url, title, width, height, status, resizable, scroll, WPID){
    dialogArgumentsForChild = new Object();
    dialogArgumentsForChild.window = window;
    dialogArgumentsForChild.sPage = TranslateUrlForCall(url);
    dialogArgumentsForChild.sTitle = title;
    dialogArgumentsForChild.WPID = WPID; 
    var left = (window.screen.width - width) / 2;
    var top = (window.screen.height - height) / 2;
    var glob = GetGlobalManager(); 
    if (WPID && glob) {
        var o = glob.GetWindowSettings(WPID); 
        if (o && o.Width!=0 && o.Height!=0) {
            if (resizable === true) {
                width = o.Width; 
                height = o.Height; 
            }    
            top = o.Top;
            left = o.Left; 
            if (top > screen.height) top = screen.height - height; 
            if (left > screen.width) left = screen.width - width; 
        }
    }
    if (isFF2) {
      // **** FOR FF2 - Pokusime se otevrit nativni modal okno FF ****
      try {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
      } catch (every) { window.alert(jsresModalNotAllowed); return null; }
      var windowArgs = "height=" + height + ", width=" + width + ", top=" + top + ", left=" + left + ", toolbar=0, location=0, menubar=0, dependent=1, dialog=1, minimizable=0, modal=1, status=" + (status ? "1" : "0") + ", resizable=" + (resizable ? "1" : "0") + ", scrollbars=" + (scroll ? "1" : "0");
      window.open(Gordic_General_WebApplication_ModalPage, "", windowArgs);
      if (typeof (ModalDialog) != 'undefined') // pokud se volajici stranka mezitim reloadne, ztrati se kontext ani nema smysl vracet zpet hodnotu
        return ModalDialog.value;
    } else {
      // **** FOR IE,FF3+,CHROME - Otevreme nativni showModalDialog ****
      var windowArgs = "dialogHeight:" + height + "px;dialogWidth:" + width + "px; dialogTop=" + top + "px; dialogLeft=" + left + "px; center:yes; status:" + (status ? "yes" : "no") + ";resizable:" + (resizable ? "yes" : "no") + ";scroll:" + (scroll ? "yes" : "no");
      var oReturn = window.showModalDialog(
              Gordic_General_WebApplication_ModalPage,
              dialogArgumentsForChild,
              windowArgs
        );
      return oReturn;
    }
}

// Funkce pro vyvolani modalniho okna
function ShowModalWindow(url, title, width, height, WPID){
    return ShowModalWindowEx(url, title, width, height, false, false, false, WPID);
}

// Funkce pro vyvolani obycejneho okna
function ShowWindowEx(url, target, width, height, status, resizable, scroll, WPID) {
    var windowArgs;
    if (!width) width = 500; 
    if (!height) height = 400; 
    var left = (window.screen.width - width) / 2;
    var top = (window.screen.height - height) / 2;
    var glob = GetGlobalManager(); 
    if (WPID && glob) {
        var o = glob.GetWindowSettings(WPID); 
        if (o && o.Width!=0 && o.Height!=0) {
            if (resizable === true) {
                width = o.Width; 
                height = o.Height; 
            }
            top = o.Top;
            left = o.Left; 
            if (top > screen.height) top = screen.height - height; 
            if (left > screen.width) left = screen.width - width; 
        }
    }
    windowArgs = "width="+width+", height="+height+", left="+left+", top="+top;
    windowArgs += ", toolbar=0, location=0, menubar=0, dialog=1";
    if (!status) status = false; 
    if (!resizable) resizable = false;
    if (!scroll) scroll = false;
    windowArgs += ", status="+(status?"1":"0")+", resizable="+(resizable?"1":"0")+", scrollbars="+(scroll?"1":"0");
    if (!WPID) WPID="";
    var title=""; 
    if (target && target.indexOf(';') >= 0) {
        var i = target.indexOf(';'); 
        title = target.substr(i+1, target.length); 
        target = target.substr(0,i);  
    }
    
    return ShowWindow(Gordic_General_WebApplication_NonModalPage+"?WPID="+WPID+"&top="+top+"&left="+left+"&title="+encodeURIComponent(title)+"&url="+encodeURIComponent(TranslateUrlForCall(url)), target, windowArgs, false);
}

// Funkce pro vyvolani obycejneho okna, bez IFRAMU
function ShowSimpleWindowEx(url, target, width, height, status, resizable, scroll) {
    var windowArgs;
    if (!width) width = 500; 
    if (!height) height = 400; 
    var left = (window.screen.width - width) / 2;
    var top = (window.screen.height - height) / 2;
    windowArgs = "width="+width+", height="+height+", left="+left+", top="+top;
    windowArgs += ", toolbar=0, location=0, menubar=0, dialog=1";
    if (!status) status = false; 
    if (!resizable) resizable = false;
    if (!scroll) scroll = false;
    windowArgs += ", status="+(status?"1":"0")+", resizable="+(resizable?"1":"0")+", scrollbars="+(scroll?"1":"0");
    
    return ShowWindow(url, target, windowArgs, false);
}    

// Funkce pro vyvolani okna s Help&Manual strankou. Ta nesnese diky absolutne strukturovanym sablonam zobrazeni ve framu (sama pouziva window.top).
function ShowHelpAndManualWindowEx(url, target, width, height, status, resizable, scroll) {
  // HelpAndManual se NESMI volat do FRAMU. Pri zmene chovani ShowWindow, je treba zmenit volani 
  return ShowSimpleWindowEx(url, target, width, height, status, resizable, scroll);
}

// Funkce pro vyvolani obycejneho okna
function ShowWindow(url, target, features, replace) {
    // Funkce ShowWindow je volana z funkce ShowHelpAndManualWindowEx, ktera je zavisla na window.open. Pri zmene zkontrolujte zminenou funkci.
    var win = this.window; 
    if (isFF || isChrome) 
        while (win.top.opener && win.top.opener.closed !== true) win = win.top.opener; 
    return win.open(TranslateUrlForCall(url), target, features, replace);
}

// funkce, ktera otevre modul GINISu v normalizovanem okne 
function RunGinisApp(url, faze, fullscreen) {
    faze += "MainWindow"; 
    if (fullscreen == null) fullscreen = true; 
    var args = "menubar=0,resizable=1,titlebar=1,toolbar=0,status=1"; 
    var sx = parseInt(window.screen.availWidth)-8;
    var sy = parseInt(window.screen.availHeight)-58;
    if (fullscreen) 
        args += ",left=0,top=0,height="+sy+",width="+sx;
        
    var windowExecute = ShowWindow(url, faze, args); 
    windowExecute.focus();
}

// Definice preddefinovanych tlacitek pro MessageBox (kompatibilni s C# enum MessageBoxButtons)
var MessageBoxButtons = new Object();
MessageBoxButtons.AbortRetryIgnore = "AbortRetryIgnore";
MessageBoxButtons.OK = "OK";
MessageBoxButtons.OKCancel = "OKCancel";
MessageBoxButtons.RetryCancel = "RetryCancel";
MessageBoxButtons.YesNo = "YesNo";
MessageBoxButtons.YesNoCancel = "YesNoCancel";
// Definice preddefinovanych vystupu z MessageBox (kompatibilni s C# enum DialogResult)
var DialogResult = new Object();
DialogResult.Abort = "Abort";
DialogResult.Cancel = "Cancel";
DialogResult.Ignore = "Ignore";
DialogResult.No = "No";
DialogResult.None = null;
DialogResult.OK = "OK";
DialogResult.Retry = "Retry";
DialogResult.Yes = "Yes";
// Definice preddefinovanych obrazku pro MessageBox (kompatibilni s C# enum MessageBoxIcon)
var MessageBoxIcon = new Object();
MessageBoxIcon.Asterisk = "Asterisk";
MessageBoxIcon.Error = "Error";
MessageBoxIcon.Exclamation = "Exclamation";
MessageBoxIcon.Hand = "Hand";
MessageBoxIcon.Information = "Information";
MessageBoxIcon.Question = "Question";
MessageBoxIcon.Stop = "Stop";
MessageBoxIcon.Warning = "Warning";

// Funkce pro zobrazeni konfigurovatelneho MessageBoxu v modalnim okne.
// Vstupní argumenty
// message - text hlavni zprávy
// caption - text v zahlavi okna
// buttons - tlacitka ktera se maji zobrazit. Muze obsahovat:
//  1) null ci prazdny retezec - bude zobrazeno jedno tlacitko OK
//  2) Nekterou z preddefinovanych konstant objektu MessageBoxButtons, potom bude zobrazen standardni dialog se std. tlacitky.
//  3) Nazvy tlacitek oddelene carkami (napr. "Smaz,Ponech" - budou nabidnuta tlacitka s zadanymi texty
// icon - URL adresa obrazku 50x50 px, je-li predano null, ci prazdny retezec bude message box bez obrazku.
//        Je mozne pouzit nekterou z nasledujicich preddefinovanych hodnot objektu MessageBoxIcon 
// Navratova hodnota je v pripade
//  1) nepodstatna, je tam jen jedno tlacitko...
//  2) Jedna z preddefinovanych konstant objektu DialogResult 
//  3) Nazev tlacitka, ktere bylo stisknuto (tj. jeden z nazvu ktere byly na vstupu, napr. "Smaz")
// Vzdy muze byt vraceno null (DialogResult.None) - v situaci kdy uzivatel modalní okno zavrel natvrdo "Krizkem".
function MessageBox(message, caption, buttons, icon){
  var l_sUrl = "~/Gin/Gin/MessageBox/MessageBox.aspx?message=" + encodeURI(message);
  caption = caption || ""; 
  if(icon && (icon != "")) l_sUrl += "&image="+icon;
  if(buttons && (buttons != "")) l_sUrl += "&buttons="+encodeURI(buttons);
  var oReturn = ShowModalWindow(l_sUrl, caption, 430, 160); 
  return oReturn;
}

function PreventDefault(e) {
    if ((e) && (e.preventDefault)) e.preventDefault();
    else if (window.event) window.event.returnValue = false; 
    return false; 
}

function StopPropagation(e) {
    if ((e) && (e.stopPropagation)) e.stopPropagation();
    else if (window.event) window.event.cancelBubble = true; 
    return false; 
}

function SetToClipboard(text) {
  if (isIE)
    window.clipboardData.setData("Text", text);
  else if (isFF) {
    try {
      netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
    } catch (every) { window.alert(jsresClipboardNotAllowed); return null; }
    var clip = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
    clip.copyString(text);
  } else if (isChrome)
    window.alert(jsresClipboardNotAllowedOnChrome); 
}

function GetFromClipboard() {
  if (isIE)
    return window.clipboardData.getData("Text");
  else if (isFF) {
    try {
      netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
    } catch (every) { window.alert(jsresClipboardNotAllowed); return null; }
    var clip = Components.classes["@mozilla.org/widget/clipboard;1"].getService(Components.interfaces.nsIClipboard);
    if (!clip) return false;
    var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
    if (!trans) return false; trans.addDataFlavor("text/unicode");
    clip.getData(trans, clip.kGlobalClipboard);
    var str = new Object();
    var strLength = new Object(); 
    trans.getTransferData("text/unicode", str, strLength);
    if (str) str = str.value.QueryInterface(Components.interfaces.nsISupportsString); 
    if (str) pastetext = str.data.substring(0, strLength.value / 2);
    return pastetext; 
  } else if (isChrome)
    window.alert(jsresClipboardNotAllowedOnChrome);
}

function RefreshWindow() {
    document.body.style.width = "0%"; // na IE7 se ve strictu po druhem vytvoreni prestane provedet refresh a fulldiv neni pres celou obrazovku
    document.body.style.width = "100%";
    if (isIE6 === true && window.top && window.top.ResizeWindowForIE6)
        window.top.ResizeWindowForIE6();   
}

function CloseApplication(async) {
    var l_sUrl = TranslateUrlForCall("~/Gin/CloseApplication.aspx");
    
    var serverReq = null;
    if (window.XMLHttpRequest) serverReq = new XMLHttpRequest();
    else if (window.ActiveXObject) { // IE6
      try { serverReq = new ActiveXObject("Msxml2.XMLHTTP"); } 
      catch (e) {
        try { serverReq = new ActiveXObject("Microsoft.XMLHTTP"); } 
        catch (e) {}
      }
    }
    if (!serverReq) return false;

    serverReq.open('POST', l_sUrl, async !== false);
    serverReq.send("");
    return true;
}

var SessionDataToClear = "";
var LastSessionDataToClearChange = null; 

function AsyncSessionClearRun(data) {
    SessionDataToClear += data; 
    var d = new Date();
    if (LastSessionDataToClearChange == null) { 
        // pokud casovac nebezi, spustime ho
        LastSessionDataToClearChange = new Date(); 
        window.setTimeout("ClearSessionData();", 250); 
    } else if (Math.ceil(d.getTime() - LastSessionDataToClearChange.getTime()) > 1000) 
        // pokud casovac bezi dele nez 1000ms, spustime metodu uvolneni okamzite (beh v MP je blokovan napr. modalnim oknem)
        ClearSessionData(); 
} 

function ClearSessionData() {
    // doplneni o aktualni klice dle parametru
    for (var i = 0; i < arguments.length; i++) 
        SessionDataToClear += arguments[i] + "|";
    
    // pokud neni zadny klic ke smazani, vyskocime
    if (SessionDataToClear.length == 0) 
        return true
    
    // Pokud existuje global manager a hlavni stranka je dle MP, zaregistrujeme uvolneni session pres hlavni stranku
    var glob = null; 
    if (arguments.length>0 && GetGlobalManager) { 
        glob=GetGlobalManager(); 
        if (glob) {
            var win = glob.GetWindow('Default0');
            if (win && win.AsyncSessionClearRun && win != this) {
                // registrace uvolneni do hlavni MP 
                win.AsyncSessionClearRun(SessionDataToClear); 
                SessionDataToClear = ""; 
                return true; 
            }
        }    
    }    
    
    // Pokud je toto samostatna stranka, nebo bylo vyzadano okamzite odstraneni, zavolame synchronne uvolenni dat ze session    
    var l_sUrl = TranslateUrlForCall("~/Gin/ClearSessionData.aspx");
    var serverReq = null;
    if (window.XMLHttpRequest) serverReq = new XMLHttpRequest();
    else if (window.ActiveXObject) { // IE6
      try { serverReq = new ActiveXObject("Msxml2.XMLHTTP"); } 
      catch (e) {
        try { serverReq = new ActiveXObject("Microsoft.XMLHTTP"); } 
        catch (e) {}
      }
    }
    if (!serverReq) return false;

    serverReq.onreadystatechange = function () { };
    serverReq.open('POST', l_sUrl, true);
    serverReq.send(SessionDataToClear);
    SessionDataToClear = "";
    LastSessionDataToClearChange = null;  
    return true;
}

function DownloadFile(type, data, filename, contenttype) {
    if (!filename) filename = "vychozi_nazev"; 
    if (!contenttype) contenttype = "application/octet-stream"; 
    ShowWindow(encodeURI("~/Gin/FileDownload.aspx?type="+type+"&data="+data+"&filename="+filename+"&contenttype="+contenttype), null, "width=10,height=10,resizable=1");
}

// interni udalost pro zniceni popupokna. Predpoklada se, ze ji zavola fulldiv (nadrazeny div popupu)
function __popupDestroy(e) {
    var div = null;
    if (e && e.target) div = e.target;         // FF, musi byt prvni!
    else if (event && event.srcElement) div = event.srcElement; // IE (FF padne, pokud event neni definovano a v if se na nej zeptame)
    if (div && div.fulldiv) {// udalost se zavola skrz vsechny divy, ktere jsou pres sebe. My nicime jen fulldiv
        parentObject = window.document.body.getElementsByTagName("FORM")[0] || window.document.body;
        try { div.removeChild(div.popupDiv); } catch (every) { }
        parentObject.removeChild(div);
        //RefreshWindow();
        PreventDefault(e); // pri ukonceni pomoci oncontextmenu na fulldivu, je treba potlacit puvodni menu
    }
}

function __popupSetPopupDiv(popupDiv, fulldiv, x, y, width, height) {
}

// interni pretizena funkce popup.show - vytvori fulldiv, schova se do nej a zobrazi popup
function __popupShow(x, y, width, height) {
    this.style.left = x+"px"; 
    this.style.top = y+"px";
    if (width == null) { if (this.ItemArray && this.ItemArray.width) width = this.ItemArray.width; else width = 220; }
    this.style.width = width+"px";
    if (height != null) 
        this.style.height = height+"px";
    this.style.display = "block";
    var cDestroy = typeof(this.customHide) == "function" ? this.customHide : __popupDestroy;

    var fulldiv = this.parentDiv;
    if (this.level == 0) {
      fulldiv = document.createElement('DIV');
      fulldiv.id = "FullDiv" + (popupIdGenerator++); 
      fulldiv.style.position = "absolute";
      fulldiv.style.margin = "0px";
      fulldiv.style.padding = "0px";
      fulldiv.style.left = "0px"; 
      fulldiv.style.top = "0px";
      fulldiv.style.width = "100%"
      fulldiv.style.height = "100%";
      fulldiv.style.zIndex = "500";
      // prazdny bgImage se nastavuje, protoze IE nevyrenderuje DIV spravne pokud neni nastaven bgcolor nebo bgimage
      fulldiv.style.backgroundImage = "url("+TranslateUrlForCall("~/gin/img/empty.gif")+")";
      fulldiv.fulldiv = true;
      fulldiv.popupDiv = this; 
      if (fulldiv.addEventListener) {
          fulldiv.addEventListener("click", cDestroy, false);        // FF
          fulldiv.addEventListener("contextmenu", cDestroy, false);  // FF
      } else {
          fulldiv.onclick = cDestroy;               // IE
          fulldiv.oncontextmenu = cDestroy;         // IE
      }
    }
    if (this.level == 0) {
      parentObject = window.document.body.getElementsByTagName("FORM")[0] || window.document.body;
      parentObject.appendChild(fulldiv);
      //RefreshWindow();
    }

    fulldiv.appendChild(this);
    this.parentDiv = fulldiv;    // protoze FF nezvlada jednoduche prochazeni DOM, vytvorime si vlastni odkaz

    if (this.ItemArray && this.ItemArray.length > 0)  // DULEZITE PORADI PRIDAVANI DIVU DO SEBE, jinak je mozne ze na pridanem divu se spatne zaregistruji eventy
      this.innerHTML = CreatePopupMenuHtml(this.ItemArray);

    // zarovnani, aby popup menu neslo pres okraj
    // musi byt pred pridanim bugframu, protoze jinak IE6 trva strasne dlouho nez detekuje fulldiv.clientWidth a menu se submenu se renderuje strasne dlouho
    if (fulldiv.popupDiv.dockToVisibleBorder == true) {
      if (this.clientWidth+this.offsetLeft > fulldiv.clientWidth) 
          this.style.left = (fulldiv.clientWidth - this.clientWidth) + "px";
      if (this.clientHeight+this.offsetTop > fulldiv.clientHeight) 
          this.style.top = (fulldiv.clientHeight - this.clientHeight) + "px";
    }

    // Reseni bugu IE6, kdy prvek <SELECT> (combobox) je vzdy nad ostatnimi prvky bez ohledu na poradi a zindexy a prosvita pres popupmenu
    if (isIE6) {
      var bugframe = document.createElement('IFRAME');
      bugframe.style.zIndex = "-1"; // neptejte se :) 
      bugframe.style.filter = "mask()";
      bugframe.style.position = "absolute";
      bugframe.style.left = "0px";
      bugframe.style.top = "0px";
      bugframe.style.display = "block";
      bugframe.style.width = this.clientWidth;  // "100%" funguje "divne" pokud je submenu, protoze IE spatne prepocita clientWidth
      bugframe.style.height = this.clientHeight;
      this.appendChild(bugframe);
    }

  }

// interni pretizena funkce popup.hide - schova popup
function __popupHide() {
    if (this.level != 0) { 
      this.style.display = "none";
      if (typeof(this.subDiv) != 'undefined' && this.subDiv) 
        this.subDiv.hide();
    } else if (this.parentDiv) { // v podstate musime zavolat parentDiv.click(), ale FF padne, ze nezna click() na divu
        var e = new Object; 
        e.target = this.parentDiv;
        __popupDestroy(e);
    }    
}

// interni pretizena funkce popup.popup - ucelova funkce pro zobrazeni popup menu
function __popupPopup(e, width) {
    this.show(e.clientX-5, e.clientY-5, width);
    PreventDefault(e);
}

// interni pretizena funkce popup.addItem - prida polozku do menu 
function __popupAddItem(text, icon, run, enabled) {
    var Arr = null; 
    if (this.ItemArray) Arr = this.ItemArray;
    else if (this.subItems) Arr = this.subItems; 
    else return null; 
    
    var obj = new Object();
    obj.text = text; 
    if((enabled == null) || (enabled == true)) obj.enabled = true;
        else obj.enabled = false; 
    if(icon && (icon != "")) { 
        obj.icon = icon;
        if ((Arr.popupDiv.translateTangoIconNames == true) && (typeof(popupImgPre) != 'undefined')) 
            if (obj.enabled === true)
                obj.icon = popupImgPre+obj.icon+popupImgExtension;
            else 
                obj.icon = popupImgPreD+obj.icon+popupImgExtension;
    } else obj.icon = null; 
    if(run && (run != "")) obj.run = run; 
        else obj.run = null;
    obj.subItems = new Array();
    obj.subItems.popupDiv = Arr.popupDiv;
    obj.addItem = __popupAddItem;
    obj.addSeparator = __popupAddSeparator;
    Arr.push(obj);
    return obj;
}

// interni pretizena funkce popup.addSeparator - prida oddelovac do menu 
function __popupAddSeparator() {
  return this.addItem("-", null, null, false);
}

// funkce, ktera z predanych ItemArray vytvori vnitrni HTML text contextoveho menu
function CreatePopupMenuHtml(ItemArray) {
    var autoHideStr = "";
    if (ItemArray.popupDiv && ItemArray.popupDiv.autoHide)
        autoHideStr = "document.getElementById('"+ItemArray.popupDiv.id+"').hide(); ";
    var result = "<DIV class='ContextMenu'><TABLE style='width:100%;' cellpadding='0' cellspacing='0'><TBODY>";
    for (var i = 0; i < ItemArray.length; i++) {
        var item = ItemArray[i];
        var hasSubs = item.subItems.length > 0;
        if (item.enabled == true) {
            var onMV = ""; 
            if (hasSubs === true) {
              var subDiv = __createPopupDiv(item.subItems, ItemArray.popupDiv.parentDiv, ItemArray.parentDiv.level + 1);
              ItemArray.parentDiv[subDiv.id] = subDiv; 
                onMV = "var parDiv = document.getElementById(\""+ItemArray.parentDiv.id+"\");"+
                       "var subDiv = parDiv[\""+subDiv.id+"\"]; "+
                       "if (typeof(parDiv.subDiv) != \"undefined\" && parDiv.subDiv != null && parDiv.subDiv != subDiv) { parDiv.subDiv.hide(); parDiv.subDiv = null;} "+
                       "if (subDiv.style.display == \"none\") { subDiv.show(parDiv.offsetLeft+this.clientWidth-5,parDiv.offsetTop+this.offsetTop+3); parDiv.subDiv = subDiv; }";
            } else 
                onMV = "var parDiv = document.getElementById(\""+ItemArray.parentDiv.id+"\"); "+
                       "if (typeof(parDiv.subDiv) != \"undefined\" && parDiv.subDiv != null) { parDiv.subDiv.hide(); parDiv.subDiv = null;} ";
              result += "<TR class='ContextMenuItemNormal' onclick=\"" + autoHideStr + item.run + "\" " +
                      "onmouseover='javascript: className = \"ContextMenuItemHighlight\";"+onMV+"' "+
                      "onmouseout='javascript: className = \"ContextMenuItemNormal\";'>";
        } else
            result += "<TR class='ContextMenuItemDisabled'>";
        result += "<TD class='ContextMenuIconCell' align='center'>";
        if (item.text == "-")
          result += "</TD><TD colspan='2'><IMG src='" + Gordic_General_WebApplication_SkinPath + "images/menuSeparator.gif' style='margin-left:-24px' /></TD>";
        else {
          if (item.icon) result += "<IMG style='margin: 0px; padding:0px; border:none;' SRC='" + TranslateUrlForCall(item.icon) + "' />";
          result += "</TD><TD class='ContextMenuTextCell'>" + item.text + "</TD><TD width='18px'>" + (hasSubs === true ? "&#x25ba;" : "") + "</TD>";
        }
        result += "</TR>";                 
    }
    result += "</TBODY></TABLE></DIV>";
    return result; 
}

var popupIdGenerator = 0 ;
function __createPopupDiv(aItemArray, fullDiv, aLevel) {
    var popupDiv = document.createElement('DIV'); 
    popupDiv.style.position = "absolute";
    popupDiv.style.margin = "0px";
    popupDiv.style.padding = "0px";
    popupDiv.style.display = "none";
    popupDiv.id = "PopupDIV"+(popupIdGenerator++);
    popupDiv.ItemArray = aItemArray;
    popupDiv.ItemArray.parentDiv = popupDiv;
    popupDiv.parentDiv = fullDiv;
    popupDiv.level = aLevel; 
    popupDiv.show = __popupShow;
    popupDiv.hide = __popupHide;
/*    if (aLevel != 0) 
      fullDiv.appendChild(popupDiv);*/
    return popupDiv;
}

// verejna funkce pro vytvoreni platforme nezavisleho popup okna
function createIPopup() {
    var popupDiv = __createPopupDiv(new Array(), null, 0); 
    popupDiv.popup = __popupPopup;
    popupDiv.addItem = __popupAddItem;
    popupDiv.addSeparator = __popupAddSeparator;
    popupDiv.ItemArray.popupDiv = popupDiv;
    popupDiv.ItemArray.addItem = __popupAddItem;
    popupDiv.ItemArray.addSeparator = __popupAddSeparator;
    popupDiv.autoHide = true;
    popupDiv.dockToVisibleBorder = true;
    popupDiv.translateTangoIconNames = true;
    return popupDiv;
}

var __AsyncWind = new Array(); 
function ShowAsyncWindow(url, x, y, width, height, returnFce, data) {
  var d = createIPopup();
  var fr = document.createElement('IFRAME');
  fr.style.position = "absolute";
  fr.style.left = "0px"; 
  fr.style.top = "0px";
  fr.style.display = "block";
  fr.style.width = "100%"
  fr.style.height = "100%";
  
  d.appendChild(fr);
  fr.src = url; 
  __AsyncWind.push(returnFce); 
  __AsyncWind.push(window.top.close);
  __AsyncWind.push(d);
  __AsyncWind.push(fr);
  __AsyncWind.push(data); 
  d.show(x, y, width, height);
  fr.contentWindow.returnValue = null; 
  window.top.close = __bypassedAsyncClose;
  return d;  
}

function __bypassedAsyncClose() {
  var data = __AsyncWind.pop(); 
  var fr = __AsyncWind.pop(); 
  var d = __AsyncWind.pop();
  window.top.close = __AsyncWind.pop();
  var returnFce = __AsyncWind.pop();
  if (returnFce)
    returnFce(fr.contentWindow.returnValue, data);
  fr.contentWindow.returnValue = null; 
  d.hide();
}

// IE6,IE7 neumozni prepsat window.close v modalnim okne, ma to natvrdo. Funkce je alternativou k window.close()
window.close2 = function() {
  if (__AsyncWind.length > 0) 
    window.setTimeout("__bypassedAsyncClose()", 1); 
  else if (parent.window.close2) 
    parent.window.close2();
  else
    window.close();
}

function CreateCoverDiv(parentDiv) {
  if (typeof (parentDiv.coverDiv) != "undefined" && parentDiv.coverDiv != null) return;   
  coverdiv = document.createElement('DIV');
  coverdiv.id = "Cover" + (popupIdGenerator++); 
  coverdiv.className = "CoverDiv";
  // prazdny bgImage se nastavuje, protoze IE nevyrenderuje DIV spravne pokud neni nastaven bgcolor nebo bgimage
  coverdiv.style.backgroundImage = "url(" + TranslateUrlForCall("~/gin/img/empty.gif") + ")";
  img = document.createElement('IMG');
  img.src = TranslateUrlForCall("~/gin/Graphics/Images/Tango/aplikace_pracuje_anim.gif");
  img.className = "CoverImgSmall";
  coverdiv.img = img; 
  parentDiv.appendChild(coverdiv);
  parentDiv.appendChild(img); 
  parentDiv.coverDiv = coverdiv;
  parentDiv.hideCoverDiv = function () {
    HideCoverDiv(this);
  };
}

function HideCoverDiv(parentDiv) {
  if (typeof (parentDiv.coverDiv) == "undefined" || parentDiv.coverDiv == null) return;
  try {
    parentDiv.removeChild(parentDiv.coverDiv.img);
    parentDiv.removeChild(parentDiv.coverDiv);
    parentDiv.coverDiv = null; 
  } catch (every) { }
}

function ShowAjaxError(WMresult, shorttext) {
  if (typeof(shorttext) != "String")
    shorttext = jsresAJAXDefaultError; 
  var stackTrace = WMresult.get_stackTrace();
  var message = WMresult.get_message();
  var statusCode = WMresult.get_statusCode();
  var exceptionType = WMresult.get_exceptionType();
  var timedout = WMresult.get_timedOut();
  var s = "------------------------------------------------------\n" +
        "Exception Type: " + exceptionType + "\n" +
        "Service Error: " + message + "\n" +
        "Stack Trace:\n" + stackTrace + "\n" +
        "Status Code: " + statusCode + "\n" +
        "Timedout: " + timedout;

  if (window.confirm(shorttext + "\n\n" + jsresAJAXMoreInfo))  
    window.alert(shorttext + "\n" + s);
}

String.prototype.trim = function (chars) { return trim(this.toString(), chars); }
String.prototype.trimLeft = function (chars) { return ltrim(this.toString(), chars); }
String.prototype.trimRight = function (chars) { return rtrim(this.toString(), chars); }

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"), "");
}

// dodefinovani XMLHttpRequest pro IE6
if (isIE && (typeof(XMLHttpRequest) == "undefined"))
  XMLHttpRequest = function() {
    var serverReq = null; 
    if (window.ActiveXObject) { // IE6
      try { serverReq = new ActiveXObject("Msxml2.XMLHTTP"); }
      catch (e) {
        try { serverReq = new ActiveXObject("Microsoft.XMLHTTP"); }
        catch (e) { }
      }
    }
    return serverReq;
  }
  

