window.unit7 = window.unit7 || {}

if (window.jQuery)
    (function ($) {
        
        if ($.browser.msie) {
            $('html').addClass('ie');
        }

        /* ========== Main Navigation Module ========== */

        var nav = unit7.mainNavigation = {
            fadeTo : .5,

            speed : 200,
            
            init : function () {
                var selector = nav.getSelector();

                $(selector).click(function (ev) {
                    ev.preventDefault();

                    $('#menu-main-navigation > li.current-menu-item')
                        .removeClass('current-menu-item');

                    nav.activate(this);
                });

                $('#main-nav').hover(
                    function (ev) {
                        // $('#menu-main-navigation > li').stop().fadeTo(nav.speed, 1);
                    },

                    nav.fade
                );

                nav.fade();
            },

            getSelector : function () {
                var selector = '';
                
                // We only want to apply on "Main" templates
                selector += 'body.page-template-template-main-php';

                // We care only about the first 5 items (zero indexed)
                selector += ' #menu-main-navigation > li:lt(5)';

                // Only immediate child anchors
                selector += ' > a';

                return selector;
            },

            activate : function (navItem, subItem) {

                // Direct jQuery Instance
                if (typeof navItem === 'function') {
                    var target = navItem;
                }

                // The page number
                else if (typeof navItem === 'number') {
                    var target = $('#menu-main-navigation > li:nth-child(' + (navItem + 1) + ')');
                }

                // The anchor from a click event
                else if (navItem.nodeName && navItem.nodeName === 'A') {
                    var target = $(navItem).parent();
                }

                // The target LI
                else if (navItem.nodeName && navItem.nodeName === 'LI') {
                    var target = $(navItem);
                }

                // Clobber the original
                $('#menu-main-navigation > li.current-menu-item')
                    .removeClass('current-menu-item');

                // Apply to the current LI
                target.addClass('current-menu-item');

                // Sub Navigation
                if (typeof subItem !== 'undefined') {
                    target.find('ul > li.current-menu-item').removeClass('current-menu-item');
                    target.find('ul > li:nth-child(' + (subItem + 1) + ')').addClass('current-menu-item');
                }
            },

            fade : function () {
                return;
            }
        };

        // FIXME: Hacking the URI to enable custom post types triggering
        // BUGFIX: Case studies hilight the wrong nav items...
        $(function () {
            if ( /^\/people/.test(window.location.pathname) || /^\/(.*)\/people\/(.*)/.test(window.location.pathname) ) {
				$('#menu-main-navigation .current_page_parent').removeClass('current_page_parent');
				nav.activate(1,0);
			}
            else if ( /^\/case\-studies/.test(window.location.pathname) || /^\/(.*)\/case\-studies\/(.*)/.test(window.location.pathname) ) {
                $('#menu-main-navigation .current_page_parent').removeClass('current_page_parent');
                nav.activate(3,1);
            }
        });

        $(nav.init);
        
        /* ========== Hero Rotator Module ========== */
        
        var hr = unit7.heroRotator = {
            speed: 500,
            width: 772,
            pages: 1,
            container: null,
            cursor: 0,
            data: null,
            
            gotoPage : function (pageNumber, dontAnimate) {
                var selector, slug;

                if (pageNumber < 0) {
                    pageNumber = hr.pages - 1;
                }
                else if (pageNumber >= hr.pages) {
                    pageNumber = 0;
                }

                hr.cursor = pageNumber;
                
                try {
                    slug = unit7.heroRotator.data.slugs[hr.cursor];
                }
                catch (e) {
                    slug = 'home';
                }

                dontAnimate = !!dontAnimate;
                selector = {
                    left: (hr.cursor * hr.width) * -1
                };

                if (dontAnimate === true) {
                    hr.container.css(selector);
                }
                else {
                    hr.container.animate(selector, hr.speed);
                }
                
                mod.render(slug);
            },

            prev : function () {
                hr.gotoPage(hr.cursor - 1);
            },

            next : function () {
                hr.gotoPage(hr.cursor + 1);
            },

            getData : function () {
                return null;
            },
            
            init : function () {
                // Capture the data
                // Note: The getData method is overwritten during page load
                hr.data = hr.getData();

                // Make sure the width is accurate
                hr.width = $('#hero-rotator').width();

                // Count the number of pages
                hr.pages = $('#hero-rotator article').size();

                // Init the masked container
                hr.container = $('#hero-rotator .content-container');

                // Set the width of the container
                hr.container.width(hr.width * hr.pages);

                // Set the real cursor and load
                try {
                    hr.cursor = $.inArray(hr.data.currentPage.data.post_name, hr.data.slugs);
                }
                catch (e) {
                    hr.cursor = 0;
                }
                hr.gotoPage(hr.cursor, true);

                // Previous Button
                $('#hero-rotator menu .prev').click(function (ev) {
                    ev.preventDefault();
                    hr.prev();
                    nav.activate(hr.cursor, 0);
                });

                // Next Button
                $('#hero-rotator menu .next').click(function (ev) {
                    ev.preventDefault();
                    hr.next();
                    nav.activate(hr.cursor, 0);
                });

                // Navigation Clicks
                $(nav.getSelector()).click(function (ev) {
                    var pos;

                    ev.preventDefault();
                    pos = $(this).parent().prevAll('li').length;
                    hr.gotoPage(pos);
                });

            }
        };

        /* ========== Page Modules ========== */
        
        var mod = unit7.pageModules = {
            template: null,
            data: null,
            modules: null,
            enabled: false,
            
            render : function (pageSlug) {
                if (!mod.enabled) return;
                
                var items = $('#module-list .grid_8'),
                    size = items.size(),
                    counter = 0;
                    
                    items.fadeOut(200, function () {
                    counter += 1;
                    
                    if (counter === size) {
                        $(mod.modules[pageSlug]).each(function () {
                            $(this).fadeOut(10, function () {
                                $(this).appendTo('#module-list').fadeIn(200);
                            });
                        });
                    }
                });
            },
            
            init: function () {
                // ===== Load the module data ==========

                var pageData, currentPage;

                mod.data = {};
                mod.modules = {};
                
                try {
                    pageData = hr.getData().pages;
                }
                catch (e) {
                    return;
                }

                // ===== Prevent unwanted initialization on non-main pages =====

                currentPage = document.location.pathname.replace(/[^a-z0-9\-]/ig, '');
                mod.enabled = !!pageData[currentPage] || currentPage === '';

                // ===== Prepare the module data containers =====

                for (var slug in pageData) {
                    mod.data[slug] = pageData[slug].related;
                    mod.modules[slug] = [];
                }

                // ===== Create the template ==========

                mod.template = $('#module-list .content-container').get(0);
                mod.template = $(mod.template).clone();

                // ===== Generate the modules ==========

                var slug, related, i, l, module;

                for (slug in mod.data) {
                    related = mod.data[slug];
                    
                    for (i = 0, l = related.length; i < l; i++) {
                        if (jQuery.browser.msie) {
                            module = mod.createModuleIE(i, related);
                        }
                        else {
                            module = mod.createModule(i, related);
                        }

                        mod.modules[slug].push(module);
                    }
                }
            },
            
            createModuleIE : function (i, related) {
                var module = '<div class="grid_8 content-container';

                // Set up the class names
                switch (i) {
                    case 0:
                        module += ' alpha';
                    break;

                    case 3:
                        module += ' omega';
                    break;
                }
                
                module += '"><article class="related-module"><h2><a href="' + related[i].heading.href + '">';
                module += related[i].heading.title + '</a></h2><figure>';


                // Set the artwork
                if (related[i].artwork) {
                    module += '<a style="height:102px;" href="'+ (related[i].permaLink) +'"><img src="'+related[i].artwork[0]+'" width="232" /></a>';
                }

                // Set the sub-heading
                module += '<figcaption><h3>'+(related[i].subHead)+'</h3>';

                // Set the exceprt
                module += '<p>'+(related[i].data.post_excerpt)+'</p></figcaption></figure>';

                // Set the CTA link
                module += '<menu><a href="'+related[i].permaLink+'">Find out more</a></menu></article></div>';

                return $(module);
            },
            
            createModule : function (i, related) {
                var module = mod.template.clone();

                // Set up the class names
                switch (i) {
                    case 0:
                        module.addClass('alpha');
                        module.removeClass('omega');
                    break;

                    case 3:
                        module.removeClass('alpha');
                        module.addClass('omega');
                    break;

                    default:
                        module.removeClass('alpha');
                        module.removeClass('omega');
                    break;
                }

                // Set the heading
                module.find('> article h2 a')
                    .attr('href', related[i].heading.href)
                    .text(related[i].heading.title);

                // Set the artwork
                if (related[i].artwork) {
                    module.find('> article figure a')
                        .attr('href', related[i].permaLink);
                    module.find('> article figure a')
                        .find('> img').attr('src', related[i].artwork[0]);
                }
                else {
                    module.find('> article figure a').remove();
                }

                // Set the sub-heading
                module.find('> article figure figcaption h3').text(related[i].subHead);

                // Set the exceprt
                module.find('> article figure figcaption p').text(related[i].data.post_excerpt);

                // Set the CTA link
                module.find('> article menu a').attr('href', related[i].permaLink);
                
                return module;
            }
        };
        
        window.onload = function () {
            hr.init();
            mod.init();
        };
        
    })
(window.jQuery);

