
///////////////////////////////////////////////////////////////
// GLOBAL VARS
///////////////////////////////////////////////////////////////
var isfullscreen = false;
var embedded_mcfh = 0;
var embedded_mch = 0;
var embedded_mcw = 0;
var embedded_header_height = 0;
var leftbar_width = 0;

var feedbackcentered = false;
var popupcentered = false;
var childpopupcentered = false;

var inframe = (window.location != window.parent.location) ? true : false;

///////////////////////////////////////////////////////////////
// DOCUMENT LOAD FUNCTIONS
///////////////////////////////////////////////////////////////

$(document).on('change', '.btn-file :file', function() {
    var input = $(this),
        numFiles = input.get(0).files ? input.get(0).files.length : 1,
        label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
    input.trigger('fileselect', [numFiles, label]);
});


// set a field to be required based on some javascript event
function set_dynamic_required($el) {
    $el.attr('required', 'true');
    $el.addClass('required');
    $el.keyup();
}

// remove the dynamic required constraint from the field
function remove_dynamic_required($el) {
    $el.removeAttr('required');
    $el.removeClass('required');
}

$(document).ready(function() {

    // escape key was pressed, so lets close some stuff
    $(document).keyup(function(e) {
        if (e.keyCode == 27) {
            close_popup();
            close_child_popup();
            clear_whiteout();
            hide_throbber();
            $("#feedback_layer").css("visibility", "hidden");
        }
    });

    // the button click event that allows cancel buttons to actually allow
    // the submission of bootstrap validator forms
    $('input.cancel-validator').click(function() {
        $('form *').removeAttr('required');
    });
    
    // the form validator icon remover
    $('body').on('keyup', 'input.required', function() {

        // if input gets empty again
        if ($(this).val() == '') {
            $(this).attr('required', 'true');
        }

        // if input has some value
        if ($(this).val() != '') {
            $(this).removeAttr('required');
        }
    });

    // make sure anything that is specified to be required
    // has the required class
    $('input[required]').each(function() {
        $(this).addClass('required').keyup();;
    });


    $('.tt-bind').tooltip({container: 'body'});

    var popover_options = {
        html: true,
        container: "body",
        placement: function (context, source) {
            var position = $(source).position();

            if (position.left > 515) {
                return "left";
            }

            if (position.left < 515) {
                return "right";
            }

            if (position.top < 110){
                return "bottom";
            }

            return "top";
        }
    };

    $('.pop').popover(popover_options);
    $('.sk-spinner-center').center(false);

    $('.btn-file :file').on('fileselect', function(event, numFiles, label) {
        var input = $(this).parents('.input-group').find(':text');
        $(input).val(label);
    });

    // Add padding to enterprise message on non-frame windows
    if (!inframe) {
        if ($('body > .enterprisefeaturenotice').length > 0) {
            $('body.child').css('padding-top', '31px');
        }
    }

    if (window == top) {
        resize_content(false);
        center_content_throbbers();
    }
    
    $(window).resize(function() {
        if (window == top) { resize_content(false); }
        center_content_throbbers();
        if ($('#child_popup_layer').is(":visible")) { center_child_popup(); }
        if ($('#popup_layer').is(":visible")) { center_popup(); }
        if ($('#whiteout').is(":visible")) {
            clear_whiteout();
            whiteout();
        }
    });

    $('.servicestatustable').on('change', '.tablepagerselect', function() {
        $('.tablepagerselect').val($(this).val());
    });

    $('.servicestatustable').on('keyup', '.tablepagertextfield', function() {
        $('.tablepagertextfield').val($(this).val());
    });

    $('.hoststatustable').on('change', '.tablepagerselect', function() {
        $('.tablepagerselect').val($(this).val());
    });

    $('.hoststatustable').on('keyup', '.tablepagertextfield', function() {
        $('.tablepagertextfield').val($(this).val());
    });

    $("#closetrialnotice").click(function() {
        var p = this.parentNode;
        var gp = p.parentNode;
        $(gp).remove();

        var opts = { "ignore_trial_notice": 1 };
        set_session_vars(opts);
        $('#maincontent').css('top', 'inherit');
    });

    $("#closefreenotice").click(function() {
        var p = this.parentNode;
        var gp = p.parentNode;
        $(gp).remove();

        var opts = { "ignore_free_notice": 1 };
        set_session_vars(opts);
        $('#maincontent').css('top', 'inherit');
    });

    // close handler for the fips warning banner
    $("#closefipsnotice").click(function() {
        var p = this.parentNode;
        var gp = p.parentNode;
        $(gp).remove();
        $('#maincontent').css('top', 'inherit');
        
        var opts = { "ignore_fips_warning": 1 };
        set_session_vars(opts);
        resize_content();
    });
    
    // dismiss handler for the fips warning banner
    $("#dismiss-anniversary-license-notice").click(function() {
        var p = this.parentNode;
        var gp = p.parentNode;
        $(gp).remove();
        $('#maincontent').css('top', 'inherit');
        
        var opts = { "ignore_25_year_celebration_license_notice": 1 };
        set_session_vars(opts);
        resize_content();
    });

    $("#topmenucontainer ul.menu li a").click(function() {
        show_throbber();
    });

    $('#maincontentframe').load(function() {
        try {
            if ($('#maincontentframe').contents().find('.enterprisefeaturenotice').length > 0) {
                var v = $('#maincontentframe').contents().find('.enterprisefeaturenotice').outerHeight();
                var tpad = v + $('.parenthead').outerHeight();
                if ($('.contentheadernotice').length > 0) {
                    tpad += $('.contentheadernotice').outerHeight();
                }
                $('#fullscreen').css('top', tpad+'px');
                $('#maincontentframe').contents().find('.childpage').css('margin-top', v+'px');
            } else {
                $('#fullscreen').removeAttr('style');
            }
        } catch (e) {
            // Frame was not from same domain
        }
    });

    $("#fullscreen").click(function() {
        var x = 1;
        if (!isfullscreen) {

            $("body").css("margin","0");
            $("#leftnav").hide();
            $("#header").hide();
            $("#footer").hide();
            $("#viewtools").hide();
            isfullscreen = true;
            $("#maincontentframe").css('width', "100%");

            $('#fullscreen').css('left', '0px');
            $('#fullscreen').removeClass('fs-open').addClass('fs-close');

            // Make the iframe fullscreen
            do_fullscreen();

        } else {

            $("body").css("margin", bodymargin+"px");
            $("#leftnav").show();
            $("#header").show();
            $("#footer").show();
            $("#viewtools").show();
            isfullscreen = false;

            $('#fullscreen').css('left', '200px');
            $('#fullscreen').removeClass('fs-close').addClass('fs-open');

            try {
                if ($('#maincontentframe').contents().find('.enterprisefeaturenotice').length > 0) {
                    var tpad = $('#maincontentframe').contents().find('.enterprisefeaturenotice').outerHeight() + $('.parenthead').outerHeight();
                    $('#fullscreen').css('top', tpad+'px');
                } else {
                    $('#fullscreen').removeAttr('style');
                }
            } catch (e) {
                // Frame was not same domain
            }

            resize_content();

        }
    });

    // permalink
    $("#permalink a").click(function() {

        show_throbber();
        var parser = document.createElement('a');
        parser.href = $('#maincontentframe').contents()[0].URL;
        var url = parser.pathname + parser.search + parser.hash;
        var theurl = decodeURIComponent(base_url) + "?fusionwindow=" + encodeURIComponent(url);


        var opts = {
            "theurl": theurl
            };

        $("#popup_layer").draggable('disable');

        post_ajax_data_with_callback('get_permalink_form', opts, function(data) {

            $("#popup_container").html(data);

            hide_throbber();
            display_popup(450);
        });
    });

    // anniversary popup
    $('#update-license').click(function(event) {
        event.preventDefault()
        
        var key = $('#key').val()
        var opts = {
            key: key,
            needs_acknowledgement: true
        };
        post_ajax_data_with_callback('check_25_year_celebration_license', opts, function(is_valid) {
            if (is_valid) {
                show_throbber();
                $("#child_popup_layer").draggable('disable');

                post_ajax_data_with_callback('get_25_year_celebration_license_popup', opts, function(data) {
                    set_child_popup_content(data)
                    whiteout()
                    display_child_popup()
                    hide_throbber();
                });
            } else {
                $('#update-license-form').trigger('submit')
            }
        });
    });

    // slicense popup
    $('#view-slicense-popup').click(function() {
        var opts = {
            needs_acknowledgement: false
        };
        post_ajax_data_with_callback('get_25_year_celebration_license_popup', opts, function(data) {
            $("#popup_container").html(data)

            display_popup(600)
            hide_throbber();
        });
    });

    $("#leftnav").on("click", ".menusectiontitle", function(e) {

        // Verify that we aren't clicking a link
        var target = $(e.target);
        if (target.is('a')) { return; }

        var menusection = $(this).parents('.menusection');
        if (menusection.hasClass("menusection-collapsed")) {
            menusection.removeClass("menusection-collapsed");
            menusection.find('.fa.fa-chevron-up').removeClass('fa-chevron-up').addClass('fa-chevron-down').attr('title', '');
            var opts = {
                "keyname": "menu_collapse_options",
                "menuid": $(this).data('id'),
                "keyvalue": 1,
                "autoload": false
                };
            set_user_meta(opts);

        } else {
            menusection.addClass("menusection-collapsed");
            menusection.find('.fa.fa-chevron-down').removeClass('fa-chevron-down').addClass('fa-chevron-up').attr('title', '');
            var opts = {
                "keyname": "menu_collapse_options",
                "menuid": $(this).data('id'),
                "keyvalue": 0,
                "autoload": false
                };
            set_user_meta(opts);
        }
    });

    $("#popout a").click(function() {
        var theurl = $('#maincontentframe').contents()[0].URL;
        window.open(theurl);
    });

    ///////////////////////////////////////////////////////////////////////////////
    // POPUP
    ///////////////////////////////////////////////////////////////////////////////
    
    // Make it draggable
    $("#popup_layer").each(function() {
        $(this).draggable();
    });

    // Close popup
    $("#close_popup_link").click(function() {
        close_popup();
    });
        
    ///////////////////////////////////////////////////////////////////////////////
    // CHILD POPUP
    ///////////////////////////////////////////////////////////////////////////////
    
    // Make it draggable
    $("#child_popup_layer").each(function() {
        $(this).draggable();
    });

    // Close popup
    $("#close_child_popup_link").click(function() {
        close_child_popup();
        clear_whiteout();
    });

    $("#child_popup_layer").on('click', ".close_child_popup_btn", function() {
        close_child_popup();
        clear_whiteout();
    });

    // All form submissions
    $(":submit").click(function() {
        hide_message();
    });

    // Hide throbber on links
    $("#get_online_help_link").click(function() { hide_throbber(); });
    $(".tablesorter tbody tr td a").click(function() { hide_throbber(); });
    $("#feedbacklayer a").click(function() { hide_throbber(); });
    $("#notices a").click(function() { hide_throbber(); });

    ///////////////////////////////////////////////////////////////////////////////
    // TABS
    ///////////////////////////////////////////////////////////////////////////////
    
    // Hide tab span text if there is an icon 
    $('#tabs ul.tabnavigation a i').parent().find("span").hide();

    // Show span text if tab is active
    $('#tabs ul.tabnavigation li').first().find("span").show();
    
    $('#tabs ul.tabnavigation a i').parent().tooltip();
    
    $('#tabs ul.tabnavigation a').click(function () {
        $('#tabs ul.tabnavigation a i').parent().find("span").hide();
        $(this).find("span").show();
    });
    

    ///////////////////////////////////////////////////////////////////////////////
    // FEEDBACK
    ///////////////////////////////////////////////////////////////////////////////
    
    // Make it draggable
    $("#feedback_layer").each(function() {
        $(this).draggable();
    });

    $("#close_feedback_link").click(function() {
        hide_throbber();
        $("#feedback_layer").css("visibility", "hidden");
    });

    $("#feedback a").click(function() {

        show_throbber();

        if (!feedbackcentered) {
             center_feedback();
        }
        hide_throbber();
        $("#feedback_layer").css("visibility", "visible");
        
        // Restore original html
        $("#feedback_container").each(function() {
            if (this.origHTML) {
                this.innerHTML = this.origHTML;
            }
        });

        // Clear old feedback text
        $("#feedback_form textarea").each(function() {
             this.value = '';
        });
    });

    // Handle feedback_form submission
    $("#feedback_form").submit(function() {

        hide_throbber();
        var params = {};
        $(this) 
            .find(":input, :password, :checkbox, :radio, :submit, :reset")
            .each(function() { params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value; });
    
        $.ajax({
            type: "POST",
            url: this.getAttribute("action"),
            data: params,
            beforeSend: function(XMLHttpRequest) {
                get_ajax_data_html('get_feedback_sending', 0, $("#feedback_container"));
            },
            success: function(msg) {
                get_ajax_data_html('get_feedback_success', 0, $("#feedback_container"));
            },
            error: function(msg) {
                get_ajax_data_html('get_feedback_error', 0, $("#feedback_container"));
            }
        });
        return false;
    });

    $('#open-search').click(function() {
        $(this).hide();
        $('.search-field').fadeIn('fast');
        $('input.search-query').focus();
    });

    $('input.search-query').blur(function() {
        var s = $(this).val();
        if (s == "") {
            $('.search-field').hide();
            $('#open-search').show();
        }
    });
        
    // Refresh the whole page only if it needs to be
    $(document).keydown(function(e) {
        if (e.keyCode == 116 || (e.ctrlKey && e.keyCode == 82)) {
            if (inframe) {
                // Inside a frame
                e.preventDefault();
                e.stopPropagation();
                self.location.reload(true);
            } else {
                // Outside the frame
                if ($('#maincontentframe').length > 0) {
                    e.preventDefault();
                    e.stopPropagation();
                    document.getElementById('maincontentframe').contentDocument.location.reload(true);
                }
            }
        }
    });
});


