// Dialog return value  
//var returnValue = null;
var resizeIsActive = false;

var MIN_WINDOW_WIDTH = 150;
var MIN_WINDOW_HEIGHT= 100;
var BLOCKING_MESSAGE = 'Браузер заблокировал показ нового окна, ' + 
                       'для того, чтобы сайт работал правильно, ' +
                       'отключите блокировку всплывающих окон ' +
                       'в настройках вашего браузера.'

// Icons Types
var ICON_NONE        = 0;
var ICON_STOP        = 1;
var ICON_HAND        = 1;
var ICON_ASTERISK    = 2;
var ICON_EXCLAMATION = 3;
var ICON_QUESTION    = 4;

// Button Types
var MB_OK            = 0;
var MB_OKCANCEL      = 1;
var MB_YESNO         = 2;
var MB_YESNOCANCEL   = 3;

// Return Values
var MB_RESULT_CANCEL = 0;
var MB_RESULT_OK     = 1;
var MB_RESULT_YES    = 2;
var MB_RESULT_NO     = 3;

var MB_ICONS = new Array("../images/enabled/32x32/mb_stop.gif",
                         "../images/enabled/32x32/mb_asterisk.gif",
                         "../images/enabled/32x32/mb_exclamation.gif",
                         "../images/enabled/32x32/mb_question.gif");

var tempInitObject = null;
var windowSize = null;
var returnDialogValue = null;
var focusCascade = false;

function messageBox(title, message, preformatted, nowrap, buttonType, iconType, callback, width, height, strict) {
    if (window.showModalDialog && !strict) {
        var param = "resizable:" + false + "; callback:" + callback + "; dialogWidth:" + (width ? width : MIN_WINDOW_WIDTH) + "px; dialogHeight:" + (height ? height : MIN_WINDOW_HEIGHT) + "px;" + "status:0; ";
        var icon = iconType ? ((iconType < ICON_NONE || iconType > ICON_QUESTION) ? ICON_NONE : iconType) : ICON_NONE, iconType;
        var type = buttonType ? ((buttonType < MB_OK || buttonType > MB_YESNOCANCEL) ? MB_OK : buttonType) : MB_OK;
        var dialogArguments = { data         : null,                       
                                width        : width,                      
                                height       : height,                     
                                title        : title,                      
                                strict       : true,                       
                                message      : message,                    
                                preformatted : preformatted,               
                                nowrap       : nowrap,                     
                                type         : type,                 
                                icon         : icon
                               };
        if (callback)
            callback(window.showModalDialog("../general/messagebox.htm", dialogArguments, param));
        else
            window.showModalDialog("../general/messagebox.htm", dialogArguments, param);
    } else
        showWindowStep1({page         : "../general/messagebox.htm",
                         data         : null,
                         resize       : false,
                         callback     : callback,
                         width        : width,
                         height       : height,
                         title        : title,
                         strict       : true,
                         message      : message,
                         preformatted : preformatted,
                         nowrap       : nowrap,
                         buttonType   : buttonType,
                         iconType     : iconType});
}


function showWindow(url, width, height) {
    var width = width ? ((width && width>MIN_WINDOW_WIDTH) ? width : MIN_WINDOW_WIDTH) : null;
    var height = height ? ((height && height>MIN_WINDOW_HEIGHT) ? height : MIN_WINDOW_HEIGHT) : null;
    var wnd = top.open((url ? url : "about:blank"),
                       "_blank",
                       "fullscreen=0," +
                       "channelmode=0," +
                       "toolbar=0," +
                       "location=0," +
                       "directories=0," +
                       "status=0," +
                       "menubar=0," +
                       "scrollbars=0," +
                       "resizable=1," +
                       (width ? ("left=" + (screen.availWidth - width) / 2 + ",") : "") +
                       (height ? ("top=" + (screen.availHeight - height) / 2 + ",") : "") +
                       (width ? ("width=" + width + ",") : "") +
                       (height ? ("height=" + height) : ""));
}


function showDialog(page, data, resize, callback, width, height, strict) {
    if (window.showModalDialog && !strict) {
        var param = "resizable:" + resize + "; callback:" + callback + "; dialogWidth:" + (width ? width : MIN_WINDOW_WIDTH) + "px; dialogHeight:" + (height ? height : MIN_WINDOW_HEIGHT) + "px;" + "status:0; ";
        var dialogArguments = {data : data,
                               callback : callback,
                               width    : width,
                               height   : height,
                               strict   : strict,
                               top      : top,
                               window   : top
        };
        if (callback)
            callback(window.showModalDialog(page, dialogArguments, param));
        else
            window.showModalDialog(page, dialogArguments, param);
    } else 
        showWindowStep1({page     : page,
                         data     : data,
                         resize   : resize,
                         callback : callback,
                         strict   : strict,
                         width    : width,
                         height   : height});
}    
     
