var Famark = Famark || {};
var Resources = Resources || {};

Famark.pageLoad = function () {
    Famark._defaultUrls = {};

    Famark._nav = document.getElementById('nav');
    Famark._area = document.getElementById('area');
    Famark._main = document.getElementById('main');
    Famark._pane = document.getElementById('pane');

    Famark._btnMenuTitle = Resources.TooltipMenu + ' (ctrl + [)';
    Famark._btnSettingsTitle = Resources.TooltipSettings + ' (ctrl + 0)';
    Famark._btnPaneCollapseTitle = Resources.TooltipCollapsePanel + ' (ctrl + ])';
    Famark._btnPaneExpandTitle = Resources.TooltipExpandPanel + ' (ctrl + ])';

    var lnks = Famark._nav.getElementsByTagName('span');

    for (var i = 0; i < lnks.length; i++) {
        if (lnks[i].getAttribute('data-expanded') != 'True')
            Famark.toggleSub(lnks[i]);
    }

    var chkReCache = document.getElementById('chkReCache');
    var dom = document.getElementById('domain');
    var domName = dom.getAttribute('data-name');
    if (chkReCache != null) {
        chkReCache.checked = (Famark.getCookie(domName + '#ReCache') == '1');
        chkReCache.onclick = function () {
            if (chkReCache.checked)
                Famark.setCookieByPath(domName + '#ReCache', '1', '/');
            else
                Famark.removeCookieByPath(domName + '#ReCache', '/');
        };
    }

    var settings = document.getElementById('settings');

    var btnSignOut = document.getElementById('btnSignOut');
    if (btnSignOut != null) {
        btnSignOut.onclick = function () {
            domName = domName.toLowerCase();
            Famark.removeCookieByPath(domName + '.sessionId', '/');
            Famark.removeCookieByPath(domName + '.user', '/');
            hideSettings();
            window.location.reload(true);
        };
    }

    var btnPersonalSettings = document.getElementById('btnPersonalSettings');
    if (btnPersonalSettings != null) {
        btnPersonalSettings.onclick = function () {
            hideSettings();
            window.top.Famark.showWindow('Plot.ashx?data-entity=@user');
        };
    }

    var btnDomainSettings = document.getElementById('btnDomainSettings');
    if (btnDomainSettings != null) {
        btnDomainSettings.onclick = function () {
            hideSettings();
            window.top.Famark.showWindow('Plot.ashx?data-entity=@domain');
        };
    }

    var btnChangeSite = document.getElementById('btnChangeSite');
    if (btnChangeSite != null) {
        btnChangeSite.onclick = function () {
            hideSettings();
            window.top.Famark.showDialog('Plot.ashx?data-entity=@site');
        };
    }

    var btnSettings = document.getElementById('btnSettings');
    if (btnSettings != null) {
        btnSettings.title = Famark._btnSettingsTitle;
        btnSettings.onclick = function () {
            if (settings.style.display == 'none') {
                settings.style.display = 'block';
                btnSettings.innerHTML = "<svg class='icon'><use href='Attachment/all-icons.svg#close'></use></svg>";
            } else {
                hideSettings();
            }
        };
    }

    var hideSettings = function () {
        settings.style.display = 'none';
        btnSettings.innerHTML = "<svg class='icon'><use href='Attachment/all-icons.svg#gear'></use></svg>";
    };

    var btnMenu = document.getElementById('btnMenu');
    if (btnMenu != null) {
        btnMenu.title = Famark._btnMenuTitle;
        btnMenu.onclick = function () {
            var width = 0;
            if (Famark._nav.offsetWidth < 40) {
                var width = document.body.clientWidth;
                width = (width > 768) ? 240 : (width > 384 ? 160 : width);
            }

            Famark.setNavWidth(width);
            Famark.setNavState();

            if (Famark._main != null)
                Famark.resizeEnd(Famark._main);
            if (Famark._pane != null)
                Famark.resizeEnd(Famark._pane);
        };
    }

    Famark.loadDefault();
    Famark.addHandler(document, 'keyup', Famark.docKeyUp);
    Famark.addHandler(window, 'resize', Famark.screenLoad);
    Famark.screenLoad();
};
Famark._resizeTimeout = null;
Famark.screenLoad = function () {
    if (Famark._resizeTimeout)
        window.clearTimeout(Famark._resizeTimeout);
    Famark._resizeTimeout = window.setTimeout(function () {
        var width = document.body.clientWidth;
        var height = document.body.clientHeight;
        var headerHeight = Famark._nav.offsetTop;
        Famark._nav.style.height = (height - headerHeight) + 'px';
        Famark._area.style.height = (height - headerHeight) + 'px';
        var showMain = true, showPane = false;

        if (width > 768) {
            Famark._nav.style.width = '240px';
            Famark._area.style.width = (width - Famark._nav.offsetWidth - 1) + 'px';
            showPane = (Famark._defaultUrls['pane'] != 'about:hidden');
        } else if (width > 384 && width <= 768) {
            Famark._nav.style.width = '160px';
            Famark._area.style.width = (width - Famark._nav.offsetWidth - 1) + 'px';
        } else {
            Famark._nav.style.width = '100%';
            Famark._area.style.width = '0';
            showMain = false;
        }

        if (showPane) {
            Famark._main = Famark.addElement(Famark._main, 'main', '60%');
            Famark._pane = Famark.addElement(Famark._pane, 'pane', '40%');
            Famark.setNavTarget('iframe-main', function () { Famark._main.firstChild.style.visibility = 'hidden'; });
        } else if (showMain) {
            Famark._main = Famark.addElement(Famark._main, 'main', '100%');
            Famark._pane = Famark.removeElement(Famark._pane, 'pane');
            Famark.setNavTarget('iframe-main', function () { Famark._main.firstChild.style.visibility = 'hidden'; });
        } else {
            Famark._main = Famark.removeElement(Famark._main, 'main');
            Famark._pane = Famark.removeElement(Famark._pane, 'pane');
            document.getElementById('btnMenu').onclick = null;
            Famark.setNavTarget('_self', null);
        }

        Famark.setCookieByPath('IsMobile', (width <= 480 ? '1' : '0'), '/');
        Famark.setPaneToggle(showPane);
        Famark._resizeTimeout = null;
    }, 100);
};
Famark.setPaneToggle = function (isTrue) {
    var btnPane = document.getElementById('btnPane');
    if (!isTrue) {
        if (btnPane != null)
            Famark._area.removeChild(btnPane);
        return;
    }
    if (btnPane != null) {
        btnPane.className = 'expanded';
        btnPane.innerHTML = "<svg class='icon'><use href='Attachment/all-icons.svg#pane-right-arrow'></use></svg>";
        btnPane.title = Famark._btnPaneCollapseTitle;
        return;
    }
    btnPane = document.createElement('button');
    btnPane.id = 'btnPane';
    btnPane.className = 'expanded';
    btnPane.innerHTML = "<svg class='icon'><use href='Attachment/all-icons.svg#pane-right-arrow'></use></svg>";
    btnPane.title = Famark._btnPaneCollapseTitle;
    Famark._area.appendChild(btnPane);
    btnPane.onclick = function () {
        if (Famark._pane.offsetWidth < 40) {
            Famark._main.style.width = '60%';
            Famark._pane.style.width = '40%';
        } else {
            Famark._pane.style.width = '6px';
            Famark._main.style.width = (Famark._area.offsetWidth - 6) + 'px';
        }
        Famark.resizeEnd(Famark._main);
        Famark.resizeEnd(Famark._pane);
        Famark.setPaneState();
    };
};
Famark.setPaneState = function () {
    var isCollapsed = (Famark._pane.offsetWidth < 40);
    Famark._pane.firstChild.style.visibility = isCollapsed ? 'hidden' : 'visible';
    var btnPane = document.getElementById('btnPane');
    if (btnPane != null) {
        if (isCollapsed) {
            btnPane.className = 'collapsed';
            btnPane.innerHTML = "<svg class='icon'><use href='Attachment/all-icons.svg#pane-left-arrow'></use></svg>";
            btnPane.title = Famark._btnPaneExpandTitle;
        } else {
            btnPane.className = 'expanded';
            btnPane.innerHTML = "<svg class='icon'><use href='Attachment/all-icons.svg#pane-right-arrow'></use></svg>";
            btnPane.title = Famark._btnPaneCollapseTitle;
        }
    }
};
Famark.relatedViewShifted = function (url, label) {
    if (Famark._main != null) {
        function setTitleHandler() {
            Famark.removeMainLoading();
            var iframe = Famark._main.firstChild;
            try {
                var iframeWin = iframe.contentWindow || iframe.contentDocument.defaultView;

                Famark.addHandler(iframeWin, 'unload', Famark.setMainLoading);

                if (Famark._recordTitle !== undefined && Famark._recordTitle != null)
                    label = '<b>' + Famark._recordTitle + '</b><i>' + label + '</i>';

                if (iframeWin.Famark !== undefined && iframeWin.Famark.showFilterLabel != null)
                    iframeWin.Famark.showFilterLabel(label);
            }
            catch (e) { }
            finally {
                if (iframe.removeEventListener)
                    iframe.removeEventListener('load', setTitleHandler, false);
                if (iframe.detachEvent)
                    iframe.detachEvent('onload', setTitleHandler);
            }
        }

        Famark.addHandler(Famark._main.firstChild, 'load', setTitleHandler);
        Famark._main.firstChild.style.visibility = 'hidden';
        Famark._main.firstChild.src = url;
    }
};
Famark.setMainLoading = function () { Famark._main.className += ' loading'; };
Famark.removeMainLoading = function () {
    var mainClass = Famark._main.className;
    var lPos = mainClass.indexOf(' loading');
    if (lPos > -1)
        Famark._main.className = mainClass.substr(0, lPos);
};
Famark.viewRecordSelected = function (entity, rid, title) {
    if (Famark._pane != null) {
        var iframe = Famark._pane.firstChild;
        try {
            var iframeWin = iframe.contentWindow ? iframe.contentWindow : iframe.contentDocument.defaultView;
            if (iframeWin.Famark !== undefined && iframeWin.Famark._isWorking)
                return;
        } catch (e) { }
        Famark._recordTitle = title;
        iframe.style.visibility = 'hidden';
        iframe.src = 'Prop.ashx?entity=' + entity + '&rid=' + rid;
    }
};
Famark.viewRecordPicked = function (entity, rid, title) {
    var frames = window.frames;
    for (var i = 0; i < frames.length; i++) {
        if (frames[i].Famark != null && frames[i].Famark.viewRecordPicked != null)
            frames[i].Famark.viewRecordPicked(entity, rid, title);
    }
};
Famark.formRecordCreated = function (entity, rid, data) {
    var frames = window.frames;
    for (var i = 0; i < frames.length; i++) {
        if (frames[i].Famark != null && frames[i].Famark.formRecordCreated != null)
            frames[i].Famark.formRecordCreated(entity, rid, data);
    }
};
Famark.formRecordUpdated = function (entity, rid, data) {
    var frames = window.frames;
    for (var i = 0; i < frames.length; i++) {
        if (frames[i].Famark != null && frames[i].Famark.formRecordUpdated != null)
            frames[i].Famark.formRecordUpdated(entity, rid, data);
    }
};
Famark.addElement = function (el, name, width) {

    if (el == null) {
        el = document.createElement('div');
        el.id = name;
        el.className = name;
        Famark._area.appendChild(el);
    }

    el.style.width = width;

    var iframe = el.firstChild;
    var span = el.lastChild;

    if (iframe == null) {
        iframe = document.createElement('iframe');
        iframe.id = 'iframe-' + name;
        iframe.name = 'iframe-' + name;
        iframe.className = 'iframeCon';
        iframe.scrolling = 'no';
        iframe.frameBorder = '0';
        el.appendChild(iframe);
        Famark.addHandler(iframe, 'load', function () {
            iframe.style.visibility = (iframe.name == 'pane' && iframe.offsetWidth < 40) ? 'hidden' : 'visible';
            var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
            Famark.addHandler(iframeDoc, 'keyup', Famark.docKeyUp);
        });
        var loadingClass = '';
        if (name == 'main') {
            Famark.addHandler(iframe, 'load', Famark.selectNav);
            loadingClass = ' loading';
        }
        var defaultUrl = Famark._defaultUrls[name];
        if (defaultUrl !== undefined) {
            el.className += loadingClass;
            iframe.style.visibility = 'hidden';
            iframe.src = defaultUrl;
        }
    }

    if (span == null) {
        span = document.createElement('span');
        span.style.position = 'absolute';
        try {
            span.style.backgroundColor = 'rgba(0,0,0,0.1)';
        } catch (e) { }
        span.style.zIndex = '-1';
        el.appendChild(span);
    }

    iframe.style.width = span.style.width = (el.offsetWidth - 6) + 'px';
    iframe.style.height = span.style.height = (el.offsetHeight - 6) + 'px';
    span.style.left = (el.offsetLeft + 6) + 'px';
    span.style.top = (el.offsetTop + 6) + 'px';

    Famark.setResizing(el, name);
    return el;
};
Famark.setResizing = function (el, name) {
    if (el == null || el.dragging !== undefined)
        return;

    el.dragging = null;

    Famark.addHandler(el, 'mouseover', function (e) {
        e = e || window.event;
        var x = (e.clientX - el.offsetLeft);
        if (x < 6)
            el.style.cursor = 'col-resize';
        else if (el.dragging == null)
            el.style.cursor = 'default';
    });

    Famark.addHandler(el, 'mousedown', function () {
        if (el.style.cursor == 'col-resize') {
            el.dragging = name;

            if (Famark._main != null)
                Famark._main.lastChild.style.zIndex = '1';
            if (Famark._pane != null)
                Famark._pane.lastChild.style.zIndex = '1';

            if (name == 'main') {
                Famark._nav.dragging = 'main';
                Famark._nav.onmousemove = Famark.screenResizing;
                Famark._main.onmousemove = Famark.screenResizing;
            } else if (name == 'pane') {
                Famark._main.dragging = 'pane';
                Famark._main.onmousemove = Famark.screenResizing;
                Famark._pane.onmousemove = Famark.screenResizing;
            }
        } else {
            el.dragging = null;
        }
    });

    Famark.addHandler(el, 'mouseup', function () {
        if (el.dragging != null) {
            window.setTimeout(function () { Famark._nav.dragging = null; Famark._nav.onmousemove = null; }, 100);
            Famark.setNavState();
            if (Famark._main != null)
                Famark.resizeEnd(Famark._main);
            if (Famark._pane != null) {
                Famark.resizeEnd(Famark._pane);
                Famark.setPaneState();
            }
            Famark.clearSelection();
        }
    });
};
Famark.screenResizing = function (e) {
    e = e || window.event;
    var el = e.target || e.srcElement;

    while (el.nodeName != 'DIV' && el.nodeName != 'BODY')
        el = el.parentNode;

    if (el.nodeName != 'DIV') return;

    if (el.dragging != null) {
        if (el.dragging == 'main')
            Famark.setNavWidth(e.clientX - 3);
        else if (el.dragging == 'pane')
            Famark.setPaneWidth(e.clientX - 3);
    }
};
Famark.setNavWidth = function (width) {
    var navWidth = Famark._nav.offsetWidth;
    Famark._nav.style.width = width + 'px';
    Famark._area.style.width = (Famark._area.offsetWidth + navWidth - Famark._nav.offsetWidth) + 'px';

    if (Famark._main != null)
        Famark.resizeSpan(Famark._main);

    if (Famark._pane != null) {
        var paneWidth = Famark._pane.offsetWidth;
        Famark._main.style.width = (Famark._area.offsetWidth - paneWidth) + 'px';
        Famark._pane.style.width = paneWidth + 'px';
        Famark.resizeSpan(Famark._pane);
    }
};
Famark.setNavState = function () {
    Famark._nav.style.visibility = (Famark._nav.offsetWidth < 40) ? 'hidden' : 'visible';
};
Famark.setPaneWidth = function (width) {
    var mainLeft = Famark._main.offsetLeft;
    Famark._main.style.width = (width - mainLeft) + 'px';
    Famark._pane.style.width = (Famark._area.offsetWidth - Famark._main.offsetWidth) + 'px';
    Famark.resizeSpan(Famark._main);
    Famark.resizeSpan(Famark._pane);
};
Famark.resizeSpan = function (el) {
    el.lastChild.style.width = (el.offsetWidth - 6) + 'px';
    el.lastChild.style.left = (el.offsetLeft + 6) + 'px';
};
Famark.resizeEnd = function (el) {
    el.firstChild.style.width = (el.offsetWidth - 6) + 'px';
    el.lastChild.style.zIndex = '-1';
    window.setTimeout(function () { el.onmousemove = null; el.dragging = null; }, 100);
};
Famark.setNavTarget = function (target, onClickHandler) {
    var links = Famark._nav.firstChild.getElementsByTagName('a');
    for (var i = 0; i < links.length; i++) {
        links[i].setAttribute('target', target);
        links[i].onclick = onClickHandler;
    }
};
Famark.removeElement = function (el, name) {
    if (el == null)
        return null;
    if (el.firstChild != null) {
        var url = 'about:blank';
        try {
            var iframeDoc = el.firstChild.contentDocument || el.firstChild.contentWindow.document;
            url = iframeDoc.location.href;
        }
        catch (e) {
            if (el.firstChild.src !== undefined)
                url = el.firstChild.src;
        }
        Famark._defaultUrls[name] = url;
    }
    Famark._area.removeChild(el);
    return null;
};
Famark.docKeyUp = function (e) {
    e = e || window.event;
    if (!e.ctrlKey)
        return;
    var link = null, btn = null;
    switch (e.keyCode) {
        case 192:
            link = Famark._nav.querySelector('.selected');
            break;
        case 48:
            link = btn = document.getElementById('btnSettings');
            break;
        case 219:
            if (e.shiftKey) {
                if (Famark._nav.offsetWidth < 40)
                    btn = document.getElementById('btnMenu');
                link = Famark._nav.querySelector('ul li span');
            } else {
                btn = document.getElementById('btnMenu');
            }
            break;
        case 221:
            if (e.shiftKey && Famark._pane != null) {
                if (Famark._pane.offsetWidth < 40)
                    btn = document.getElementById('btnPane');
                var iframe = Famark._pane.firstChild;
                link = Famark.getFocusElement(iframe.contentDocument || iframe.contentWindow.document);
            } else {
                btn = document.getElementById('btnPane');
            }
            break;
    }
    if (btn != null)
        btn.click();
    if (link != null)
        link.focus();
};
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.getElementsByClassName = function (cName, tName, node) {
    var els = [];
    var tmp, i;

    tName = tName || '*';
    node = node || document;

    if (node.getElementsByClassName) {
        tmp = node.getElementsByClassName(cName);
        for (i = 0; i < tmp.length; i++)
            els.push(tmp[i]);
    }
    else {
        var pattern = new RegExp('\\b' + cName + '\\b');
        tmp = node.getElementsByTagName(tName);
        for (i = 0; i < tmp.length; i++) {
            if (pattern.test(tmp[i].className))
                els.push(tmp[i]);
        }
    }

    return els;
};
Famark.toggleSub = function (el) {
    var n = el;
    if (!n)
        return;
    
    do n = n.nextSibling;
    while (n != null && n.nodeType != 1);

    if (n != null) {
        if (n.style.display == 'none')
            n.style.display = '';
        else
            n.style.display = 'none';
    }
};