// Whiteout the page background (z-index > 9000 only)
function whiteout()
{
    if (inframe || $('#maincontent').length == 0) {
        $('#whiteout').width($(window).width());
        $('#whiteout').height($(window).height());
        $('#whiteout').css('position', 'fixed');
        $('#whiteout').css('top', '0');
        $('#whiteout').css('left', '0');
    } else {
        var w = $('#maincontent').width();
        var h = $('#maincontent').height();
        var t = $('#maincontent').css('top');
        var l = $('#maincontent').css('left');
        $('#whiteout').width(w);
        $('#whiteout').height(h);
        $('#whiteout').css('top', t);
        $('#whiteout').css('left', l);
        $('#whiteout').css('position', 'absolute');
    }
    $('#whiteout').show();
}

function clear_whiteout()
{
    $('#whiteout').hide();
}

// Blackout the entire UI (z-index > 9000 only)
function blackout()
{
    blackout_resize();
    $('#blackout').show();
}

function blackout_resize()
{
    $('#blackout').css('width', $(window).width()+'px');
    $('#blackout').css('height', $(window).height()+'px');
    $('#blackout').css('position', 'fixed');
    $('#blackout').css('top', '0');
    $('#blackout').css('left', '0');
}

function clear_blackout()
{
    $('#blackout').hide();
}

