/**
 * jQuery.carousel - slide between images; create navigation to slide manually
 * Date: 2010/08/02
 *
 * @author Michaël van Oosten
 * @version 1.0
 *
 **/

(function($) {

	$.fn.carousel = function(options) {
		
		var config = {
			'autoslide' : true,
			'carousel_hover' : false,
			'parent' : '.billboard',
			'imgwrp' : '.imgwrp',
			'slidespeed' : 500,
			'interval' : 5000,
			'distance' : 960
		};
		var opts = $.extend(config, options);				
		
		if( $(config.parent).length ) {
			var itemCount = $(config.parent + ' img').length;
			var wrpWidth = itemCount * $(config.parent).width();
			$(config.parent + ' ' + config.imgwrp).width(wrpWidth);
			$(config.parent + ' ul').width(wrpWidth);

			// append '.billboard .imgwrp' navigation
			html = '<ul class="navigation">';
			for(i=0; i<itemCount; i++) {
				html += '<li><a href="#"></a></li>';
			}
			html += '</ul>';
			$(config.parent + ' ' + config.imgwrp).after(html);
			// activate first item
			$(config.parent + ' .navigation li:eq(0) a').addClass('act');

			// start carousel
			$.fn.carousel.start(config);

			// bind hover
			$(config.parent + ' .navigation li a').hover(
				function() {
					config.carousel_hover = true;
					$.fn.carousel.slide(config,$(this).parent().index());
				},
				function() {
					config.carousel_hover = false;
					$.fn.carousel.start(config);
				}
			);

		}
	}

	//   slide carousel to given item
	$.fn.carousel.slide = function(config, toItem) {
		$(config.parent + ' ' + config.imgwrp).stop(true);
		$(config.parent + ' .navigation li a').removeClass('act'); // remove hover state
		$(config.parent + ' .navigation li a:eq('+toItem+')').addClass('act');

		/* TO DO : animate based on settings (e.g. left-to-right, right-to-left, top-to-bottom, bottom-to-top ... ) */
		$(config.parent + ' ' + config.imgwrp).animate({ left : ( -1 * config.distance * toItem ) }, config.slidespeed, function() { });
	}

	//   return index of next item
	$.fn.carousel.next = function(config) {
		var thisMarginLeft = parseInt( $(config.parent + ' .imgwrp').css('left') );
		var thisIndex = Math.ceil( -1 * (thisMarginLeft / $(config.parent + ' img:eq(0)').width()) );
		return (thisIndex+1) % $(config.parent + ' ' + config.imgwrp + ' img').length;
	}

	//   start carousel
	$.fn.carousel.start = function(config) {
		if( config.autoslide ) {
			$.fn.carousel.stop(config);
			$(config.parent + ' ' + config.imgwrp).everyTime(config.interval, 'controlled', function() {
				if(!config.carousel_hover)
					$.fn.carousel.slide( config,$.fn.carousel.next(config) );
			});
		}
	}
	
	//   stop carousel
	$.fn.carousel.stop = function(config) {
		$(config.parent + ' ' + config.imgwrp).stopTime('controlled');
	}
 
})(jQuery);
