$.widget('ui.bf_ctr_fade', {
   _init: function() {
      var self = this;
      var parent = $(this).parent();
      self.timer = null;

      $('> '+ self.options.selector, self.element ).click( function() {
         if( self.timer ) {
            clearTimeout( self.timer );
         }
      });

      $('ul.container-paging li').click( function() {
         var parent = $( this );
         var idx = parent.prevAll('li').length;

         $('> '+ self.options.selector, self.element ).hide();
         $('> '+ self.options.selector +':nth-child('+ ( idx + 1 ) + ')', self.element ).show();

         self.activate_nav( idx );

         if( self.timer ) {
            clearTimeout( self.timer );
         }
      });

      $('ul.container-paging li img').each( function() {
         var el = $(this);
         el.data('out',  el.attr('src') );
         el.data('over', el.attr('rel') );
      });

      $('.bf-ctr-fade-next' ).click( function() {
         self.next();
      });
      $('.bf-ctr-fade-prev').click( function() {
         self.next();
      });

      if( $('> '+ self.options.selector, self.element ).length > 1 ) {
         self.next();
      } else {
         $('> '+ self.options.selector, self.element ).addClass('on');
      }
   },

   next: function() {
      var self = this;
      var on = $('> '+ self.options.selector +'.on', self.element );
      if( !on.length ) {
         var next = $('> '+ self.options.selector +':first-child', self.element );
         next.addClass('on');
      } else {
         var next = on.next( self.options.selector ).hide();
         if( !next.length ) {
            next = $('> '+ self.options.selector +':first-child', self.element );
         }

         next.addClass('next').fadeIn( self.options.animation_speed, function() {
            on.hide().removeClass('on');
            next.addClass('on').removeClass('next');
         });
      }

      self.activate_nav( next.prevAll( self.options.selector ).length );

      if( self.timer ) {
         clearTimeout( self.timer );
      }
      self.timer = setTimeout( function() {
         self.next();
      }, self.options.panel_timeout );
   },

   activate_nav: function( idx ) {
      var self = this;
      $('ul.container-paging li img').each( function() {
         $(this).attr('src', $(this).data('out') );
      });

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

$.extend( $.ui.bf_ctr_fade, {
   defaults: {
      selector: 'div.featurette',
      panel_timeout: 5000,
      animation_speed: 'slow'
   }
});