// Center the feedback container
function center_feedback()
{
    var l = $("#feedback_layer");
    var wh = $(window).height();
    var ww = $(window).width();
    var lh = $(l).height();
    var lw = $(l).width();

    var newtop = (wh-lh)/2;
    var newleft = (ww-lw)/2;
    $("#feedback_layer").css("top", newtop);
    $("#feedback_layer").css("left", newleft);
    feedbackcentered = true;
}

// Center the login_alert_popup container
function center_login_alert_popup()
{
    var l = $("#feedback_layer");
    var wh = $(window).height();
    var ww = $(window).width();
    var lh = $(l).height();
    var lw = $(l).width();

    var newtop = (wh-lh)/2;
    var newleft = (ww-lw)/2;
    $("#login_alert_popup").css("top", newtop);
    $("#login_alert_popup").css("left", newleft);
    feedbackcentered = true;
}


// Generic async fetcher with callback
function get_ajax_data_with_callback(c, o, success)
{
    if (typeof o === 'object')
        o = array2json(o);

    $.ajax({
        type: "GET",
        async: true,
        url: ajax_helper_url,
        data: { cmd: c, opts: o, nsp: nsp_str },
        success: success
    });
}

// Async fetcher for inner html
function get_ajax_data_html(c, o, obj)
{
    get_ajax_data_with_callback(c, o, function(data) {
        $(obj).html(data);
    });
}

