var Famark = Famark || {};
Famark._winRecycleBin = [];
Famark._pressOkToClose = 'Press Ok to close or Cancel to remain open.';
Famark._winMinTitle = 'minimize (ctrl + space)';
Famark._winMaxTitle = 'maximize (ctrl + space)';
Famark._winOutTitle = 'open out';
Famark._winCloseTitle = 'close (esc)';
Famark.showDialog = function (url) {
    return Famark.showWindow(url, 'Dialog', 30);
};
Famark.showWindow = function (url, type, headerSpace, ddSpace) {
    type = type || 'Form';
    var div = Famark._winRecycleBin.length > 0 ? Famark._winRecycleBin.pop() : document.createElement('div');
    div.className = 'divWin';
    div.style.position = 'absolute';
    div.maximized = true;
    if (type == 'Dialog') {
        var fs = Famark.appendFullScreen(12);
        fs.style.zIndex = 12;
        div.style.zIndex = 14;
        div.rePosition = Famark.positionDialog;
        div.headerSpace = headerSpace || 60;
    }
    else {
        div.style.zIndex = 10;
        div.rePosition = Famark.positionForm;
        div.headerSpace = headerSpace || 60;
        div.ddSpace = ddSpace || 100;
    }

    document.body.appendChild(div);

    var head = document.createElement('div');
    head.className = 'divWinHead';
    head.tabIndex = -1;
    div.appendChild(head);

    var divButtons = document.createElement('div');
    divButtons.className = 'divWinButtons';
    head.appendChild(divButtons);

    var title = document.createElement('div');
    title.className = 'divWinTitle';
    head.appendChild(title);

    var close = document.createElement('button');
    close.className = 'btnWinClose';
    close.value = 'x';
    close.title = Famark._winCloseTitle;
    close.innerHTML = "<svg class='icon'><use href='Attachment/all-icons.svg#win-close'></use></svg>";
    divButtons.appendChild(close);

    var out = null, min = null;
    if (type == 'Form') {
        out = document.createElement('button');
        out.className = 'btnWinOut';
        out.value = '{}';
        out.title = Famark._winOutTitle;
        out.innerHTML = "<svg class='icon'><use href='Attachment/all-icons.svg#win-out'></use></svg>";
        divButtons.appendChild(out);

        min = document.createElement('button');
        min.className = 'btnWinMin';
        min.value = '-';
        min.title = Famark._winMinTitle;
        min.innerHTML = "<svg class='icon'><use href='Attachment/all-icons.svg#win-min'></use></svg>";
        divButtons.appendChild(min);
    }

    var iframe = document.createElement('iframe');
    iframe.className = 'iframeWin';
    iframe.scrolling = 'no';
    iframe.frameBorder = '0';

    div.closeWindow = function () {
        if (Famark.checkAndClose(iframe, div))
            Famark.removeFullScreen();
    };

    div.setTitle = function (val) {
        window.setTimeout(function () { title.innerHTML = val.replace(/&/g, '&amp;').replace(/\>/g, '&gt;').replace(/\</g, '&lt;'); }, 200);
    };

    div.setContentHeight = function (val) {
        div.defaultContentHeight = val;
        window.setTimeout(function () {
            iframe.contentHeight = val;
            div.rePosition();
        }, 200);
    };

    close.onmousedown = function (e) { e.stopPropagation() };
    close.onclick = function () {
        if (Famark.checkAndClose(iframe, div))
            Famark.removeFullScreen();
    };
    if (out != null) {
        out.onmousedown = function (e) { e.stopPropagation() };
        out.onclick = function () {
            var formWin = window.open(url, '_blank', 'width=' + div.offsetWidth + 'px,height=' + div.offsetHeight + 'px,resizable=1,location=1,menubar=1,toolbar=1');
            formWin.focus();
            if (Famark.checkAndClose(iframe, div))
                Famark.removeFullScreen();
        };
    }

    if (min != null) {
        min.onmousedown = function (e) { e.stopPropagation() };
        min.onclick = function () {
            if (div.maximized) {
                iframe.style.display = 'none';
                div.maxHeight = div.offsetHeight;
                div.maxWidth = div.offsetWidth;
                div.style.height = '24px';
                if (div.offsetWidth > 280)
                    div.style.width = '280px';
                min.value = '[]';
                min.className = 'btnWinMax';
                min.title = Famark._winMaxTitle;
                min.innerHTML = "<svg class='icon'><use href='Attachment/all-icons.svg#win-max'></use></svg>";
                div.maximized = false;
                var forms = Famark.getElementsByClassName('divWin', 'div');
                var minCount = 0;
                for (var i = 0; i < forms.length; i++) {
                    if (!forms[i].maximized)
                        minCount++;
                }
                if (minCount > 0) {
                    var newLeft = div.offsetLeft + (minCount * 32);
                    var newTop = div.offsetTop + (minCount * 32);
                    Famark.setWinLeftTop(div, newLeft, newTop);
                }
            }
            else {
                iframe.style.display = '';
                div.style.height = div.maxHeight + 'px';
                div.style.width = div.maxWidth + 'px';
                min.value = '-';
                min.className = 'btnWinMin';
                min.title = Famark._winMinTitle;
                min.innerHTML = "<svg class='icon'><use href='Attachment/all-icons.svg#win-min'></use></svg>";
                div.maximized = true;
                div.rePosition();
            }
        };
    }

    var shortKey = function (e) {
        e = e || window.event;
        if (e.keyCode == 27)
            close.click();
        else if (e.ctrlKey && e.keyCode == 32)
            min.click();
    };

    div.onkeyup = shortKey;

    title.innerHTML = '<img src="Attachment/loading.gif" alt="wait" style="width:32px;height:22px;" />';
    iframe.src = 'about:blank';
    div.appendChild(iframe);
    div.rePosition();

    Famark.addHandler(iframe, 'load', function () {
        try {
            iframe.style.visibility = 'visible';
            var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
            iframeDoc.onTitleChange = function () {
                var titles = iframeDoc.getElementsByTagName('title');
                if (titles != null && titles.length > 0)
                    title.innerHTML = titles[0].innerHTML;
            };
            iframeDoc.onTitleChange();
            Famark.addHandler(iframeDoc, 'keyup', shortKey);
        }
        catch (e) { title.innerHTML = '~'; }
        finally {
            iframe.contentHeight = null;
            iframe.style.height = null;
            div.style.height = null;
            div.rePosition();
            head.focus();
        }
    });

    window.setTimeout(function () {
        iframe.style.visibility = 'hidden';
        var iframeWin = iframe.contentWindow ? iframe.contentWindow : iframe.contentDocument.defaultView;
        iframeWin.location.replace(url);
    }, 2);

    head.onmousedown = function (e) {
        e = e || window.event;
        var target = e.target || e.srcElement;
        if (target.nodeName == 'INPUT')
            return;

        head.initX = e.clientX - div.offsetLeft;
        head.initY = e.clientY - div.offsetTop;

        var screen = Famark.appendFullScreen();

        screen.style.zIndex = 20;

        screen.onmouseup = function () {
            screen.style.zIndex = screen.lastZIndex;
            Famark.clearSelection();
        };
        screen.onmousemove = function (em) {
            em = em || window.event;
            var newLeft = em.clientX - head.initX;
            var newTop = em.clientY - head.initY;
            window.setTimeout(function () {
                Famark.setWinLeftTop(div, newLeft, newTop);
            }, 10);
        };
    };

    var resizeTimeout = null;
    Famark.addHandler(window, 'resize', function () {
        if (resizeTimeout)
            window.clearTimeout(resizeTimeout);
        resizeTimeout = window.setTimeout(function () { div.rePosition(); resizeTimeout = null; }, 100);
    });

    return div;
};
Famark.checkAndClose = function (iframe, div) {
    try {
        var iframeWin = iframe.contentWindow ? iframe.contentWindow : iframe.contentDocument.defaultView;
        if (iframeWin.Famark !== undefined && iframeWin.Famark._isWorking && iframeWin.Famark._preventUnloadMessage) {
            if (!confirm(iframeWin.Famark._preventUnloadMessage + '\n' + Famark._pressOkToClose))
                return false;
        }
    } catch (e) { }
    if (div.closing !== undefined && div.closing != null) {
        div.closing();
        div.closing = null;
    }
    document.body.removeChild(div);
    div.innerHTML = '';
    div.style.height = null;
    div.style.top = null;
    div.defaultContentHeight = null;
    if (div.opener != null) {
        div.opener.focus();
        div.opener = null;
    }
    Famark._winRecycleBin.push(div);
    return true;
};
Famark.appendFullScreen = function (lastZIndex) {

    var screen = document.getElementById('fullScreen');
    if (screen != null) {
        if (lastZIndex != null) {
            screen.onmousemove = null;
            screen.lastZIndex = lastZIndex;
        }
        return screen;
    }
    screen = document.createElement('div');
    screen.id = 'fullScreen';
    screen.style.position = 'absolute';
    try {
        screen.style.backgroundColor = 'rgba(0,0,0,0.1)';
    } catch (e) { }
    screen.style.left = 0;
    screen.style.top = 0;
    screen.style.width = '100%';
    screen.style.height = '100%';
    screen.style.cursor = 'move';
    screen.lastZIndex = lastZIndex || -20;
    document.body.appendChild(screen);

    return screen;
};
Famark.removeFullScreen = function () {
    var screen = document.getElementById('fullScreen');
    if (screen != null)
        document.body.removeChild(screen);
};
Famark.closeWindow = function (frameWin) {
    var frameNodes = document.getElementsByTagName("iframe");
    var frames = window.frames;
    for (var i = 0; i < frames.length; i++) {
        if (frames[i] == frameWin) {
            Famark.checkAndClose(frameNodes[i], frameNodes[i].parentNode);
            Famark.removeFullScreen();
            return;
        }
    }
    if (frameWin == window.top)
        frameWin.close();
};
Famark.getWindow = function (frameWin) {
    var frameNodes = document.getElementsByTagName("iframe");
    var frames = window.frames;
    for (var i = 0; i < frames.length; i++) {
        if (frames[i] == frameWin)
            return frameNodes[i].parentNode;
    }
    return null;
};
Famark.positionDialog = function () {
    var body = this.parentNode;
    if (body == null)
        return;
    this.style.width = '240px';

    var iframe = this.getElementsByTagName('IFRAME')[0];
    iframe.style.width = '236px';

    var newHeight = body.clientHeight - 10;

    var contentHeight = Famark.frameContentHeight(iframe);

    if (contentHeight < (newHeight - this.headerSpace))
        newHeight = contentHeight + this.headerSpace;

    this.style.height = (newHeight - 4) + 'px';
    iframe.style.height = (newHeight - this.headerSpace) + 'px';

    this.style.left = ((body.clientWidth - this.offsetWidth) / 2) + 'px';
    this.style.top = ((body.clientHeight - this.offsetHeight) / 2) + 'px';
};
Famark.positionForm = function () {

    var body = this.parentNode;
    if (body == null)
        return;
    if (this.maximized) {
        var newWidth = 666;
        if (body.clientWidth > 666)
            this.style.width = '666px';
        else {
            newWidth = body.clientWidth - 10;
            this.style.width = newWidth + 'px';
        }

        var iframe = this.getElementsByTagName('IFRAME')[0];
        iframe.style.width = (newWidth - 4) + 'px';

        var newHeight = body.clientHeight - 10;

        var contentHeight = Famark.frameContentHeight(iframe);

        if (contentHeight < (newHeight - this.headerSpace - this.ddSpace))
            newHeight = contentHeight + this.headerSpace + this.ddSpace;

        this.style.height = (newHeight - 4) + 'px';
        iframe.style.height = (newHeight - this.headerSpace) + 'px';

        this.style.left = ((body.clientWidth - this.offsetWidth) / 2) + 'px';
        this.style.top = ((body.clientHeight - this.offsetHeight) / 2) + 'px';
    }
    else {
        if (body.clientWidth > 666)
            this.maxWidth = 666;
        else
            this.maxWidth = (body.clientWidth * 90) / 100;
        this.maxHeight = (body.clientHeight * 90) / 100;

        this.style.left = ((body.clientWidth - this.maxWidth) / 2) + 'px';
        this.style.top = ((body.clientHeight - this.maxHeight) / 2) + 'px';
    }
};
Famark.frameContentHeight = function (iframe) {

    if (iframe.contentHeight !== undefined && iframe.contentHeight != null)
        return iframe.contentHeight;

    try {
        var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
        var body = iframeDoc.body, html = iframeDoc.documentElement;
        iframe.contentHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
    } catch(e) {
        iframe.contentHeight = iframe.parentNode.defaultContentHeight || 100;
    }

    return iframe.contentHeight;
};

Famark.addHandler = function (el, ev, fn) {
    if (el.addEventListener)
        el.addEventListener(ev, fn, false);
    else if (el.attachEvent)
        el.attachEvent('on' + ev, fn);
    else
        el[ev] = fn;
};

Famark.setWinLeftTop = function(div, newLeft, newTop) {
    if (newLeft <= 0)
        newLeft = 0;
    else if (newLeft >= (document.body.clientWidth - div.offsetWidth))
        newLeft = document.body.clientWidth - div.offsetWidth;

    if (newTop <= 0)
        newTop = 0;
    else if (newTop >= (document.body.clientHeight - div.offsetHeight))
        newTop = document.body.clientHeight - div.offsetHeight;

    div.style.left = newLeft + 'px';
    div.style.top = newTop + 'px';
};

Famark.clearSelection = function () {
    if (document.selection && document.selection.empty) {
        try {
            document.selection.empty();
        } catch (e) { }
    } else if (window.getSelection) {
        var sel = window.getSelection();
        sel.removeAllRanges();
    }
};