(function (Core) {

    //
    // This page is included on Orion's Master Pages just before the closing body tag.
    //

    var Header = Core.Header = Core.Header || {},
    Footer = Core.Footer = Core.Footer || {},
    MessageBox = Core.MessageBox = Core.MessageBox || {};

    MessageBox.Dialog = function (config) {
        var html = '<div>' +
               '  <div style="padding: 3px 10px;">' +
                    config.html +
               '    <div style="bottom:10px; text-align:center;" >';

        if (config.buttons != null && config.buttons != undefined) {
            for (i = 0; i < config.buttons.length; i++) {
                html += config.buttons[i].html + '<span>&nbsp;</span>';
            }
        }

        html += '    </div>' +
               '  </div>' +
               '</div>';

        var dlg = $(html);

        dlg.show().dialog({
            title: config.title || '',
            width: config.width || 450,
            dialogClass: "sw-message-box",
            modal: !!config.modal,
            overlay: { "background-color": "black", opacity: 0.4 },
            height: config.height || 200
        });

        if (config.buttons != null && config.buttons != undefined) {
            for (i = 0; i < config.buttons.length; i++) {
                $('#' + config.buttons[i].id, dlg).click(function () {
                    for (j = 0; j < config.buttons.length; j++) {
                        if (config.buttons[j].id == this.id)
                            config.buttons[j].handler(dlg);
                    }
                });
            }
        }
    }

    // Eval Banner Handling.
    Header.EvalInit = function (EvalBannerDetails) {

        $('#evalMsg a').click(function () {
            var html = '<div id="evalDetails">' +
               '  <div style="padding: 3px 10px;">' +
               '    <div>' +
               '       <p>You have the following SolarWinds Orion free trials installed:' +
               '       <ul id="evalDetailsList"/>' +
               '    </div>' +
               '    <div style="position:absolute;bottom:10px;right:10px;padding-right:5px;" >' +

               SW.Core.Widgets.Button('Close', { type: 'primary', id: 'evalDetailsClose' }) +

               '    </div>' +
               '  </div>' +
               '</div>';
            var dlg = $(html);

            $('#evalDetailsClose', dlg).click(function () {
                dlg.dialog('close');
            });

            var fmt = Core.String.Format;

            var items = '';
            $.each(EvalBannerDetails, function () {
                var countTxt = this.IsExpired ? 'Expired' : fmt(this.DaysRemaining == 1 ? '1 day' : '{0} days left', this.DaysRemaining);
                items += '<li><b>' + this.DisplayName + '</b> - ' + countTxt + '</li>';
            });
            $('#evalDetailsList', dlg).empty().append(items);

            dlg.dialog({
                title: 'Evaluation Details',
                width: 500,
                modal: true
            });
        });

    };

    // RC panel Handling
    Header.RCInit = function (RCBannerDetails, HelpUrl) {

        $('#rcMsg a').click(function () {
            var html = '<div id="rcDetails">' +
               '  <div style="padding: 3px 10px;">' +
               '    <div>' +
               '       <p>You have the following SolarWinds  Release Candidates installed. <span style="font-size: 8.5pt; cursor: pointer;">&nbsp;' +
               '           » <a href="' + HelpUrl + '" ' +
               '              target="_blank">What is a release candidate?</a></span>' +
               '       <ul id="rcDetailsList"/>' +
               '    </div>' +
               '    <div style="position:absolute;bottom:10px;right:10px;padding-right:5px;" >' +

               SW.Core.Widgets.Button('Close', { type: 'primary', id: 'rcDetailsClose' }) +

               '    </div>' +
               '  </div>' +
               '</div>';
            var dlg = $(html);

            $('#rcDetailsClose', dlg).click(function () {
                dlg.dialog('close');
            });

            var fmt = Core.String.Format;

            var items = '';
            $.each(RCBannerDetails, function () {
                var countTxt = this.IsExpired ? 'Expired' : fmt(this.DaysRemaining == 1 ? '1 day' : '{0} days left', this.DaysRemaining);
                items += '<li><b>' + this.DisplayName + '</b> - ' + countTxt + '</li>';
            });
            $('#rcDetailsList', dlg).empty().append(items);

            dlg.dialog({
                title: 'Release Candidate Details',
                width: 600,
                modal: true
            });
        });

    };

    Header.WarnIfOldBrowser = function () {
        if ($.browser.msie && ($.browser.version == "6.0")
            && location.href.toLowerCase().indexOf('inlinerendering=true') == -1
            && location.href.toLowerCase() != 'about:blank'
            && !SW.Core.Cookie.Get("SW_UnsupportedBrowser_HideWarning")) {
            Core.MessageBox.Dialog({
                title: 'Update Browser',
                width: 450,
                modal: true,
                height: 150,
                html: '<table style="width: 100%;">' +
                  ' <tr>' +
                  '  <td style="vertical-align: top; padding:0px 10px 0px 2px;">' +
                  '   <img src="/orion/images/info_32x32.gif" />' +
                  '  </td>' +
                  '  <td>' +
                  '   This browser version is no longer supported by SolarWinds. ' +
                  '     <br/>&#0187; <a href="http://knowledgebase.solarwinds.com/kb/questions/2997/" target="_blank" class="coloredLink">More Details</a> ' +
                  '     <br/><br/>' +
                  '     <table>' +
                  '        <tr><td width="20px"><input id="notShowAgain" type="checkbox" style="width:20px!important;"/></td>' +
                  "            <td class='cb-label'>Don\'t show this again</td><tr>" +
                  '     </table>' +
                  '  </td>' +
                  ' </tr>' +
                  '</table>',
                buttons: [
                {
                    id: 'updateBrowserWarningBtn',
                    html: SW.Core.Widgets.Button('Ok', { type: 'primary', id: 'updateBrowserWarningBtn' }),
                    handler: function (msbox) {
                        if ($('#notShowAgain').get(0).checked) {
                            SW.Core.Cookie.Set('SW_UnsupportedBrowser_HideWarning', '1', 'years', 5);
                        }
                        else {
                            SW.Core.Cookie.Set('SW_UnsupportedBrowser_HideWarning', '1', 'minutes', 5);
                        }
                        msbox.dialog('close');
                    }
                }
            ]
            });

            // fix i18n button's styles for IE6 browser
            // due to this message shows only for IE6 browser
            $("#updateBrowserWarningBtn").find('span.sw-btn-m').css('overflow', 'hidden');
            $("#updateBrowserWarningBtn").find('span.sw-btn-br').css('background-position', '-10px -108px');
            $("#updateBrowserWarningBtn").find('span.sw-btn-bl').css('background-position', '0px -108px');
            $("#updateBrowserWarningBtn").find('span.sw-btn-b').css('background-position', '0px -6px');
            $("#updateBrowserWarningBtn").find('span.sw-btn-c').css('padding-bottom', '6px');
        }
    }

    Header.TabsInit = function (OrionTabSettings) {

        var url = window.location + "";
        if (url.toLowerCase().search("login.aspx") > 0) {
            return true;
        }

        var tabCount = $('div#tabs div.sw-mainnav-bars a').length;

        if (tabCount == 0) {
            return true;
        }

        var $currentTab = '';
        var $selectedTab = '';
        var overTimeout = 0;
        var outTimeout = 0;
        var sensitiv = 1;

        sensitiv = OrionTabSettings.TabsSensitivity;
        overTimeout = OrionTabSettings.TabsMouseOverTimeout;
        outTimeout = OrionTabSettings.TabsMouseOutTimeout;

        var tabContainers = $('div#tabs div.sw-mainnav-bars ul');
        var redirect = false;
        var mouseOver = false;
        var mouseOut = false;
        var hash;
        var allowSetActiveTabIdCallback = true;

        var isAdmin = window.IsOrionAdminPage || (window.location.pathname.match(new RegExp('Orion[/a-zA-Z]+Admin')) != null);
        var tabsConfig = {
            sensitivity: sensitiv,
            interval: 0,
            over: function (e) { },
            timeout: outTimeout,
            out: function (e) {
                // if e doesn't exist, get it.
                if (!e) var e = window.event;
                // this is the element we've moved to
                var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
                // if reltg is null - cursor is out of browser window
                if (reltg != null && reltg != undefined) {
                    while (reltg.id != 'tabs' && reltg.tagName != 'BODY' && reltg.tagName != 'HTML')
                        reltg = reltg.parentNode;
                    if (reltg.id == 'tabs') {
                        // we found tg as a parent. So this is not really leaving the element
                        return;
                    }
                }
                // return to current tab
                mouseOut = true;
                if (!isAdmin) {
                    $("ul[id*='tabs-empty']").css('display', 'none');
                    $("a[href='" + $currentTab + "']").click();
                }
                else {
                    $("ul[id*='tabs-']").css('display', 'none');
                    $("ul[id*='tabs-empty']").css('display', 'block');
                }
            }
        };

        var tabConfig = {
            sensitivity: sensitiv,
            interval: overTimeout,
            over: function (e) {
                mouseOver = true;
                mouseOut = false;
                $(this).click();
            },
            timeout: 0,
            out: function (e) { }
        };

        $("div#tabs").hoverIntent(tabsConfig);
        $('div#tabs div.sw-mainnav-tabs a').hoverIntent(tabConfig);

        $('div#tabs div.sw-mainnav-tabs a').click(function () {
            tabContainers.hide().filter(this.hash).show();
            $('div#tabs div.sw-mainnav-tabs li').removeClass('selected');
            $(this).parent('li').addClass('selected');

            hash = this.hash;
            $selectedTab = $(this)[0].href;

            setCookie('SelectedTab', this.hash.replace('#tabs-', ''), 'hours', 2);

            if (allowSetActiveTabIdCallback) {
                $.ajax({
                    type: 'Post',
                    url: '/Orion/Services/TabsManager.asmx/SetActiveTabId',
                    data: "{'tabId': '" + this.hash.replace('#tabs-', '') + "'}",
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    success: function () {
                    },
                    error: function () {
                        redirect = true;
                        mouseOver = false;
                        mouseOut = false;
                    }
                });
            }

            if (redirect && !mouseOver && !mouseOut) {
                $currentTab = $selectedTab;
                isAdmin = false;
                window.location.href = tabContainers.filter(hash).find('a').filter(':first')[0].href;
            }
            redirect = true;
            mouseOver = false;
            mouseOut = false;

            return false;
        });

        $('div#tabs .sw-mainnav-bars a').click(function () {
            if (this.target != '_blank') {
                $currentTab = $selectedTab;
                isAdmin = false;
                window.location.href = this.href;
                return false;
            }
            else {
                window.open(this.href);
                return false;
            }
        })

        // Set the current tab...
        if (!isAdmin) {
            allowSetActiveTabIdCallback = false;
            $("a[href='#tabs-" + OrionTabSettings.CurrentTabId + "']").click();
            allowSetActiveTabIdCallback = true;
        }

        $currentTab = '#tabs-' + OrionTabSettings.CurrentTabId;
        $selectedTab = '#tabs-' + OrionTabSettings.CurrentTabId;
    };

    Header.SyncTo = function (cssselector) {

        // default to syncing with web resources.
        var selector = cssselector || '.ResourceContainer', appregionid, syncid,

    sync_region = function () {
        if (!syncid) {
            appregionid = Core.Id($('.sw-app-region')[0]);
            var p = $(selector)[0];
            while (p && p.parentNode) {
                if ((p.parentNode.tagName == 'FORM') || (p.parentNode.id == appregionid)) break;
                p = p.parentNode;
            }
            syncid = Core.Id(p);
        }

        var docw = $(window).width(),
            winw = $(window).width(),
            res = $('#' + syncid),
            off = res.offset().left,
            rm = parseInt(res.css('margin-right'), 10),
            resw = rm + off + res.outerWidth(),
            w = Math.max(winw, resw);

        w = (w == winw) ? '100%' : '' + w + 'px';
        $('#pageHeader,#footer,#' + appregionid).css('width', w);
    };

        $(sync_region);
        $(window).resize(sync_region);
        $(window).load(sync_region);
    };

    // Footer (revised from original 'ie6' version)

    Footer.Init = function (opts) {
        var options = opts || {};
        $(function () {
            var domid = options.ismobile ? '#mobileFooter' : '#footer',
        _w, _d, sync = function () {
            var w = $(window).height(), m = $('#footermark'), d = m.offset().top;
        if( (w != _w) || (d != _d) )
        {
                $(domid).css('position', (w >= (d + 40)) ? 'fixed' : 'static');
                _w = w;
                _d = d;
            }
        };

            // if within container, 'content' is in content, !ie6 && !mobile: we don't neeed javascript
            var within = $(domid).parents('#container')[0], present = $('#content')[0], is_ie6 = jQuery.browser.msie && (parseInt(jQuery.browser.version) == 6);
            if (options.ismobile || is_ie6 || !within || !present) {
                $(sync);
                $(window).resize(sync);
                $(window).load(sync);
            }
        });
    };

    Header.WarnIfOldBrowser();
})(SW.Core);