// Bind tool tip via CSS selector
function bind_tt(data)
{
    $('.a-tt-bind').tooltip();
}

// Send data to ajax helper without doing anything with it
function post_ajax_data(c, o)
{
    if (typeof o === 'object')
        o = array2json(o);

    $.ajax({
        type: 'POST',
        url: ajax_helper_url,
        data: { cmd: c, opts: o, nsp: nsp_str }
    });
}

// send data to ajax helper and specify a success callback function
function post_ajax_data_with_callback(c, o, success) {

    if (typeof o === 'object')
        o = array2json(o);

    $.ajax({
        type: 'POST',
        url: ajax_helper_url,
        data: { cmd: c, opts: o, nsp: nsp_str },
        success: success
    });
}

// set session vars via ajax helper
function set_session_vars(o) {

    post_ajax_data('set_session_vars', o);
}

// set user meta
function set_user_meta(o) {

    post_ajax_data('set_user_meta', o);
}

function set_user_meta_with_success(o, success) {
    post_ajax_data_with_callback('set_user_meta', o, success);
}

// get user meta
function get_user_meta(o, success) {

    var opts = {
        "keyname": o
    };

    post_ajax_data_with_callback('get_user_meta', opts, success);
}

    
// Throbbers
function show_throbber() { $("#throbber").css("display", "block"); }
function hide_throbber() { $("#throbber").css("display", "none"); }

