jQuery(document).ready(function() {
  var postWidth = jQuery(".featureStoryPost").width();
  var totalContentWidth = parseFloat((postWidth + 20) * 5);
  var slideLeft = postWidth + 20;
  var contentLeft = jQuery(".featureStoryContent").position();
  var intval = "";
  var rightClicks = 0;
  
  jQuery(".stepcarousel").css({
    "overflow": "hidden"
  });
  jQuery(".featureStoryPost").css({
    'float': 'left'
  });
  jQuery(".featureStoryContent").css({
    'width': ''+ totalContentWidth +'px'
  });
  
  slideLeft = '-='+ slideLeft +'px';
  
  function startInterval() {
    if(intval == "") {
      intval = setInterval(function() {
				if(rightClicks < 4 && contentLeft.left > -((postWidth + 20) * 4)) {
		      jQuery('.featureStoryContent').animate({
		        left: slideLeft
		      }, 1500, function() {
		        contentLeft = jQuery('.featureStoryContent').position();
		      });
					rightClicks++;
		    } else {
		      jQuery('.featureStoryContent').stop().queue("fx", []).animate({
		        left: '0px'
		      }, 1500, function() {
		        contentLeft = jQuery('.featureStoryContent').position();
		      });
		      rightClicks = 0;
		    }
      }, 5000);
    }
  }
  
  function stopInterval() {
    if(intval !== "") {
      clearInterval(intval);
      intval = "";
			jQuery('.featureStoryContent').queue("fx", []);
    }
  }
  
  startInterval();
  
  jQuery('.scrollLeft').click(function() {
    rightClicks--;
    if(rightClicks < 0) {
      rightClicks = 5 + rightClicks;
    }
    stopInterval();
    
    if(contentLeft.left < 0) {
      jQuery('.featureStoryContent').animate({
        left: '+='+ (postWidth + 20) +'px'
      }, 1500, function() {
        contentLeft = jQuery('.featureStoryContent').position();
        if(contentLeft.left > 0) {
          jQuery('.featureStoryContent').stop().animate({
            left: ''+ -((postWidth + 20) * 4) +'px'
          }, 0, function() {
            contentLeft = jQuery('.featureStoryContent').position();
            rightClicks = 5;
          });
        }
      });
    } else {
      jQuery('.featureStoryContent').animate({
        left: ''+ -((postWidth + 20) * 4) +'px'
      }, 1500, function() {
        contentLeft = jQuery('.featureStoryContent').position();
        rightClicks = 5;
      });
    }
    
    startInterval();
  });
  
  jQuery('.scrollRight').click(function() {
    rightClicks++;
    stopInterval();
    
    if(rightClicks <= 4) {
      jQuery('.featureStoryContent').animate({
        left: slideLeft
      }, 1500, function() {
        contentLeft = jQuery('.featureStoryContent').position();
      });
    } else {
      jQuery('.featureStoryContent').stop().queue("fx", []).animate({
        left: '0px'
      }, 1500, function() {
        contentLeft = jQuery('.featureStoryContent').position();
      });
      rightClicks = 0;
    }
    
    startInterval();
  });
});