function showWindowStep1(params) {
    var iframe = top.document.createElement("iframe");
    iframe.id = "$$WRAPPER$$"
    iframe.src = "../general/window_wrapper.htm";
    iframe.scrolling = "no";
    iframe.frameBorder = "no"
    iframe.style.top = "0px";
    iframe.style.left = "0px";
    iframe.style.position = "absolute";
    iframe.style.width = "100%";
    iframe.style.height = "100%";
    iframe.style.filter = "alpha(opacity=0) filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0)";
    iframe.style.opacity = "0.0";
    iframe.style.MozOpacity = "0.0";
    iframe.style.zIndex = "100";
    top.document.body.appendChild(iframe);

    var width = (params.width && params.width>MIN_WINDOW_WIDTH) ? params.width : MIN_WINDOW_WIDTH;
    var height = (params.height && params.height>MIN_WINDOW_HEIGHT) ? params.height : MIN_WINDOW_HEIGHT;
    
    top.onfocusOldHandler = top.onfocus;
    if (top.dialogArguments==null)
        top.onunloadOldHandler = top.onunload;

    var wnd = top.open(params.page,
                       "_blank",
                       "fullscreen=0," +
                       "channelmode=0," +
                       "toolbar=0," +
                       "location=0," +
                       "directories=0," +
                       "status=0," +
                       "menubar=0," +
                       "scrollbars=0," +
                       "resizable=" + (params.resize ? 1 : 0) + "," +
                       "left=" + (screen.availWidth - width) / 2 + "," +
                       "top=" + (screen.availHeight - height) / 2 + "," +
                       "width=" + width + "," +
                       "height=" + height);

    if (wnd==null || (wnd!=null && wnd.closed)) {
        alert(BLOCKING_MESSAGE);
        if (top.document.getElementById("$$WRAPPER$$"))
            top.document.body.removeChild(top.document.getElementById("$$WRAPPER$$"));
        if (top.document)
            top.document.body.focus();
        return;
    }

    tempInitObject = {data         : params.data,
                      callback     : params.callback,
                      strict       : params.strict,
                      width        : width,
                      height       : height,
                      title        : params.title,
                      message      : params.message,
                      preformatted : params.preformatted,
                      nowrap       : params.nowrap,
                      buttonType   : params.buttonType,
                      iconType     : params.iconType,
                      top          : (top.dialogArguments ? top.dialogArguments.top : top),
                      wnd          : wnd};
    waitForStep2();
}

function waitForStep2() {
    if (!tempInitObject || !tempInitObject.wnd)
        return;
    var wnd = tempInitObject.wnd;
    var status = true;
    try {
        status = wnd.document.body==null;
    } catch (error) {}
    if (status)
        setTimeout("waitForStep2()",1);
    else showWindowStep2();
}

function showWindowStep2() {
    var wnd = tempInitObject.wnd;
    wnd.resizeTo(tempInitObject.width, tempInitObject.height);

    wnd.dialogArguments = {data     : tempInitObject.data,
                           title    : tempInitObject.title,
                           message  : tempInitObject.message ? (tempInitObject.preformatted ? tempInitObject.message : ('<p class="text">' + tempInitObject.message + '</p>')) : "&nbsp;",
                           nowrap   : tempInitObject.nowrap ? tempInitObject.nowrap : false,
                           type     : tempInitObject.buttonType ? ((tempInitObject.buttonType < MB_OK || tempInitObject.buttonType > MB_YESNOCANCEL) ? MB_OK : tempInitObject.buttonType) : MB_OK,
                           icon     : tempInitObject.iconType ? ((tempInitObject.iconType < ICON_NONE || tempInitObject.iconType > ICON_QUESTION) ? ICON_NONE : tempInitObject.iconType) : ICON_NONE,
                           callback : tempInitObject.callback,
                           strict   : tempInitObject.strict,
                           width    : tempInitObject.width,
                           height   : tempInitObject.height,
                           top      : tempInitObject.top,
                           window   : top};

    top.focusedWindow = wnd;
    top.childWindow = wnd;
    
    top.onfocus = window_onfocusCascadeHandler;
    
    if (top.dialogArguments==null)
        top.onunload = window_onunloadHandler;

    var wnd = tempInitObject.wnd;

    top.frames[top.frames.length-1].focusedWindow = wnd; 
    top.frames[top.frames.length-1].childWindow = wnd; 

    var iframe = top.document.getElementById("$$WRAPPER$$");

    try {
        iframe.onfocus = window_onfocusCascadeHandler;
        iframe.onmouseover = window_onfocusHandler;
        iframe.onmousemove = window_onfocusHandler;
        iframe.onclick = window_onfocusCascadeHandler;
    } catch (e) {}

    tempInitObject = null;
}