function hide_message() { $("#message").css("visibility", "hidden"); }
function remove_message() { $("#message").remove(); }

var MCT = 0;
var MCL = 0;

function resize_content()
{
    var h = $(window).height();
    var w = $(window).width();

    var mf = $("#mainframe");
    if (!mf) {
        return;
    }

    var hpad = 0;
    if ($('#header').is(':visible') && $('#footer').is(':visible')) {
        hpad = $('#header').outerHeight() + $('#footer').outerHeight();
    }

    var height = h - hpad;
    $("#mainframe").css('height', height+"px");
    
    var nh = 0;
    if ($('.contentheadernotice').length > 0) {
        $('.contentheadernotice').each(function() {
            nh += $(this).outerHeight();
        });
    }
    var mfh = $("#mainframe").outerHeight();

    $("#leftnav").css('height', mfh-extraheightnav-nh+"px");   
    $("#maincontent").css('height', mfh-extraheight-nh+"px");

    var mcfw = w - extrawidth;
    if ($('#header').is(':visible') && $('#footer').is(':visible')) {
        mcfw -= $('#leftnav').outerWidth();
    }
    var mcfh = mfh;

    $('#maincontent').css('top', nh+'px');
    if (!$('#header').is(':visible') && !$('#footer').is(':visible')) {
        $('#maincontent').css('left', '0px');
    } else {
        if (nh > 0) {
            if (MCT == 0) {
                var mct = $('#maincontent').css('top');
                MCT = parseInt(mct.substring(0, mct.length - 2));
            }
            $('#maincontent').css('top', (MCT+nh)+'px');
        }

        // Fix header/sidebar
        if ($('#header').is(':visible')) {
            $('#maincontent').css('top', $('#header').outerHeight()+nh+'px');
        }
        if ($('#leftnav').is(':visible')) {
            $('#maincontent').css('left', $('#leftnav').outerWidth()+'px');
        }
    }

    // Move the fullscreen button
    try {
        if ($('#maincontentframe').contents().find('.enterprisefeaturenotice').length > 0) {
            var tpad = $('#maincontentframe').contents().find('.enterprisefeaturenotice').outerHeight();
            if ($('#header').is(':visible')) {
                tpad += $('.parenthead').outerHeight();
            }
            if ($('.contentheadernotice').length > 0) {
                tpad += $('.contentheadernotice').outerHeight();
            }
            $('#fullscreen').css('top', tpad+'px');
        }
    } catch (e) {
        // Frame was not from same domain
    }

    $("#maincontentframe").css('width', mcfw+"px");
    $("#maincontent").css('width', mcfw+"px");
    $("#myviewoverlay").css('height', mcfh-20);
    $("#myviewoverlay").css('opacity', 0.1);
}

