var bf_ctr_fade_timer = null;
var bf_ctr_fade_timeout = 6000;


function bf_ctr_fade( selector ) {
   var e = $( selector );

   $('> div.featurette', e ).click( function() {
      if( bf_ctr_fade_timer ) {
         clearTimeout( bf_ctr_fade_timer );
      }
   });

   $('#b_flash ul.columns-four li a').click( function() {
      var parent = $( this ).parent();
      var idx = parent.prevAll('li').length;

      $('> div.featurette', e ).hide();
      $('> div.featurette:nth-child('+ ( idx + 1 ) + ')', e ).show();

      bf_ctr_fade_activate_nav( idx );

      if( bf_ctr_fade_timer ) {
         clearTimeout( bf_ctr_fade_timer );
      }
   });

   $('#b_flash ul.columns-four li img').each( function() {
      var el = $(this);
      el.data('out',  el.attr('src') );
      el.data('over', el.attr('src').replace('_off', '_on') );
   });

   bf_ctr_fade_next( e );
}

function bf_ctr_fade_next( e ) {
   var on = $('> div.featurette.on', e );
   if( !on.length ) {
      var next = $('> div.featurette:first-child', e );
      next.addClass('on');
   } else {
      var next = on.next('div.featurette').hide();
      if( !next.length ) {
         next = $('> div.featurette:first-child', e );
      }

      next.addClass('next').fadeIn('slow', function() {
         on.hide().removeClass('on');
         next.addClass('on').removeClass('next');
      });
   }

   bf_ctr_fade_activate_nav( next.prevAll('div.featurette').length );

   bf_ctr_fade_timer = setTimeout( function() {
      bf_ctr_fade_next( e );
   }, bf_ctr_fade_timeout );
}

function bf_ctr_fade_activate_nav( idx ) {
   $('#b_flash ul.columns-four li img').each( function() {
      $(this).attr('src', $(this).data('out') );
   });

   var img = $('#b_flash ul.columns-four li:nth-child('+ ( idx + 1 ) + ') img');
   img.attr('src', img.data('over') );
}

$( function() {
   bf_ctr_fade('.bf-ctr-fade');
});


