(function($) {

  window.application = {
    init: function() {
      application.activateCarousels();
      application.activateCarouselTimers();
      application.activateColorBox();
      application.activateExternalLinks();
    },

    activateCarousels: function() {
      $('.carousel nav a').live('click', function(event) {
        event.preventDefault();

        var action   = $(this),
            carousel = action.parents('.carousel');

        ( action.hasClass('right') ? application.slideCarouselLeft : application.slideCarouselRight )(carousel);

        return false;
      });
    },

    activateCarouselTimers: function() {
      setInterval(function() {
        application.slideCarouselLeft( $('#banners') );
      }, 15000);

      setInterval(function() {
        application.slideCarouselLeft( $('#platforms') );
      }, 5000);
    },

    slideCarouselLeft: function(carousel) {
      var item   = carousel.find('li:first-child'),
          margin = item.css('marginLeft');

      item.animate({ marginLeft: '-' + item.width() + 'px' }, function() {
        carousel.find('ul').append( item.detach() );
        item.css('marginLeft', margin);
      });
    },

    slideCarouselRight: function(carousel) {
      var item   = carousel.find('li:last-child'),
          margin = item.css('marginLeft');

      item.css({ marginLeft: '-' + item.width() + 'px' });
      carousel.find('ul').prepend( item.detach() );

      item.animate({ marginLeft: margin });
    },
    
    activateColorBox: function() {
      $('article.game').colorbox({
        iframe:     true,
        width:      '800px',
        height:     '600px',
        rel:        'games',
        current:    'Game {current} of {total}',

        href:  function() {
          return $(this).find('a').attr('href');
        },

        title: function() {
          var article     = $(this),
              title       = article.find('h4').text()
              description = article.find('img').attr('alt'),
              extract     = description.substr(0, 45);

          if(description.length > 45) extract = extract + '...';

          return "<strong>" + title + "</strong>: " + extract;
        }
      });
    },

    activateExternalLinks: function() { $("a[rel='external nofollow']").attr('target', '_blank'); }
  };

  $(application.init);

})(jQuery);