function do_fullscreen()
{
    var d = document;
    if (!d) {
        return;
    }
    var db = document.body;
    if (!db) {
        return;
    }

    resize_content();
}
    
function display_popup(cwidth,cheight)
{
    $("#popup_close").each(function() {
        $(this).css("visibility", "visible");
    });
        
    // Forced content dimensions
    if (cwidth) {
        $("#popup_content").css("width", cwidth);
    }
    if (cheight) {
        $("#popup_content").css("height", cheight);
    }
    
    // $("#popup_layer").css("background-color", "#F1F1F1");
    $("#popup_layer").css("opacity", "1.0");
    $("#popup_layer").css("display", "block");

    // Adjust height to fit contents
    var lh = $("#popup_layer").height();
    var ch = $("#popup_content").height();
    var chmt = parseInt($("#popup_content").css("margin-top"));
    var chmb = parseInt($("#popup_content").css("margin-bottom"));
    height = ch+chmt+chmb;
    $("#popup_layer").css("height", height);

    // Adjust width to fit contents
    var lw = $("#popup_layer").width();
    var cw = $("#popup_content").width();
    var cwmr = parseInt($("#popup_content").css("margin-right"));
    var cwml = parseInt($("#popup_content").css("margin-left"));
    width = cw+cwmr+cwml;
    $("#popup_layer").css("width", width);

    if (!popupcentered) {
        center_popup();
    }
    
    $("#popup_layer").css("visibility", "visible");
    $("#popup_layer").each(function() {
        $(this).fadeIn("fast");
    });
}

function set_popup_content(content)
{
    $("#popup_container").each(function() {
        $(this).html(content);
    });
}

function fade_popup(color, time)
{
    time = typeof(time) != 'undefined' ? time : 1000;
    $("#popup_close").each(function() {
        $(this).css("visibility", "hidden");
    });
    $("#popup_layer").each(function() {
        var c = "#D0FF76";
        if (color == "red") {
            c = "#FF9999";
        }

        var myColors = [{ param:'background-color', cycles: "1", isFade: false, colorList:["#F1F1F1", c] }];
        $(this).colorBlend(myColors);

        $(this).oneTime(time, "popuptimer", function(i) {
            $(this).fadeOut();
            $(this).oneTime(500, "popuptimer2", function(i) {
                close_popup();
            });
        });
    });
}
    
function close_popup()
{
    hide_throbber();
    $("#popup_close").each(function() {
        $(this).css("visibility", "hidden");
    });
    $("#popup_layer").each(function() {
        $(this).css("visibility", "hidden");
    });
}

