/* 
 *	@copyright Art.Lebedev Studio (http://www.artlebedev.ru)
 * 	@autor: Vasily Mamaevsky (polochka@design.ru)
 *
 *	Requires:
 *	- jquery
 */
 
(function($){
	// static constructs
	$.xdraggable = $.xdraggable || {version: '1.0'};
	
	$.xdraggable.conf = {
		sensitivity: 1.0
	}
	
	function xDraggable (root, conf) {
		// Flags
		var isMoved = false;
		
		// xdraggable properties
		var self = this,
			sensitivity = conf.sensitivity,
			pos = root.position().left,
			mousePos_ = 0,
			mousePos = 0,
			mouseShift = 0;
		
		$.extend(self, {
			setSens: function(val) {
				sensitivity = val;
			},
			
			setPosLeft: function(pos) {
				root.css('left', Math.round(pos) + 'px');
			},
			
			setSensitivity: function(val) {
				sensitivity = val;
			}
		});
		
		// Events
		root.mousedown(function(event){
			isMoved = true;
			mousePos_ = event.pageX;
			pos = root.position().left;
		});
		
		$(document).mouseup(function(){
			isMoved = false;
		});
		
		$(document).mousemove(function(event){
			if (isMoved) {
				mousePos = event.pageX;
				mouseShift = mousePos - mousePos_;
				pos += mouseShift * sensitivity;
				self.setPosLeft(pos);
				
				mousePos_ = mousePos;
			}
		});
		
		return self;
	}	

	$.fn.xdraggable = function(conf) {
		
		// already constructed --> return API
		var el = this.data("xdraggable");
		if (el) { return el; }	
		
		conf = $.extend({}, $.xdraggable.conf, conf);
		
		this.each(function() {			
			el = new xDraggable($(this), conf);
			$(this).data("xdraggable", el);	
		});
		
		return conf.api ? el: this; 
	};
})(jQuery);
