

var AFRAME = {
  homeFeature: function() {
    var $feature 	= 	$('#home-feature'),
        $items 		= 	$feature.find('.featured-list'),
        itemCount 	= 	$items.children().length, //get number of featured items
        slideNav 	= 	'<ul class="featured-nav">'; 

    for(var i = 0; i < itemCount; i++) { //build featured nav buttons based on number of items
      var slideNum = i+1;
      slideNav += '<li';
      if(i === 0) {
        slideNav += ' class="current"';
      } else if (i === (itemCount - 1)) {
        slideNav += ' class="inactive"';
      }
      slideNav += '><a href="#'+slideNum+'">'+slideNum+'</a></li>';
     }
     slideNav += '</ul>';
     $feature.append(slideNav);

     var $featureNav = $feature.find('.featured-nav'),
         featureNavMargin = Math.floor($featureNav.width() / 2);

     $featureNav.css({
       marginLeft: '-'+featureNavMargin+'px',
       display: 'none',
       visibility: 'visible'
      }).fadeIn(250);

      var featureTimer = setInterval(timedRotate, 4000); //4 second switch

      function timedRotate() {
        var activePos = $featureNav.children('.current').prevAll().length + 1,
            nextItem;

        if(activePos === itemCount) {
          nextItem = 1;
        } else {
          nextItem = activePos + 1;
        }

        moveSlideshow(nextItem);
      }


     function moveSlideshow(pos) { 

      var $newNav = $featureNav.children('li:nth-child('+pos+')');

      if(!$newNav.hasClass('current')) {
         $newNav.siblings().removeClass('current');
         $newNav.addClass('current');

         $items.children('.current').fadeOut(350, function() {$(this).removeClass('current');});
         $items.children('li:nth-child('+pos+')').fadeIn(350, function() {$(this).addClass('current');});
       }
     }

     $featureNav.find('a').bind('click', function(e) {
       var newPos = $(this).parent().prevAll().length + 1;
       clearTimeout(featureTimer);
       moveSlideshow(newPos);
       e.preventDefault();
     });
  }
};

$(document).ready(function() {AFRAME.homeFeature();});

