(function( $ ){
	var internal = {
		backgroundAnimation: function(el, options) {
		
		}	
	};
	
	var uagent = navigator.userAgent.toLowerCase();
	var is_handheld = false;
	if (uagent.search("iphone") < 0 &&
		uagent.search("ipod") < 0 &&
		uagent.search("ipad") < 0 &&
		uagent.search("blackberry") < 0) {
		is_handheld = false;
	} else {
		is_handheld = true;
	}

	var methods = {
		init: function(o) {
			return this.each(function() {
				var $this = $(this);
				var defaults = {
						show_rotate:true,
						nb_images: 15,
						image_width: 240,
						fallback: function(el) {}
				};
				var options = $.extend(defaults, o);
				if (is_handheld || ! options.show_rotate) {
					options.fallback($this);
					return;
				}
				$this.css("background-position", parseInt((options.nb_images+1)/2*options.image_width)+"px 0px");
				$this.bind("mousemove", 
					{ image_width: options.image_width, nb_images: options.nb_images },  
					function(evt) {
						var position =$(this).offset();
						var cw = $(evt.target).get(0).clientWidth;
						if (cw > 0) {
							var x = evt.pageX - position.left;
							var a = 1 + Math.floor((x - 1) * evt.data.nb_images / cw);
							var backgroundPositionX = a * evt.data.image_width;
							$this.css("background-position", backgroundPositionX+"px 0px");
						}
					});
			});
		}
	};
	
	$.fn.SculpteoThumbnail = function( method ) {
		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 on jQuery.SculpteoThumbnail' );
		}
	};
})( jQuery );


$.fn.animatedPng = function(o) {
	return this.each(function() {
		var defaults = {
				nb_images: 19,
				image_width: 240,
				delay: 150
		}
		var options = $.extend(defaults, o);
		var idx = 1;
		if ($(this).data("bg-idx")) {
			idx = $(this).data("bg-idx");
		} else {
			idx = 1;
		}
		if (idx == options.nb_images) {
			$(this).data("bg-idx", 1);
		} else {
			$(this).data("bg-idx", idx+1);
		}
		$(this).css("background-position", (idx-1)*options.image_width+"px 0px")
		$(this).delay(options.delay);
		$(this).queue(function() { $(this).animatedPng(options); $(this).dequeue(); });
	});
}