Famark.navSpanKeyPress = function (e, el) {
    e = e || window.event;
    if (e.keyCode == 13)
        Famark.toggleSub(el);
};

Famark.setCookieByPath = function (key, value, path) {
    value = window.escape(value);
    document.cookie = key + '=' + value + '; path=' + path;
};

Famark.removeCookieByPath = function (key, path) {
    var past = new Date(0);
    document.cookie = key + '=; expires=' + past.toUTCString() + '; path=' + path;
};

Famark.getCookie = function(key) {
    if (document.cookie.length > 0) {
        var sPos = document.cookie.indexOf(key + '=');
        if (sPos != -1) {
            sPos = sPos + key.length + 1;
            var ePos = document.cookie.indexOf(';', sPos);
            if (ePos == -1)
                ePos = document.cookie.length;
            return window.unescape(document.cookie.substring(sPos, ePos));
        }
    }
    return null;
};

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();
    }
};

Famark.selectNav = function (e) {
    e = e || window.event;
    var iframe = e.target || e.srcElement;
    var links = Famark._nav.getElementsByTagName('a');
    var i;
    Famark.removeMainLoading();
    try {
        var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
        Famark.addHandler(iframeDoc.defaultView, 'unload', Famark.setMainLoading);

        var mainUrl = iframeDoc.location.href;
        if (mainUrl == null || mainUrl == 'about:blank') {
            for (i = 0; i < links.length; i++)
                links[i].className = null;
            return;
        }

        for (i = 0; i < links.length; i++) {
            var linkUrl = links[i].getAttribute('href');
            var linkPos = mainUrl.indexOf(linkUrl);
            var linkEnd = linkPos + linkUrl.length;
            if (linkPos >= 0 && (mainUrl.length <= linkEnd || mainUrl[linkEnd] == '&'))
                links[i].className = 'selected';
            else
                links[i].className = null;
        }

        Famark.getFocusElement(iframeDoc).focus();
    } catch (e) {
        for (i = 0; i < links.length; i++)
            links[i].className = null;
    }
};
Famark.getFocusElement = function (doc) {
    try {
        var focusable = doc.querySelector('select:not([disabled]), input:not([type="hidden"]):not([disabled]), button:not([disabled]), a[href], textarea:not([disabled]), [tabindex]:not([tabindex="-1"])');
        return (focusable || doc.defaultView);
    } catch (e) {
        return doc.defaultView;
    }
};
window.onrendercomplete = function () {
    if (Famark._main != null && Famark._main.lastChild != null)
        Famark._main.removeChild(Famark._main.lastChild);
    if (Famark._pane != null && Famark._pane.lastChild != null)
        Famark._pane.removeChild(Famark._pane.lastChild);
};