(function($) {
    //============================================================
	
    // document ready
    $(function() {
        
        /** 
         * auto rotate hero gallery
         */
        if ($('#gallery_type').length && $('#gallery_type').val() == 'campaign') {
            setInterval(function() {
                loadGalleryItem('', 'right');
            }, 6000);
        }
        
        $('a.film-thumbnail').mouseover(function() {
            var videoData = $(this).data('item');
        
            if ($('a.big-play').attr('title') !== videoData.title) {
                $('.gallery-wrapper').animate({
                    opacity: 0
                }, {
                    duration: 500, 
                    queue: false, 
                    complete : function() { 
                        var html = '<img class="big-poster" src="' + videoData.image + '" alt="' + videoData.title +'" />' + 
                        '<a class="big-play" href="' + videoData.url + '" title="' + videoData.title + '">' + 
                        '<img src="style/assets/ui/play-big.png" class="big-play"/>' +
                        '</a>';
                    
                        $(this).html(html);
                        
                        $('.featured-video-title').html('Featured video: ' + videoData.title);
                        
                        $('.big-poster').load(function() {
                            $('.gallery-wrapper').animate({
                                opacity: 1
                            }, {
                                duration: 500, 
                                queue: false
                            });
                        });
                    
                
                    }
                });
            }
                       
        });
        
        /**
         * Smooth scrolling implementation (for hash links)
         */ 
        $('a[href*=#]').each(function() {
            $(this).click(function(event) {
                var target = this.hash;
                
                if (target) {
                    // var navigationOffset = $('#page-header').outerHeight() + $('#site-header').outerHeight();
                    var navigationOffset = 0;
                    var targetOffset = $(this.hash).offset().top;
                    var relativeOffset = targetOffset - navigationOffset;
                    event.preventDefault();                  
                    $('body, html').animate({
                        scrollTop: relativeOffset                        
                    }, 600, function() {
                        //location.hash = target;
                        });
                }
            });
        });

        /**
         * Profile template, avatar list
         */
        if ($('ul.avatar-list')) {
            $('ul.avatar-list li a').click(function() {
                $('ul.avatar-list li a input').removeAttr('checked');
                $(this).children('input').attr('checked', 'checked');
            });
        }

        /*
         * Bind the top navigation large arrows
         * to the loadGalleryItem event
         */
        $('.topnav-left').click(function() {
            loadGalleryItem('', 'left');
        });
        
        $('.topnav-right').click(function() {
            loadGalleryItem('', 'right');
        });
        /*
         * Configure the fancybox plugin
         * Add a callback function for title formatting
         */
        $(".fancybox").fancybox({
            'titlePosition'	: 'inside',
            'overlayColor' : '#000000',
            'overlayOpacity' : 0.7,
            'padding' : 0,
            'margin' : 50,
            'transitionIn'	: 'fade',
            'transitionOut'	: 'none',
            'titleFormat' : function(title, currentArray, currentIndex, currentOpts) {
                var obj = $(currentArray[0]);
                var description = $(obj).attr('data-description')
                var html = title + '<div class="fancybox-title-description">' + description + '</div>';
                
                return html;
            }
        });
        
        if ($('.bar-menu ul').length) {
            /*
             * clone the last item and prepend it at the start of the list
             * shift the list with the width of an item
             * useful trick for scrolling the list both sides
             * 97px is the width of a <li>
             */
            $('.bar-menu ul').css('width', '679px');
            $('.bar-menu ul').css('margin-left', '-97px');
            $('.bar-menu ul').prepend($('.bar-menu ul li:last').clone().addClass('dummy'));
            
            $('.bar-menu ul li').live('click', (function() {
                loadGalleryItem($(this).data('parent'));
            }));
            /**
             * Disable the thumbnail links (were enabled for non-js users)
             * Keep thumbnail links on when the gallery contains campaign items
             * Hover functionality for gallery items if they represent campaigns
             */
            if ($('#gallery_type').val() == 'campaign') {
                $('.bar-menu ul li').live('hover', (function() {
                    if (!$(this).hasClass('active')) {
                        loadGalleryItem($(this).data('parent'));
                    }
                }));
            } else {
                $('.bar-menu ul li a').attr('href', 'javascript:;');
            }
        }
        /*
         * Featured section functionality
         * for the Homepage
         * When the mouse cursor hovers above a thumbnail
         * the main large image will change its source, title and link
         */
        if ($('.featured-thumb').length) {
            $('.featured-thumb').hover(function() {
                var parentImage = $(this).parents('.media-panel').find('.media-large img');
                var parentLink = $(this).parents('.media-panel').find('.media-large a');
                var parentTitle = $(this).parents('.media-panel').find('.media-large a span.featured-title');
                $(parentImage).attr('src', $(this).attr('data-parent-image'));
                $(parentLink).attr('href', $(this).attr('data-parent-link'));
                $(parentTitle).html($(this).attr('data-parent-title'));
            });
        }
        
        //------------------------------------------------------------
        // SIGN IN/UP FORM
		
        // Login/Logout top menu event binding
        $('.logout-link').click(function(){
            $('#login-action').val('logout');
            $('#login-form').submit();
        });
        
        // get the site header and profile area
        var $siteHeader = $('#site-header'),
        siteHeaderHeight = $siteHeader.outerHeight(),
        $profileArea = $('#profile'),
        profileAreaHeight = $profileArea.outerHeight(),
        profileAreaState = 'closed';
		
        // move/style the profile area
        $profileArea
        .addClass('profile-top')
        .css({
            position: 'fixed',
            top: '25%',
            opacity: 0,
            zIndex: 200,
            display: 'none'
        });
		
        // profile area open/close settings
        var profileAreaFadeSpeed = 600;
		
        // make #profile hash links open/close the form
        var $profileAreaToggleLinks = $('a[href=\'#profile\']').bind('click', function(e) {
			
            if (profileAreaState == 'open') {
                profileAreaState = 'closed';
                document.location.hash = '';
                $profileArea.animate({
                    top: '15%', 
                    opacity:0
                }, {
                    duration: profileAreaFadeSpeed/2, 
                    queue: false, 
                    complete: function(){
                        $profileArea.css({
                            top: '25%',
                            display: 'none'
                        });
                    }			
                });
				
            }
            else {
                profileAreaState = 'open';
                document.location.hash = 'profile';
                $profileArea.css({
                    display: 'block'
                });
                $profileArea.animate({
                    top: '20%', 
                    opacity:1
                }, {
                    duration: profileAreaFadeSpeed, 
                    queue: false
                });
            }
			
            // prevent default
            e.preventDefault();
			
        });
		
        // open the profile link if required
        if (document.location.hash == '#profile' || document.location.hash == 'profile') {
            $profileAreaToggleLinks.eq(0).trigger('click');
        }
        
        // news hero section, title span hover effects
        $('.news-hero-images a.main-image, .news-hero-images a.other-image').hover(
            function() {
                $(this).children('span').slideDown(400); 
                $(this).children('img').animate({
                    opacity : 1
                }, {
                    duration : 400
                }); 
            },
            function() {
                $(this).children('span').slideUp(400);
                $(this).children('img').animate({
                    opacity : 0.7
                }, {
                    duration : 400
                }); 
            }
            );
    });
	
//============================================================
})(jQuery);
/*
 * Main hero gallery functionality
 * Toggles the .active class base on the displayed image
 * Properly loads the first/last item if the gallery has just finished/started
 * Uses a fade out/in animation while switching between images
 */
