var dialogArgumentsForChild = null;
var ModalDialog = new Object;
ModalDialog.value = null;
var isIE = (navigator.appVersion.indexOf('MSIE')>=0); 
var isIE6 = (navigator.appVersion.indexOf('MSIE 6')>=0);
var isFF = !isIE; 

// 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; 
function closeFce() {
    // pro FF se musi navratova hodnota predat do volajiciho okna, protoze jinak neni vracena
    if (isFF===true) {
        if (window.top.opener && window.top.opener.ModalDialog) window.top.opener.ModalDialog.value = window.returnValue;
    }    
    // 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();
}
window.close = closeFce;

// Funkce pro vyvolani modalniho okna
function ShowModalWindowEx(url, title, width, height, status, resizable, scroll){
    dialogArgumentsForChild = new Object();
    dialogArgumentsForChild.window = window;
    dialogArgumentsForChild.sPage = TranslateUrlForCall(url);
    dialogArgumentsForChild.sTitle = title;
    if (isIE===true) {
// **** FOR IE - Otevreme nativni showModalDialog ****
        var windowArgs = "dialogHeight:"+height+"px;dialogWidth:"+width+"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;
    } else {
// **** FOR FF - Pokusime se otevrit nativni modal okno FF ****
        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite"); 
        } catch (every) { window.alert(jsresModalNotAllowed); return null;}
        var left = (window.screen.width - width) / 2;
        var top = (window.screen.height - height) / 2;
        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;
    }
}

// Funkce pro vyvolani modalniho okna
function ShowModalWindow(url, title, width, height){
    return ShowModalWindowEx(url,title,width,height,false,false,false);
}

// Funkce pro vyvolani obycejneho okna
function ShowWindowEx(url, target, width, height, status, resizable, scroll) {
    var windowArgs;
    if (width && height) {
        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");
    } else windowArgs = width; 
    return ShowWindow(url, target, windowArgs);
}    

// Funkce pro vyvolani obycejneho okna
function ShowWindow(url, target, features, replace) {
    return window.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);
    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 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();   
}

// 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
        document.body.removeChild(div);
        try {div.removeChild(div.popupDiv);} catch(every) {}
        RefreshWindow();
        PreventDefault(e); // pri ukonceni pomoci oncontextmenu na fulldivu, je treba potlacit puvodni menu
    }
}

// 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) width = 220; 
    this.style.width = width+"px";
    if (height != null) 
        this.style.height = height+"px";
    var fulldiv = document.createElement('DIV');
    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; 
    fulldiv.appendChild(this);  
    if (fulldiv.addEventListener) {
        fulldiv.addEventListener("click", __popupDestroy, false);        // FF
        fulldiv.addEventListener("contextmenu", __popupDestroy, false);  // FF
    } else {
        fulldiv.onclick = __popupDestroy;               // IE
        fulldiv.oncontextmenu = __popupDestroy;         // IE
    }    
    this.parentDiv = fulldiv;    // protoze FF nezvlada jednoduche prochazeni DOM, vytvorime si vlastni odkaz
    
    if (this.ItemArray.length > 0) 
        this.innerHTML = CreatePopupMenuHtml(this.ItemArray); 

    // Reseni bugu IE6, kdy prvek <SELECT> (combobox) je vzdy nad ostatnimi prvky bez ohledu na poradi a zindexy a prosvita pres popupmenu
    if (isIE) {
        var bugframe = document.createElement('IFRAME');
        bugframe.style.position = "absolute";
        bugframe.style.left = "0px"; 
        bugframe.style.top = "0px";
        bugframe.style.display = "block";
        bugframe.style.width = "100%"
        bugframe.style.height = "100%";
        bugframe.style.zIndex = "-1"; // neptejte se :) 
        bugframe.style.filter = "mask()";
        this.appendChild(bugframe);  
    }
    
    document.body.appendChild(fulldiv);
    RefreshWindow();
    // zarovnani, aby popup menu neslo pres okraj
    if (this.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";
    }
}

// interni pretizena funkce popup.hide - schova popup
function __popupHide() {
    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 obj = new Object();
    obj.text = text; 
    if(icon && (icon != "")) { 
        obj.icon = icon;
        if ((this.translateTangoIconNames == true) && (typeof(popupImgPre) != 'undefined')) 
            obj.icon = popupImgPre+obj.icon+popupImgExtension;
    } else obj.icon = null; 
    if(run && (run != "")) obj.run = run; 
        else obj.run = null;
    if((enabled == null) || (enabled == true)) obj.enabled = true;
        else obj.enabled = false; 
    this.ItemArray.push(obj);
}

// interni pretizena funkce popup.addSeparator - prida oddelovac do menu 
function __popupAddSeparator() {
    this.addItem("-", null, null, false);
}

// funkce, ktera z predanych ItemArray vytvori vnitrni HTML text contextoveho menu
function CreatePopupMenuHtml(ItemArray) {
    var autoHideStr = "";
    if (ItemArray.parentDiv && ItemArray.parentDiv.autoHide)
        autoHideStr = "document.getElementById('"+ItemArray.parentDiv.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];
        if (item.enabled == true) {
            result += "<TR class='ContextMenuItemNormal' onclick=\""+autoHideStr+item.run+"\" "+
                      "onmouseover='javascript: className = \"ContextMenuItemHighlight\"' "+
                      "onmouseout='javascript: className = \"ContextMenuItemNormal\"'>";
        } else
            result += "<TR class='ContextMenuItemDisabled'>";
        result += "<TD class='ContextMenuIconCell' align='center'>";
        if (item.icon) result += "<IMG style='margin: 0px; padding:0px; border:none;' SRC='"+TranslateUrlForCall(item.icon)+"' />";                  
        result += "</TD>";
        if (item.text == "-") 
            result += "<TD><HR /></TD>";
        else
            result += "<TD class='ContextMenuTextCell'>" + item.text + "</TD>";
        result += "</TR>";                 
    }
    result += "</TBODY></TABLE></DIV>";
    return result; 
}

var popupIdGenerator = 0 ;
// verejna funkce pro vytvoreni platforme nezavisleho popup okna
function createIPopup() {
    var popupDiv = document.createElement('DIV'); 
    popupDiv.style.position = "absolute";
    popupDiv.style.margin = "0px";
    popupDiv.style.padding = "0px";
    popupDiv.id = "PopupDIV"+(popupIdGenerator++);
    popupDiv.show = __popupShow;
    popupDiv.hide = __popupHide;
    popupDiv.popup = __popupPopup;
    popupDiv.addItem = __popupAddItem;
    popupDiv.addSeparator = __popupAddSeparator;
    popupDiv.ItemArray = new Array();
    popupDiv.ItemArray.parentDiv = popupDiv;
    popupDiv.autoHide = true;
    popupDiv.dockToVisibleBorder = true;
    popupDiv.translateTangoIconNames = true;
    return popupDiv;
}