function arrangeButtons(buttons) {
    var maxWidth = 64;
    for (var i=0; i<buttons.length; i++)
        if (buttons[i]) {
           var button = buttons[i];
           if (button.tagName=="TD")
              while (button.tagName!="TABLE")
                     button = button.parentNode;
           maxWidth = Math.max(maxWidth, getWidth(button) + 5);
        }
    for (var i=0; i<buttons.length; i++) {
        if (buttons[i]) buttons[i].style.width = maxWidth;
    }
}

function arrangeWindow(object, noCentered, width, height) {

    if (object) {
        width = (width && width>MIN_WINDOW_WIDTH) ? width : MIN_WINDOW_WIDTH;
        height = (height && height>MIN_WINDOW_HEIGHT) ? height : MIN_WINDOW_HEIGHT;
        
        var size = getBodySize();
        var dx = width - size.width;
        var dy = height - size.height;
        var rect = getClientRect(object);

        if (dx<0) 
            rect.width = rect.width - dx;

        if (dy<0) 
            rect.height = rect.height - dy;

        try {
            top.moveTo(noCentered ? 0 : (screen.availWidth - rect.width) / 2, 
                       noCentered ? 0 : (screen.availHeight - rect.height) / 2);
            top.resizeTo(rect.width + dx, rect.height + dy);
        } catch (e) {}
        
        if (window.showModalDialog) {
            top.dialogHeight = (rect.height + dy) + "px";
            top.dialogWidth = (rect.width + dx) + "px";
            top.dialogTop = (screen.availHeight - rect.height)/2;
            top.dialogLeft = (screen.availWidth - rect.width)/2;
        }
        
        windowSize = {width:rect.width + dx, height:rect.height + dy, dx: dx, dy: dy,
                      toString: function () { return "width: " + this.width + "\n" + "height: " + this.height + "\n" +
                                                     "dx: " + this.dx + "\n" + "dy: " + this.dy} };
    }
}

// catch if ESC key pressed and then close the Dialog
function document_onkeypressHandler(event) { 
    if (window==top ||
        top.document.onkeypress == top.document_onkeypressHandler) {
        event = window.event ? window.event : event;
        var keyCode = event.keyCode ? event.keyCode : event.which;
        if (keyCode==27) {
            if (window.skipButton)
                skipButton.onclick();
            else {
                if (!top.returnValue)
                    top.returnValue = top.changed;
                top.close();
            }
        }
    }
}

function removeWrappedFrame(object) {
    try {
        if (tempInitObject==null && object.document.getElementById("$$WRAPPER$$"))
            object.document.body.removeChild(object.document.getElementById("$$WRAPPER$$"));
    } catch(e) {}
}

// set focus to the top level Dialog
function window_onfocusHandler(event) {
    try {
        if (!top.focusedWindow) {
            removeWrappedFrame(top);
            return;
        }
    } catch(e) {
        try {
            removeWrappedFrame(top);
        } catch(e) {};
        return;
    }
    checkWindowsChain();
    try {
        if (top.focusedWindow)
            top.focusedWindow.focus();
        else { 
            top.onfocus = top.onfocusOldHandler;
            top.onfocusOldHandler = null;
        }
    } catch (error) { }
}

// set focus to the top level Dialog
function window_onfocusCascadeHandler(event) {
    try {
        if (!top.focusedWindow) {
            removeWrappedFrame(top);
            return;
        }
    } catch(e) {
        try {
            removeWrappedFrame(top);
        } catch(e) {};
        return;
    }
    checkWindowsChain();
    try {
        if (top.focusedWindow && !focusCascade) {
            var wnd = top.childWindow;
            focusCascade = true;
            while (wnd != null) {
                wnd.focus();
                wnd = wnd.childWindow;
            }                         
        } else {
            top.onfocus = top.onfocusOldHandler;
            top.onfocusOldHandler = null;
            focusCascade = false;
        }
    } catch (error) {}
}