function flipGalleryItem(direction, itemName) {
    var galleryItems = $('.gallery-container .gallery-item');
    var selectedItem = $('.gallery-container .active');
    var nextItem = {};
    
    if (itemName) {
        nextItem = $('#' + itemName);
    }
    
    for (var i = 0; i < galleryItems.length; i++) {
        if ($(galleryItems[i]).attr('id') === $(selectedItem).attr('id')) {
            if (!nextItem.length) {
                if (direction == 'right') {
                    if (i < galleryItems.length - 1) {
                        nextItem = $(galleryItems[i + 1]);
                    } else {
                        nextItem = $(galleryItems[0]);
                    }
                } else {
                    if (i > 0) {
                        nextItem = $(galleryItems[i - 1]);
                    } else {
                        nextItem = $(galleryItems[galleryItems.length - 1]);
                    }
                }
                
                itemName = $(nextItem).attr('id');
            }
             
            $(selectedItem).animate({
                opacity: 0
            }, {
                duration : 500, 
                queue : false, 
                complete : function() {
                    $(galleryItems).removeClass('active');
                    $(nextItem).css('opacity', 0);
                    $(nextItem).addClass('active');
                    $(nextItem).animate({
                        opacity: 1
                    }, {
                        duration : 500, 
                        queue : false
                    });
                }
            });
                
            break;
        }
    }
    
    return itemName;
}
/*
 * The main gallery function
 * This is the function which is binded to the arrow images/hero thumbnails
 */
function loadGalleryItem(itemName, direction) {
    itemName = flipGalleryItem(direction, itemName);

    var galleryHtml = '';
    
    /**
     * Temporarely disabled the dinamic text
     * functionality
     */
    if ($('#gallery_type') && ($('#gallery_type').val() == 'dynamic' || $('#gallery_type').val() == 'campaign')) {
        $('.gallery-text-container').children().each(function() {
            if ($(this).data('parent') == itemName) {
                galleryHtml = $(this).html();
            }  
        });
    
        if (galleryHtml) {
            $('#gallery-text').html(galleryHtml);
        }
    }
    
    
    scrollThumbnailGallery(direction, itemName);
}
/*
 * Thumbnail Gallery functionality
 * If there are less than 5 thumbnails, it only toggles an .active class for 
 * the current item
 * If there are at least 5 thumbnails, it simulates a scrollable effect by
 * animating the thumbnail list  
 */
function scrollThumbnailGallery(direction, itemName) {
    var listVisibleItems = 5;
    
    $('.bar-menu ul li.active').removeClass('active');
    $('.bar-menu ul li').each(function() {
        if ($(this).data('parent') == itemName) {
            $(this).addClass('active');
        }  
    });
    
    if (direction) {
        if ($('.bar-menu ul li:not(.dummy)').length > listVisibleItems) {
            if (direction == 'left') {
                $('.bar-menu ul').animate({
                    marginLeft : 0
                }, 1000, function() {
                    $('.bar-menu ul li:last').remove();
                    $('.bar-menu ul li').removeClass('dummy');
                    $('.bar-menu ul').prepend($('.bar-menu ul li:last').clone().addClass('dummy'));
                    // reset list margin
                    $(this).css('margin-left', '-97px');
                }); 
            } else {
                // move the first item to the end of the list
                $('.bar-menu ul').append($('.bar-menu ul li:eq(1)').clone());
                console.log(1);
                $('.bar-menu ul').animate({
                    marginLeft : '-194'
                }, 1000, function() {
                    $('.bar-menu ul li:first').remove();
                    // reset list margin
                    $(this).css('margin-left', '-97px');
                });
            }
        }
    }
}

function getItemIndex(itemName) {
    var index = 0;
    $('.bar-menu ul li:not(.dummy)').each(function(idx) {
        if ($(this).data('parent') == itemName) {
            index = idx;
        }  
        return;
    });
    
    return index;
}
    
