// Mathieu dumais-savard 2009
// http://www.mathieusavard.info/
// version 0.4.0 (nobody likes 1.0, it would be too nice to pretend that there is no bug :P
// amended by Skywire (www.skywire.co.uk) - 04/2010

jQuery.fn.threesixty = function(options) {

	options = options || {};
	options.images = options.images || [];
	options.method = options.method || "mousemove";
	options.cycle = options.cycle || 1;
	options.resetMargin = options.resetMargin || 0;
	options.direction = options.direction || "backward";
	if (options.direction == "backward") {
		options.images.reverse();
	}

	// more than inspired of Bret Taylor's work : http://ajaxcookbook.org/disable-text-selection/
	function disableSelection(element) {
		element.onselectstart = function() {
			return false;
		};
		element.unselectable = "on";
		element.style.MozUserSelect = "none";
		element.style.cursor = "default";
	}

	return this.each(function() {

		var imgArr = [];
		var pic = $(this);
		var picHolder = pic.parent();
		// ask browser to load all images. Requires http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript
		jQuery.preLoadImages( options.images );

		for (var x=1; x<=options.cycle; x++) {
			for (var y=0; y<options.images.length; y++) {
				imgArr.push(options.images[y]);
			}
		}

		// add the first image again to complete the loop
		imgArr.push(options.images[0]);

		// mousemove handler
		if (options.method == "mousemove") {
			pic.mousemove(function(e) {
				pic.attr("src",imgArr[Math.floor( (e.pageX - pic.offset().left) / ( pic.width() / imgArr.length ) )]);
			});
		}

		// click handler
		if (options.method == "click") {
			var follower;
			if (!$.browser.msie)
			{	follower = $("<div>").css({"z-index":0, "width":"15px", "height":"15px", "position":"absolute", "top": pic.offset().top, "left":pic.offset().left});
			$("body").append(follower);
			disableSelection(follower[0]);
		}

		disableSelection(pic[0]);
		var enabled;
		pic.mousemove(function(e) {
			if ( e.pageX<=pic.offset().left+options.resetMargin || e.pageX > pic.offset().left + pic.width()-options.resetMargin || e.pageY<=pic.offset().top+options.resetMargin || e.pageY>=pic.offset().top+pic.height()-options.resetMargin ) {
				enabled = false;
				return false;
			}
			if (follower) {
				follower.css({"top": e.pageY-7, "left": e.pageX-7});
				if (enabled === true) {
					pic.attr("src",imgArr[Math.floor((e.pageX - pic.offset().left) / (pic.width()/imgArr.length))]);
				}
			}
		});
		pic.add((follower)?follower:null).mouseup(function() {
			enabled = false; 
			}).mousedown(function() {
				enabled = true;
			});
		}

	});

};
