(function ($) {
	// view 360 action adventure
	$.fn.v360 = function (options) {
		var opts = $.extend({}, $.fn.v360.defaults, options);

		return this.each(function () {
			// extend options
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
			var $t = $(this);
			var $i = $t.find('img');

			// step change every x pixels
			var step_change = Math.ceil(100 / o.steps);

			// create interface
			$('<div class="v360-slider" />').appendTo($t).slider({
				slide: function (e, ui) {
					// get current x position for this step
					var _s = Math.floor(ui.value / step_change) * o.step;
					if (_s >= o.steps * o.step) _s = 0;
					$i.css({left: '-' + _s + 'px'});
				}
			});
			$t.prepend('<div class="v360-drag" />').find('.v360-drag').each(function () {
				$this = $(this);

				$this.mousedown(function () {
					// start the drag action
					$this.data('drag', true);
				}).mousemove(function (e) {
					e.preventDefault();
					e = e.originalEvent;
					if ($this.data('drag') == true) {
						// calculate the "width" of each pixel
						var _pw = o.step / 101;
						// calculate where we are, scaled by pixel width
						var _s = Math.floor((e.layerX / _pw) / step_change) * o.step;
						if (_s >= o.steps * o.step) _s = 0;
						$i.css({left: '-' + _s + 'px'});
						// move the slider accordingly
						_s = Math.ceil(e.layerX / o.step * 100);
						if (_s > 100) _s = 100;
						$t.find('.v360-slider a').css({left: _s + '%'});
					}
				}).mouseup(function () {
					// stop the drag action
					$this.data('drag', false);
				}).click(function (e) {
					e.preventDefault();
				});
			});
		});
	};

	// defaults
	$.fn.v360.defaults = {
		 step:  420 // each step is 420px wide
		,steps: 20  // 20 steps per image
	};
})(jQuery);
