/**
 * jQuery Featured Story Viewer
 *
 * @version			0.1
 * @since			12/09/2010
 * @author			Chad Rempp
 *
 * Usage example:
 * -----------------------------------------------------------------------------
 *
 */
// Pass jQuery to a self executing function (closure) that maps it to the dollar
// sign so it can't be overwritten by another library in the scope of its
// execution.
;(function($) {
   $global = $(this);
   
   var methods = {
      init : function(options) {
         return this.each(function(){
            methods.options = $.extend({}, $.fn.featured.defaults, options);
            
            var $this = $(this),
                data = $global.data('featuredstory'),
                elements = $this.find('.'+methods.options.storyclass);
            
//console.log('found '+elements.length+' stories');
            
            // If the plugin hasn't been initialized yet
            if ( ! data ) {
               $global.data('featuredstory', {
                  current : 1,
                  count: elements.length,
                  clickedtimer: 0,
                  timer: null,
               });
               var data = $global.data('featuredstory');
            }
            
            // Calculate the height
            var maxHeight = parseInt(methods.options.minheight,10);
            elements.each(function(){
               thisHeight=parseInt($(this).height(),10);
               if (thisHeight > maxHeight) maxHeight = thisHeight+70;  // add 70 for image space
//console.log('m='+maxHeight+' h='+thisHeight);
            });
            
            // Build the navbar
            if (methods.options.buildnav){
               var nav = '<ul id="featuredStoryNav">';
               nav += '<li class="featuredStoryLink"><a href="#">Read Story&nbsp;<img src="/eeLayout/jewishjournal/images/webcontent/uparrow.png" width="10px" />&nbsp;</li>'
               nav += '<li>Preview:</li>'
					for (var i = 1; i <= $global.data('featuredstory').count; i++){
                   nav += '<li><a href="#" onclick="$(this).featured(\'go\', '+i+');return false;">'+i+'</a></li>'
               }
               nav += '<li class="last"><a href="#" onclick="$(this).featured(\'next\');return false;">next preview >> </a></li></ul>';
               $(this).append(nav);
            }
            
            var navHeight = $this.find('#featuredStoryNav').height();
//console.log('h='+maxHeight+' nav='+navHeight);
            elements.height(maxHeight+navHeight);
            
            // Attach story links as data to the div
            elements
               .find("a")
               .each(function(index,element){
                  $(element)
                     .data('link',$(element).attr('href'));
                     //.hide();
//console.log($(element).attr('href'));
               });
            
            // Hide all story divs, then show the first
            elements
               .hide()
               .first()
               .show();
               
            if (methods.options.rotate > 0){
               // Start timer
               data.timer = setInterval ( "$('*').featured('next')", methods.options.rotate*1000 );
               
               // All clicks in this widget cancel the timer.
               // In the future we should make this configurable
               $this.find('a').click(function(){
//console.log("clearing interval");
                  clearInterval($global.data('featuredstory').timer)
               });
            }
            
            // Assign the story link
            
            
            var link = elements.eq(0).find("a[rel='storylink']").hide().attr('href');
            $("#featuredStoryNav .featuredStoryLink a").attr('href',link);
         });
         
         
      },
      next : function( ) {
         methods.go($global.data('featuredstory').current+1);
      },
      prev : function( ) {
         methods.go($global.data('featuredstory').current-1);
      },
      go : function(page) {
         return $(this).each(function(){
            var data = $global.data('featuredstory'),
                elements = $('.'+methods.options.storyclass);
            
            // Cancel any timer
            if (data.timeout) clearTimeout(data.timeout);
            
            // Handle boundry conditions by wrapping around
            if (page > data.count) page = 1;
            if (page <= 0) page = data.count;
            
//console.log("go from "+data.current+" to "+page)
            
            elements
               .eq(data.current-1).fadeOut('slow', function(){
//console.log('done');
                  elements
                     .eq(page-1)
                     .fadeIn('slow');
               });
               
            data.current = page;
            
            // Assign the story link
            $("#featuredStoryNav .featuredStoryLink a").attr('href',elements.eq(page-1).find("a[rel='storylink']").attr('href'));
            
         });
      },
      timer : function(delay){
         if (methods.options.rotate > 0){
            // Set default delay time
            if (typeof delay == 'undefined') delay = methods.options.rotate;
            
            // next page
            methods.next();
            
            // Restart timer
            data = $global.data('featuredstory');
            
            data.timeout = setTimeout ( "$('*').featured('timer')", delay*1000 );
         }
      },
      destroy : function( ) {
         return this.each(function(){
            var $this = $(this),
                data = $global.data('featuredstory');
            // Namespacing FTW
            data.featuredstory.remove();
            $this.removeData('featuredstory');
          })
      },
   };
  
	$.fn.featured = function(method ) {
      $.fn.featured.defaults = {
         storyclass: 'featuredStoryWrap',
         buildnav:    true,
         minheight:   '320px',   //'320px',
         rotate:      3,         //  5  How many seconds before story rotation. 0=no autorotation
         // animation: 'normal',
      };
   
      
      
      // Method calling logic
      if ( methods[method] ) {
         return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
      } else if ( typeof method === 'object' || ! method ) {
         return methods.init.apply( this, arguments );
         
      } else {
         $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
      }
   };
	
})( jQuery );

