;(function($) {
	
	$.widget('ui.range', {
		
		value: null,
		pairValue: null,
		
		_draw: function() {
			var _e = this.element, _o = this.options, self = this;
			var _content = '';
			
			var _disabled_lower = false, _disabled_upper = false;
			
			//if (this.value > this.pairValue)
			if (_o.border == 'bottom')
				_disabled_lower = true;
			else
				_disabled_upper = true;
			
			for (var _i = parseInt(_o.range[0], 10); _i <= parseInt(_o.range[1], 10); _i++) {
				var _class = '';
				if ((_i < self.pairValue && _disabled_lower) || (_i > self.pairValue && _disabled_upper))
					_class = 'disabled';
				if (_i == self.value)
					_class = 'active';
				var _template = '<span class="' + _class + '">' + _i + '</span>';
				
				if ((_disabled_lower && _i == self.pairValue) || (_disabled_upper && _i == self.value))
					_template = '<div>' + _template;
				if ((_disabled_lower && _i == self.value) || (_disabled_upper && _i == self.pairValue))
					_template += '</div>';
				
				_content += _template;
			}
			_e.html(_content);
		},
		
		_bindHandler: function(_f) {
			if (typeof(_f) !== 'function')
				return;
			var self = this;
			this.element.click(function(_ev) {
				var _el = $(_ev.target);
				if (!_el.filter('span:not(.' + self.options.disabledClass + ')').length)
					return;
				var _val = parseInt(_el.text(), 10);
				_f.call(_el, _val);
			})
		},
		
		_onSelect: function(_val) {
			this.value = _val;
			this._draw();
		},
		
		_init: function() {
			var _e = this.element, _o = this.options, self = this;
			_e.addClass(_o.rangeClass);
			
			self._bindHandler(function(_v){
				self._onSelect.call(self, _v);
			});
			
			if (!(_o.range instanceof Array) || _o.range.length != 2) {
				//alert()
				throw ('Invalid range format: [%d, %d] expected.');
			}
			if (_o.range[0] > _o.range[1])
				throw ('Invalid range: [min, max].');
			
			this.value = (_o.value === null) ? parseInt(_o.value, 10) : parseInt(_o.value, 10);
			this.pairValue = (_o.pairValue === null) ? parseInt(_o.pairValue, 10) : parseInt(_o.pairValue, 10);
			
			this._draw();
		},
		
		setValue: function(_v) {
			this._value = parseInt(_v, 10);
			this.draw();
		},
		
		setPairValue: function(_v) {
			this.pairValue = parseInt(_v, 10);
			this._draw();
		},
		
		addOnSelectStack: function(_f) {
			this._bindHandler(_f);
		}
	})
})(jQuery);

$.extend($.ui.range.prototype, {
	options: {
		range: [1, 10],
		value: null,
		pairValue: null,
		activeClass: 'active',
		disabledClass: 'disabled',
		rangeClass: 'b-night',
		border: 'top'
	},
	getter: 'getValue'
})