function center_popup()
{
    var l = $("#popup_layer");
    var wh = $(window).height();
    var ww = $(window).width();
    var lh = $(l).height();
    var lw = $(l).width();

    var newtop = (wh-lh)/2;
    var newleft = (ww-lw)/2;

    $("#popup_layer").css("top", newtop);
    $("#popup_layer").css("left", newleft);
    popupcentered = true;
}

function resize_popup()
{
    // Adjust height to fit contents
    var lh = $("#popup_layer").height();
    var ch = $("#popup_content").height();
    var chmt = parseInt($("#popup_content").css("margin-top"));
    var chmb = parseInt($("#popup_content").css("margin-bottom"));
    height = ch+chmt+chmb;
    $("#popup_layer").css("height", height);

    // Adjust width to fit contents
    var lw = $("#popup_layer").width();
    var cw = $("#popup_content").width();
    var cwmr = parseInt($("#popup_content").css("margin-right"));
    var cwml = parseInt($("#popup_content").css("margin-left"));
    width = cw+cwmr+cwml;
    $("#popup_layer").css("width", width);
}

function resize_child_popup()
{
    // Adjust height to fit contents
    var lh = $("#child_popup_layer").height();
    var ch = $("#child_popup_content").height();
    var chmt = parseInt($("#child_popup_content").css("margin-top"));
    var chmb = parseInt($("#child_popup_content").css("margin-bottom"));
    height = ch+chmt+chmb;
    $("#child_popup_layer").css("height", height);

    // Adjust width to fit contents
    var lw = $("#child_popup_layer").width();
    var cw = $("#child_popup_content").width();
    var cwmr = parseInt($("#child_popup_content").css("margin-right"));
    var cwml = parseInt($("#child_popup_content").css("margin-left"));
    width = cw+cwmr+cwml;
    $("#child_popup_layer").css("width", width);
}

function display_child_popup(h)
{
    $("#child_popup_layer").css("opacity", "1.0");
    $("#child_popup_layer").css("display", "block");
    $("#child_popup_layer").css("visibility", "visible");
    //resize_child_popup();

    if (!childpopupcentered) {
        $("#child_popup_layer").center();
    }

}

function set_child_popup_content(content)
{
    $("#child_popup_container").each(function() {
        $(this).html(content);
    });
}

function fade_child_popup(color, time)
{
    time = typeof time !== 'undefined' ? time : 1000;
    $("#child_popup_layer").each(function() {
        var c = "#D0FF76";
        if (color == "red") {
            c = "#FF9999";
        }

        var myColors = [{ param:'background-color', cycles: "1", isFade: false, colorList:["#F1F1F1", c] }];
        $(this).colorBlend(myColors);

        $(this).oneTime(time, "child_popuptimer", function(i) {
            $(this).fadeOut();
            $(this).oneTime(500, "child_popuptimer2", function(i) {
                close_child_popup();
                
                // This is needed to reset other child_popups backgrounds
                $(this).css('background-color', $("#leftnav", parent.document).css("background-color"));
            });
        });
    });
}

function close_child_popup()
{
    hide_throbber();
    $("#child_popup_layer").css("visibility", "hidden");
}

function center_child_popup()
{
    $("#child_popup_layer").center();
    childpopupcentered = true;
}

// Content throbbers
function center_content_throbbers()
{
    $('#throbber').center(false);
}

/**
 * Converts the given data structure to a JSON string.
 * Argument: arr - The data structure that must be converted to JSON
 * Example: var json_string = array2json(['e', {pluribus: 'unum'}]);
 *          var json = array2json({"success":"Sweet","failure":false,"empty_array":[],"numbers":[1,2,3],"info":{"name":"Binny","site":"http:\/\/www.openjs.com\/"}});
 * http://www.openjs.com/scripts/data/json_encode.php
 */
