(function($){
    $(document).ready(function () {

        // Define global variables
        var isVisible = false;
        var isMouseOverUnifier = false;

        // Setup unifier
        setUnifierDefaults();

        // Handle the "see more" click
        $('#uni-more').click(function () {toggleUnifier();return false;});

        // Handle body click
        $('#unifier').hover(function () {
            isMouseOverUnifier = true;
        }, function () {
            isMouseOverUnifier = false;
        });

        $(document).click(function (e) {
            if (!isMouseOverUnifier) toggleUnifier('hide');
        });

        function toggleUnifier(option) {

            if (option) {
                if (option == 'show') show();
                if (option == 'hide') hide();
            } else {
                if (isVisible) hide();
                else show();
            }

            function show() {
                $('#uni-more').css('background-color', $('#uni-director').css('background-color'));
                $('#unifier-wrapper').slideDown(200);
                isVisible = true;
            }

            function hide() {
                $('#unifier-wrapper').fadeOut('fast');
                $('#uni-more').css('background-color', 'transparent');
                isVisible = false;
            }
        }
    });

    // Setup the Unifier Banner (according to #uni-banner-content width)
    function setUnifierDefaults() {

        // Get #uni-banner-content width
        var width = $('#uni-banner #uni-banner-content').width();

        // Calculatet #unifier and children's margins and sizes appropriately
        var unifierWidth = width - 2; // -2 for border
        var leftWidth = (unifierWidth <= 725) ? unifierWidth * .45  : ((unifierWidth <= 750) ? unifierWidth * .25 : unifierWidth * .3);
        var rightWidth = unifierWidth - leftWidth - 20 - 10; // -20 for padding, -10 for margin
        
        var siteColumns = (unifierWidth <= 725) ? 1 : 2;
        var siteWidth = 250;

        // Apply width changes
        $('#unifier-wrapper').width(unifierWidth);
        $('#uni-left').width(leftWidth - 2);
        $('#uni-right').width(rightWidth);
        var leftMargin = (rightWidth - (siteWidth * siteColumns)) / (siteColumns+1);
        $('.uni-site').css('margin-left', leftMargin);
        
        // Get height info
        $('#unifier-wrapper').show();
        var unifierHeight = $('#unifier').height();
        var rightHeight = $('#uni-right').height();
        $('#unifier-wrapper').hide();
        
        // Calculate and apply height changes
        var topMargin = (unifierHeight - rightHeight) / 2;
        $('#uni-right').css('margin-top', topMargin);
        $('#uni-left').height(unifierHeight - 20);
        
    }
})(jQuery)
