/**
 *
 * Usage:
 *   $("#element_id").featuredslider({
 *     [options...]
 *   });
 *   $("#element_id").featuredslider("[method]", "[paramater]");
 *
 */
(function($){

	$.fn.featuredslider=function(method) {

		/**
		 * Options defaults
		 */
		var defaults={
			'maxProductsPerGroup'		: 3,
			'slideTransitionDuration'	: 1000
		};
		
		/**
		 * Public Methods
		 */
		var methods={
		
			init: function(options){
			
				if (options) {
					options=$.extend({}, defaults, options);
				}
				
				return this.each(function(){
				
					var element=$(this);
					
					// Store options
					$(this).data("options", options);
					
					// Find and cache
					var navigation=element.find("UL#navigation").eq(0);
					var viewport=element.find("DIV#viewport").eq(0);
					var canvas=element.find("DIV#canvas").eq(0);
					
					// Get total products
					var totalProducts=element.find("DIV.slide").size();
					var totalGroups=Math.ceil(totalProducts/options['maxProductsPerGroup']);
					
					// Get viewport size
					var viewportWidth=viewport.innerWidth();
					$(this).data("viewportWidth", viewportWidth); // cache it...
					
					// Size things
					viewport.css({
						'width' : viewportWidth+'px' // hard-set the width
					});
					canvas.css({
						'width' : (viewportWidth*totalGroups)+'px'
					});
					element.find("DIV.slide").css({
						'width' : Math.floor(viewportWidth/options['maxProductsPerGroup'])+'px'
					});
					
					// Navigation
					for (var i=0; i<totalGroups; i++) {
						navigation.append("<li><a>"+(i+1)+"</a></li>");
					}
					navigation.find("LI A").each(function(index){
						$(this).click(function(){
							//element.featuredslider("showGroup", index);
							showGroup(element, index);
							return false;
						});
					});
					
					// Go first
					//element.featuredslider("showGroup", 0);
					showGroup(element, 0);
					
				});
				
			},
			
			showGroup: function(index){
			
				return this.each(function(){
				
					showGroup($(this), index);
					
				});
				
			}
			
		};
		
		/**
		 * Private Methods
		 */
		var showGroup=function(element, index){

			// Navigation
			element.find("UL#navigation LI A").removeClass("selected");
			element.find("UL#navigation LI A").eq(index).addClass("selected");

			// Animate canvas
			var left=0-(index*element.data("viewportWidth"));
			element.find("DIV#canvas").eq(0).animate(
				{
					left: left+"px"
				},
				{
					duration: element.data("options").slideTransitionDuration, 
					easing: 'easeInOutCubic',
					complete: function(){
		
					}
				}
			);

		}

		/**
		 * Router
		 */
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error("Method " +  method + " does not exist");
		}
		
	};

})(jQuery);
