$(document).ready(function() {
    $('#branding-bckgrnd').headerRotate();                                      // plugin to fade between all the images in the header
    $('.ngg-gallery-thumbnail a').fancybox({                                    // popup behaviour for the gallery pages
	titleShow: true,
        titlePosition: 'inside',
	titleFormat: function() {
            return $(this.orig).attr('alt');
	    //return '<a class="fullGalleryLink" href="/gallery/">View full gallery</a>';
	}
    });

    $('.ngg-gallery-video-thumbnail a').click(function() {
        $.fancybox({
            'padding'		: 0,
            'autoScale'		: false,
            'transitionIn'	: 'none',
            'transitionOut'	: 'none',
            'title'		: this.title,
            'width'		: 680,
            'height'		: 495,
            'href'		: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
            'type'		: 'swf',
            'swf'		: {
                'wmode'         : 'transparent',
                'allowfullscreen' : 'true'
            }
        });

        return false;
    });
    $('.archives').archiveScroller(10000);                                      // news articles in the RHC cyle through every few seconds
});

jQuery.fn.extend({

    /**
     * Scroll the recent news headlines in the RHC, and allow users to click
     * the mini nav buttons to jump between them
     * @param int scrollDelay
     * @return jQuery
     */
    archiveScroller: function(scrollDelay) {

        var scrollArticles = function(targetObject, targetIndex) {
            $('li',$(targetObject)).removeClass('selected');                    // remove the red selected dot

            //var scrollDistance = $('article',$(targetObject)).width();          // how wide is each article
            var scrollDistance = 160;

            $('.aside_set',$(targetObject)).animate(                            // animate the scroll_set for this archive
                {marginLeft: (targetIndex - 1)* -scrollDistance},
                500,
                function(){
                    $('li:nth-child('+targetIndex+')',$(targetObject)).addClass('selected');    // add the red dot back in
                }
            );
            
        };

        var doAutoscroll = function(targetObject) {
            if(!$(targetObject).hasClass('autoScrollingDisabled')) {            // if suto scrolling has not been disabled by a click
                //var scrollDistance = $('article',$(targetObject)).width();      // how far do we scroll for each articles
                var scrollDistance = 160;
                var scrollPosition = parseInt($('.aside_set',$(targetObject)).css('margin-left'));  // how far have we currently scrolled
                var currentIndex = Math.abs(scrollPosition / scrollDistance) + 1; // What element are we currently at
                var totalArticles = $('article',$(targetObject)).length;        // how many news articles are there?

                if(currentIndex >= totalArticles) {                             // if we're on the last article, start from the beginning
                    scrollArticles(targetObject,1);
                } else {                                                        // otherwise scroll to the next one
                    scrollArticles(targetObject, currentIndex+1);
                }
            }
        };

        $(this).each(function(){
            if($('article',$(this)).length > 1) {                               // only add the slide handler if there are more than 1 articles
                var dst = $(this);                                              // save a reference to each matching DOM elemet

                setInterval(doAutoscroll, scrollDelay, dst);                    // slide to next article every few seconds

                $('li a',$(dst)).bind('click',function(){                       // click handler for the small dots
                    $(dst).addClass('autoScrollingDisabled');                   // one an article is clicked on, autoscrolling should be turned off
                    var targetSlide = parseInt($(this).attr('href').substr(-1, 1)); // what article index should we jump to?

                    scrollArticles(dst,targetSlide);                            // do the animation
                    return false;
                });
            } else {
                $('ul',$(this)).remove();                                       // only 1 news article, just remove the nav
            }
        });

        return this;
    },

    /**
     * Loop through all the header images
     * @param Object params
     * @return jQuery
     */
    headerRotate: function(params) {
        
        if(typeof(params) == 'undefined') params = {};                          // ensure the params exists
        if(typeof(params.interval) == 'undefined') params.interval = 7000;      // fadey every 7 seconds
        if(typeof(params.delay) == 'undefined') params.delay = 0;               // by default, don't delay the start
        
        $(this).each(function(){
            var dst = this;
        
            var fadeOutIn = function() {
                $('img:last-child',dst).fadeOut('slow',function() {
                    var lastImage = $('img:last-child',dst).remove();
                    $(dst).prepend(lastImage);
                    $('img:nth-child('+penultimateElement+')',dst).show();
                });
            }
            
            var penultimateElement = $('img',dst).length - 1;
            $('img:last-child',dst).show();
            $('img:nth-child('+penultimateElement+')',dst).show();
            
            var setFadeTimer = function() {
                setInterval(fadeOutIn,params.interval);
            }
            
            if(params.delay > 0) {
                setTimeout(setFadeTimer, params.delay);
            } else {
                setFadeTimer();
            }
        });
	
        return this;
    }
});

/**
 * Fuck-up prevention; checks to see if the console exists before posting to it, so that console.log messages that are accidentally left in do not break a page when run live
 * Called "trace" as I have been doing a lot of AS3 today and I keep typing it anyway
 * @param message
 * @return void
 */
function trace(message) {
    if(typeof(console) != 'undefined' && typeof(console.log) == 'function') {
	console.log(message);
    }
}