function array2json(arr) {
    
    var parts = [];
    var is_list = (Object.prototype.toString.apply(arr) === '[object Array]');

    for(var key in arr) {
        var value = arr[key];
        if(typeof value == "object") { //Custom handling for arrays
            if(is_list) parts.push(array2json(value)); /* :RECURSION: */
            else parts[key] = parts.push('"' + key + '":' + array2json(value)); /* :RECURSION: */
        } else {
            var str = "";
            if(!is_list) str = '"' + key + '":';

            //Custom handling for multiple data types
            if(typeof value == "number") str += value; //Numbers
            else if(value === false) str += 'false'; //The booleans
            else if(value === true) str += 'true';
            else str += '"' + value + '"'; //All other things
            // :TODO: Is there any more datatype we should be in the lookout for? (Functions?)

            parts.push(str);
        }
    }
    var json = parts.join(",");
    
    if(is_list) return '[' + json + ']';//Return numerical JSON
    return '{' + json + '}';//Return associative JSON
}

function setTooltip(btn, message) {
    $(btn).tooltip('hide')
        .attr('data-original-title', message)
        .tooltip('show');
}

function hideTooltip(btn) {
    setTimeout(function() {
        $(btn).tooltip('hide');
    }, 2000);
}

// jQuery additions

jQuery.fn.center = function(parent) {
    if (parent) {
        parent = this.parent();
    } else {
        parent = window;
    }
    this.css({
        "position": "absolute",
        "top": ((($(parent).height() - this.outerHeight()) / 2) + $(parent).scrollTop() + "px"),
        "left": ((($(parent).width() - this.outerWidth()) / 2) + $(parent).scrollLeft() + "px")
    });
    return this;
}

function flash_message(msg, type, fade) {
    var fade = typeof(fade) != 'undefined' ? fade : false;
    var msg_type = type;
    var valid_types = ['info','success','error','warning'];
    if (valid_types.includes(msg_type) === false) {
        msg_type = 'info'; 
    }

    var html = '<div id="head-msg" class="' + msg_type + '" style="display: block;"><span class="msg-text" style="padding-top: 3px;">' + msg + '</span><span class="msg-close tt-bind" onclick="$(\'#head-msg\').fadeOut(300);" title="Dismiss" data-placement="left"><i class="fa fa-times"></i></span><div class="clear"></div></div>';

    if ($('.enterprisefeaturenotice').length == 0) {
        $('body.child').prepend(html);
    } else {
        var enterprise_height = $('.enterprisefeaturenotice.maincontent').outerHeight();

        if ($('#compensator').length == 0) {
            $('.enterprisefeaturenotice').after(html);
            $('.enterprisefeaturenotice').after("<div id='compensator' style='height:" + enterprise_height + "px; display: block; z-index: 9999999;'></div>");
        } else {
            if ($('#compensator').length == 0) {
                $('.enterprisefeaturenotice').after(html);
            } else {
                $('#compensator').after(html);
            }
        }
    }

    if (fade === true) {
        $('#head-msg').delay(2500).fadeOut(1000);
    }
}

function js_html_encode(str) {

    if (typeof str !== 'undefined') {
        return $("<div>").text(str).html();
    }

    return "";
}

function js_html_decode(str) {

    if (typeof str !== 'undefined') {
        return $("<div>").html(str).text();
    }

    return "";
}

// the keepalive variable is a global default and is set in page-parts.inc.php
function set_keepalive(updated_keepalive = false) {
    keepalive = updated_keepalive
}

// converts RGBA to RGB. 
// Input should be a rgba string (ex: 'rgba(0,0,0,0)'). Outputs a RGB string
function rgbaToRGB(rgbaStr) {
    // ignores background color
    rgba = rgbaStr.match(/\d+/g).map(Number);
    rgb = [ Math.round((rgba[3] * (rgba[0] / 255))),
            Math.round((rgba[3] * (rgba[1] / 255))),
            Math.round((rgba[3] * (rgba[2] / 255))) ];
    return 'rgb('+rgb[0]+','+rgb[1]+','+rgb[2]+')';
}