/*
 * jQuery Quovolver v1.0 - http://sandbox.sebnitu.com/jquery/quovolver
 *
 * By Sebastian Nitu - Copyright 2009 - All rights reserved
 * 
 */

(function($) {
	$.fn.quovolver = function(speed, delay) {
		
		/* Sets default values */
		if (!speed) speed = 500;
		if (!delay) delay = 20000;
		
		// If "delay" is less than 4 times the "speed", it will break the effect 
		// If that's the case, make "delay" exactly 4 times "speed"
		var quaSpd = (speed*4);
		if (quaSpd > (delay)) delay = quaSpd;
		
		// Create the variables needed
		var	quote = $(this),
			rand = Math.floor(Math.random() * this.length),
			firstQuo = $(this).filter(':eq(' + rand + ')'),
			lastQuo = $(this).filter(':last'),
			wrapElem = '<div id="quote-wrap"></div>',
			nextElem = firstQuo,
			wrapHeight,
			changeQuote;
		
		// Wrap the quotes
		$(this).wrapAll(wrapElem);
		
		// Hide all the quotes, then show the first
		$(this).hide();
		$(firstQuo).show();
		
		// Set the height of the wrapper
		$(this).parent().css({height: $(firstQuo).height()});		
		
		cycleQuotes();
		
		// Cycle quotes
		function cycleQuotes(){
			changeQuote = setInterval(function(){
			
				// Set required height and element in variables for animation
				if($(lastQuo).is(':visible')) {
					nextElem = $(quote).filter(':first');
					wrapHeight = $(nextElem).height();
				} else {
					nextElem = $(quote).filter(':visible').next();
					wrapHeight = $(nextElem).height();
				}
				
				newQuote();
			
			}, delay);
		}
		
		// Next button
		$('#quotes .next').bind('click', function(){
			// Set required height and element in variables for animation
			if($(lastQuo).is(':visible')) {
				nextElem = $(quote).filter(':first');
				wrapHeight = $(nextElem).height();
			} else {
				nextElem = $(quote).filter(':visible').next();
				wrapHeight = $(nextElem).height();
			}				
			
			clearInterval(changeQuote);
			cycleQuotes();
			newQuote();
		 });
		
		// Previous button
		$('#quotes .prev').bind('click', function(){
			// Set required height and element in variables for animation
			if($(quote).filter(':first').is(':visible')) {
				nextElem = $(lastQuo);
				wrapHeight = $(nextElem).height();
			} else {
				nextElem = $(quote).filter(':visible').prev();
				wrapHeight = $(nextElem).height();
			}
			
			clearInterval(changeQuote);
			cycleQuotes();
			newQuote();
		 });
		
		function newQuote() {
			// Fadeout the quote that is currently visible
			$(quote).filter(':visible').fadeOut(speed);
			
			// Set the wrapper to the height of the next element, then fade that element in
			setTimeout(function() {
				$(quote).parent().animate({height: wrapHeight}, speed);
			}, speed);
			
			setTimeout(function() {
				$(nextElem).fadeIn(speed);
			}, speed*2);
		}
	};
})(jQuery);
