﻿/// <reference path="jquery-1.5.2.js" />

$(document).ready(function () {
    HRG.JQueryUI.Init();
    HRG.DynamicPanels.Init();
    HRG.PrimaryNav.Init();
    HRG.TaxonomyFilter.Init();
});

var _isEditing = false;
var HRG = {};

/*
* JQuery UI helper class
*/
HRG.JQueryUI =
{
    Init: function ()
    {
        HRG.JQueryUI.InitTabs();
        HRG.JQueryUI.InitCountryPickers();
    },

    InitTabs: function ()
    {
        $('#tabs').tabs();
    },

    InitCountryPickers: function ()
    {
        var pickerMenuWidth = 855;
        var numberOfColumns = 5;

        var headerCountryPicker = $('#header select.dropdown');
        headerCountryPicker.selectmenu({
            style: 'dropdown',
            menuWidth: pickerMenuWidth,
            positionOptions: {
                collision: "flip none"
            }
        });

        var footerCountryPicker = $('#pre-footer select.dropdown');
        footerCountryPicker.selectmenu({
            style: 'dropdown',
            menuWidth: pickerMenuWidth,
            positionOptions: {
                my: "left bottom",
                at: "left bottom",
                offset: "2 -26",
                collision: "flip none"
            }
        });

        HRG.JQueryUI.HideSelectCountryMoniker(headerCountryPicker);
        HRG.JQueryUI.HideSelectCountryMoniker(footerCountryPicker);

        HRG.JQueryUI.ForceMenuChoicesIntoColumns(headerCountryPicker, numberOfColumns);
        HRG.JQueryUI.ForceMenuChoicesIntoColumns(footerCountryPicker, numberOfColumns);
    },

    // Remove the "Select Country" moniker from the choice of options
    HideSelectCountryMoniker: function (countryPicker)
    {
        countryPicker.bind('selectmenuopen', function (event, ui)
        {
            if ($.data(countryPicker, 'selectCountryMonikerHidden') != true)
            {
                var countryPickerMenu = $('#' + countryPicker.attr('id') + '-menu');
                countryPickerMenu.find('li:first-child').detach();

                // Done - don't do it again
                $.data(countryPicker, 'selectCountryMonikerHidden', true);
            }
        });
    },

    // Move existing selections into several floating columns
    ForceMenuChoicesIntoColumns: function (countryPicker, cols)
    {
        countryPicker.bind('selectmenuopen', function (event, ui)
        {
            if ($.data(countryPicker, 'choicesAsColumns') != true)
            {
                var countryPickerMenu = $('#' + countryPicker.attr('id') + '-menu');

                // Calculate how many to allow per column for even distribution
                var choices = countryPickerMenu.find('li:visible');
                var itemsPerCol = Math.ceil(choices.length / cols);

                var col = 1; var item = 1; var newCol = false;
                var colHeight = 0; var maxColHeight = 0;
                choices.each(function ()
                {
                    // Add a column-specific CSS class to allow items to 
                    // appear as if they are floating in columns
                    $(this).addClass('column' + col);
                    item++;

                    // Starting a new column - bring it up inline with the rest using negative margins
                    if (newCol)
                    {
                        $(this).css('margin-top', colHeight * -1);

                        // Find the tallest column
                        if (colHeight > maxColHeight) maxColHeight = colHeight;
                        colHeight = 0;
                    }

                    // Sum the height of the current column
                    colHeight += $(this).height();

                    // New column detection
                    if (item > itemsPerCol)
                    {
                        newCol = true;
                        item = 1;
                        col++;
                    }
                    else
                    {
                        newCol = false;
                    }
                });

                // Force the height of the menu to adjust to the new configuration
                countryPickerMenu.height(maxColHeight);
                countryPicker.selectmenu('refreshPosition');
                countryPickerMenu.addClass('loaded');

                // Disable the dropdown when an option is selected, but re-enable on escape key press
                choices.find('a').bind('click', function () { countryPicker.selectmenu('disable'); });
                $(document).keyup(function (e) { if (e.keyCode == 27) countryPicker.selectmenu('enable'); });

                // Done - don't do it again
                $.data(countryPicker, 'choicesAsColumns', true);
            }
        });
    },

    // Add search textbox functionality into the dropdown
    //
    // JG 3-June-2011
    // Functionality incomplete, started this as proof of concept.  Initial
    // findings were that the jQueryUI selectmenu already responds to keypress
    // event which was stealing the input from the textbox
    AddSearchToSelectMenu: function (countryPicker)
    {
        countryPicker.bind('selectmenuopen', function (event, ui)
        {
            if ($.data(countryPicker, 'addSearchToSelectMenu') != true)
            {
                var countryPickerMenu = $('#' + countryPicker.attr('id') + '-menu');

                // Build the HTML required for the search and add it to the menu
                var searchHtml = '<li class="powersearch"><input type="text" id="' + countryPickerMenu.attr('id') + '-search" /></li>';
                countryPickerMenu.find('li:first-child').before(searchHtml);

                // Increase the height to accomodate the new row
                countryPickerMenu.height(countryPickerMenu.height() + countryPickerMenu.find('li.powersearch').height());

                // Attach search control events
                var searchBox = countryPickerMenu.find('li.powersearch input');
                searchBox
                .bind('keydown', function ()
                {
                    var txt = $(this).val();
                    if (txt)
                    {
                    }
                })
                .bind('focus', function ()
                {
                })
                .bind('blur', function ()
                {
                });

                // Done - don't do it again
                $.data(countryPicker, 'addSearchToSelectMenu', true);
            }
        });
    }
}


