jQuery.flipper = function ($activator, $transformable, $highlighter, eventFlip, eventResume) {
	this.slideshow; 
	this.flipAnimation; 
	this.currentMouseover = false;
	this.autoDelay = 3000;
	this.flipDelay = 400;
	var curObj = this;
	$activator.each(function(index){
		$(this).attr('flipperId', index);
		$transformable.eq(index).attr('flipperId', index);
	});
	$activator.filter(':first').addClass('active');
	$transformable.css('opacity', '0');
	$transformable.filter(':first').css({'z-index': 2, 'opacity': 1});
	
	if (eventFlip && eventResume) {
		$activator.bind(eventFlip,(function(){
			if (!$(this).hasClass('active')) {
				curObj.currentMouseover = $(this);
				curObj.flipTo($(this));
			}
		}));
		$activator.bind(eventResume,(function(){
			curObj.currentMouseover = false;
			if (curObj.slideshow) {
				curObj.flipAll();
			}
		}));
	}
	
	this.flipTo = function($item, delay) {
		var curObj = this;
		if (!delay) {
			delay = this.flipDelay;
		}
		clearTimeout(curObj.flipAnimation);
		curObj.flipAnimation = setTimeout(function(){ // this will add a delay before animating
			var $currentActive = $activator.filter('.active');
			$currentActive.removeClass('active');
			
			if ($highlighter) {
				$highlighter.stop().animate({
					'marginTop' : $item.css('margin-top')
				}, 300, null, function(){
					curObj.transform($item, $currentActive, $transformable, delay)
				});				
			} else {
				curObj.transform($item, $currentActive, $transformable, delay);
			}
		}, delay);
	}
	
	this.transform = function($item, $currentActive, $transformable, delay) {
			$item.addClass('active');
			var idCurrent = $currentActive.attr('flipperId');
			var idNext = $item.attr('flipperId');
			
			$transformable.filter('[flipperId=' + idCurrent + ']').
				css('z-index', 1);
			$transformable.filter('[flipperId=' + idNext + ']').
				stop().
				css('z-index', 2).
				animate({'opacity': 1}, 400, null, function(){
					$transformable.filter('[flipperId=' + idCurrent + ']').css('opacity', 0);
					if (curObj.slideshow === true && !curObj.currentMouseover) {
						curObj.flipTo(curObj.getNextItem(), curObj.autoDelay);
					} else {
						curObj.flipAnimation = false;				
					}
				});
	}

	this.flipAll = function() {
		this.slideshow = true;
		this.flipTo(this.getNextItem(), this.autoDelay);
	}

	this.getNextItem = function() {
		var $nextActive = $activator.filter('.active').next();
		if ($nextActive.length !== 1) {
			$nextActive = $activator.filter(':first');
		}
		return $nextActive;
	}
}

$(document).ready(function(){
	var recipeFlipper = new $.flipper($('#recipeHighlights .recipeName'), $('#recipeHighlights .recipeImg'), $('#recipeHighlights .nameHighlight'), 'mouseover', 'mouseleave');
	recipeFlipper.flipAll();
});