/*
 * jQuery plugin adapted from original by Kao Saelee from nojitter
 adapted by sadie welsh for gdmag 
 *
 */
(function( $ ){

	$.fn.noJitterFeatures = function( options ) {
		
		var currentPage = 1,
			numPages = 0,
			intTransition = false;
		
		this.each(function() {
			var $this = $(this),
				curPageWidth, 
				pageDiff, 
				pageWidth = 471+15+10; //width+padding left+padding right
			
			$('.controller',$this).append('<div class="carouselArrow" id="pageBtnLeft"></div>');
			
			$('.items .item',$this).each(function() {
				numPages++;
				
				if(numPages == 1)
				{
					$('.controller',$this).append('<div id="pageBtn_'+numPages+'"class="pageBtn active"></div>');
				}
				else
				{
					$('.controller',$this).append('<div id="pageBtn_'+numPages+'"class="pageBtn"></div>');
				}
			});	
			$('.controller',$this).append('<div class="carouselArrow" id="pageBtnRight"></div>');
			
            function gotoPage(page) {
				
				 if(intTransition){
					 return false;
				 }
				 
				 pageId = page;
				 pageDiff = pageId - currentPage;
				 
				 $('#pageBtn_'+currentPage).removeClass('active');
				 $('#pageBtn_'+page).addClass('active');
						
				var dir = pageId < currentPage ? -1 : 1,
                    n = Math.abs(currentPage - pageId),
                    left = pageWidth * dir * n;
				
				intTransition = true;
				$('#slider_home').filter(':not(:animated)').delay(3800).animate({
					scrollLeft : '+=' + left
				}, 1300, function () {
					intTransition = false;
				});
				
				currentPage = pageId;	
			}
			
			function next(){
				pageId = (currentPage >= numPages) ? 1 : currentPage + 1;
				gotoPage(pageId);
			}
			
			function previous()
			{
				pageId = (currentPage <= 1) ? numPages : currentPage -1;
				gotoPage(pageId);
			}
			
			
			$('.controller .carouselArrow',$this).bind('click', function() {
				 pageId = $(this).attr('id');
				 if(pageId == 'pageBtnRight')
				 {
					next();
				 }
				 else
				 {
					previous();
				 }
				 
				 gotoPage(pageId);
				 
			});
			
			$('.controller .pageBtn',$this).bind('click', function() {
				
					pageId = $(this).attr('id');
					pageId = pageId.replace("pageBtn_", "");
					pageId = parseInt(pageId);
					
					if(pageId == currentPage)
					{
						return false;
					}
					else
					{
						gotoPage(pageId);
					}
			});
			
			 // THIS IS NEW CODE FOR THE AUTOMATIC INFINITE CAROUSEL
            $(this).bind('next', function () {
                next();
            });
			
			
		});
	
	};
})( jQuery );