/*
* Dynamic tabbed panels
*
* Looks for designated web part zones and combines web parts within
* into a jQuery UI tabbed interface, one tab per web part
*/
HRG.DynamicPanels =
{
    Init: function ()
    {
        if (!_isEditing)
        {
            var webPartZone = $('.hrg-dynamicpanels');
            if (webPartZone.length > 0)
            {
                try
                {
                    // Port content from web parts into jQuery UI tabs
                    HRG.DynamicPanels.ConvertWebPartsToTabs(webPartZone);
                    $('#tabs').tabs();

                    // Finish the job - notify the container that we're done and remove all web parts
                    webPartZone.addClass('loaded');
                    webPartZone.find('table:first').remove();
                }
                catch (e)
                {
                    webPartZone.hide();
                }
            }
        }
    },

    ConvertWebPartsToTabs: function (webPartZone)
    {
        webPartZone.each(function ()
        {
            var count = 0;

            var webParts = webPartZone.find('.s4-wpTopTable');
            webParts.each(function ()
            {
                // Support a maximum of three tabs
                if (count < 3)
                {
                    var webPartTitle = $(this).find('h3.ms-WPTitle').text();
                    var webPartBody = $(this).find('.ms-WPBody').html();

                    HRG.DynamicPanels.AppendTab(
                        webPartTitle,
                        webPartBody,
                        webPartZone);
                }
                count++;
            });
        });
    },

    AppendTab: function (title, body, webPartZone)
    {
        var tabContainer = HRG.DynamicPanels.TabContainer(webPartZone);
        var nav = tabContainer.find('ul.nav');
        var content = tabContainer.find('div.content');

        // Uniquely identify each tab
        var tabId = nav.find('li').length;

        // Add a new tab top navigation item
        var navCss = (tabId == 0) ? 'ui-tabs-selected ui-state-active' : '';
        nav.append('<li class="ui-state-default ui-corner-top ' + navCss + '"><a href="#tab-' + tabId + '">' + title + '</a></li>');

        // Add the body content
        content.append('<div id="tab-' + tabId + '" class="clear ui-tabs-panel ui-widget-content ui-corner-bottom">' + body + '</div>');
    },

    TabContainer: function (webPartZone)
    {
        var elem = webPartZone.find('#tabs');
        if (elem.length > 0)
        {
            return elem;
        }
        else
        {
            return webPartZone.prepend('<div id="tabs" class="ui-tabs ui-widget ui-widget-content ui-corner-all"><ul class="nav clear ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all"></ul><div class="content"></div></div>')
        }
    }
}

/*
* Primary navigation animation and initialisation
*/
HRG.PrimaryNav =
{
    Init: function ()
    {
        var topNav = jQuery("#primary-nav");
        if (topNav.length > 0)
        {
            topNav.find("ul.root > li:last, ul.static > li:last").addClass("last");

            var topNavItems = topNav.find("ul.root > li");
            topNavItems.each(function ()
            {
                var topNavItem = jQuery(this);

                var subMenu = topNavItem.find('ul');
                if (subMenu.length > 0)
                {
                    // Setup the hover behaviour
                    var config = {
                        over: HRG.PrimaryNav.FlyoutHoverOver,
                        out: HRG.PrimaryNav.FlyoutHoverOut
                    };
                    topNavItem.hoverIntent(config);

                    // Show a down arrow on the menu item to denote that a sub-menu/flyout is available
                    topNavItem.addClass('flyout');
                }
            });
        }
    },

    FlyoutHoverOver: function ()
    {
        var topNavItem = $(this);
        topNavItem.addClass('hover');

        // Find sub menu and fade it in 
        var subMenu = topNavItem.find("ul");
        subMenu.fadeIn('fast');

        // Detect when the menu may be masked by the viewport and move accordingly
        if (jQuery('#header').width() < (topNavItem.position().left + subMenu.width()))
        {
            subMenu.addClass('overhanging');
        }
    },

    FlyoutHoverOut: function ()
    {
        var topNavItem = $(this);
        topNavItem.removeClass('hover');

        // Fade to 0 opacity
        var subMenu = topNavItem.find("ul");
        subMenu.fadeOut('fast');
    }
}


HRG.TaxonomyFilter =
{
    Init: function (container) {
        $("div.filter div.terms").each(function () {
            $(this).css("height", $(this).height());

            if ($(this).hasClass("on") == false)
                $(this).hide();
        });
    },


    Toggle: function (id) {
        var terms = this._GetGroupPanel(id);

        if ($(terms) != null) {
            if ($(terms).is(":visible")) {
                $(terms).slideUp("fast");
                $(id).children("div:first").removeClass("on");
            }
            else {
                $(terms).slideDown("fast");
                $(id).children("div:first").addClass("on");
            }
        }

        return false;
    },

    _GetGroupPanel: function (id) {
        var terms = $(id).parent().next();
        return $(terms).hasClass("terms") ? terms : null;
    }
}


//HRG.CQWPToolbar = {
//    HideSection: function (containerId, sectionText) {
//        var hideExpression = "#" + containerId + "_configureQuery div.UserSectionHead span";
//        alert(hideExpression);
//        $(hideExpression).filter(function () { return $(this).text() == "List Type"; }).parentsUntil('tr').hide();
//    }
//}