//some browsers don't fire onunload event by closing window using X-box
//this function corrects such situations
function checkWindowsChain(event) {
    try {
        //remove all windows after gap at the place of closed window
        var wnd = (top.focusedWindow && !top.focusedWindow.closed) ? top.focusedWindow : top;
        while (wnd.dialogArguments!=null && !wnd.dialogArguments.window.closed)
            wnd = wnd.dialogArguments.window;

        if (wnd.dialogArguments!=null && wnd.dialogArguments.window.closed)
           wnd.close();
        else
        if (top.focusedWindow && !top.focusedWindow.closed)
            return;

        //prepare last binded window for being last in the chain
        //remove hidden frame

        wnd = top.dialogArguments ? top.dialogArguments.top : top;
        while (wnd.childWindow != null) {
            if (wnd.childWindow.closed) {
                wnd.childWindow = null;
                wnd.focusedWindow = null;
                if (wnd.document.getElementById("$$WRAPPER$$"))
                    wnd.document.body.removeChild(wnd.document.getElementById("$$WRAPPER$$"));
            }
            wnd = wnd.childWindow;
        }
        //set last window as focused window
        var focused = wnd;
        wnd = top.dialogArguments ? top.dialogArguments.top : top;
        while (wnd.childWindow != null) {
            wnd.focusedWindow = focused;
            wnd = wnd.childWindow;
        }

        focused.document.body.focus();
    } catch (error) {}

}

// close all Dialogs in case of reloading main window
function window_onunloadHandler(event) {
    if (top.focusedWindow) {
        try {
            var last = top.focusedWindow;
            var previous = (last && last.dialogArguments) ? last.dialogArguments.window : null;
            while (last!=null) {
                if (last.dialogArguments)
                    last.close();
                last = previous;
                previous = (previous && previous.dialogArguments) ? previous.dialogArguments.window : null;
            }
        } catch (error) {}
    }
}

// reassign the top level Dialog to the newly created one and correct its size
function dialog_onloadHandler(event) {
    if (top.dialogArguments) {
        document.onkeypress = document_onkeypressHandler;
        top.onmouseover = checkWindowsChain;
        if (window.outerHeight) top.onresize = dialog_onresizeHandler;
        try {
            var wnd = top.dialogArguments.window;
            while (wnd!=null) {
                wnd.focusedWindow = top;
                wnd = wnd.dialogArguments ? wnd.dialogArguments.window : null;
            }
        } catch (error) {}
        arrangeWindow(document.getElementById("MainTable"), null, dialogArguments.width, dialogArguments.height);
     } else
        top.close();
}

// reassing the top level Dialog to the previous in hierarchy one and set its focus
function dialog_onunloadHandler(event) {
    if (!top.returnValue)
        top.returnValue = top.changed;
    if (top.dialogArguments)
        try {
            var wnd = top.childWindow;
            var win = wnd;
            while (wnd != null) {
                win = wnd;
                wnd.close();
                wnd = win.childWindow;
            }
            top.dialogArguments.window.focusedWindow = null;
            top.dialogArguments.window.childWindow = null;
            var last = top.dialogArguments.window;
            if (last!=null) {
                try {
                    var wnd = last.dialogArguments ? last.dialogArguments.window : null;
                    while (wnd!=null) {
                        wnd.focusedWindow = last;
                        wnd = wnd.dialogArguments ? wnd.dialogArguments.window : null;
                    }
                } catch (error) {}
                if (last.document.getElementById("$$WRAPPER$$"))
                    last.document.body.removeChild(last.document.getElementById("$$WRAPPER$$"));
                if (last.document)
                    last.document.body.focus();
            }
            if (top.dialogArguments.callback && !(window.showModalDialog && !top.dialogArguments.strict)) {
                top.dialogArguments.callback(window.returnValue);
            } else {
//                top.returnDialogValue = returnValue;
            }
        } catch (error) {}
}


function dialog_onresizeHandler(event) {
    if (!resizeIsActive) {
        resizeIsActive = true;
        
        var dx = top.outerWidth - top.innerWidth;
        var dy = top.outerHeight - top.innerHeight;
        if (windowSize==null || windowSize.dx<dx || windowSize.dy<dy) {
            rect = getClientRect(document.getElementById("MainTable"));
            top.resizeTo(rect.width + dx, rect.height + dy);
            top.moveTo((screen.availWidth - rect.width - dx) / 2, 
                       (screen.availHeight - rect.height - dy) / 2);
            windowSize = {width:rect.width + dx, height:rect.height + dy, dx: dx, dy: dy,
                          toString: function () { return "width: " + this.width + "\n" + "height: " + this.height + "\n" +
                                                         "dx: " + this.dx + "\n" + "dy: " + this.dy} };
        }
        resizeIsActive = false;
    }
}

