/*
 * jQuery jInputValue Plugin
 * Examples and documentation at: http://bstankowski.pl/dev/plugins/jinputvalue (/en for english)
 * Version: 1.0 (20.10.2009)
 * Copyright (c) 2009 Bartek Stankowski (http://bstankowski.pl)
 * Licensed under the MIT License: http://en.wikipedia.org/wiki/MIT_License
 *
 */

(function($){
	$.fn.jInputValue = function(options) {
		var settings = $.extend({}, $.fn.jInputValue.defaults, options),
			
			allowedKey = function(c) {
				if( (c == 9) || (c == 8) || (c >= 37 && c <= 40) || (c >= 48 && c <= 57) || (c == 45) || (c == 189) ) {
					return true;
				} else {
					return false;
				}
			},
			
			keyHandler = function(e, input) {
				var c = e.keyCode || e.which,
					step = 1,
					input = input[0],
					v = parseInt(input.value);
						
				if(allowedKey(c)) {
					step = e.shiftKey ? settings.shiftStep : settings.step;
					
					if(c == 38) {
						if(!v || v == '-') { v = 0 };
						
						if(settings.max != 'false') {
							if(v + step <= settings.max) {
								input.value = v + step;
							}
						} else {
							input.value = v + step;
						}
						
						e.preventDefault();  // for Opera
					} else if(c == 40) {
						if(!v || v == '-') { v = 0 };
												
						if(settings.min != 'false') {
							if(v - step >= settings.min) {
								input.value = v - step;
							}
						} else {
							input.value = v - step;
						}
						
						e.preventDefault();
					}
				} else { e.preventDefault(); }
			};	
				
		this.each(function() {
			var $this = $(this),
				c = '';
				
			$this.blur(function() {
				if(!this.value.match(/^\-?\d*$/)) {
					this.value = this.defaultValue ? this.defaultValue : 0;
				}
			})
				
			if(settings.min != 'false') {
				if(settings.min == 'default') {
					settings.min = this.defaultValue;
				} else if(!this.defaultValue) {
					this.value = settings.min;
				}
				
				
				$this.blur(function() {
					if(!this.value.match(/^\-?\d*$/) || this.value < settings.min) {
						this.value = settings.min;
					}
				});
			}			
			
			if(settings.max != 'false') {
				if(settings.max == 'default') {
					settings.max = this.defaultValue;
				}
				
				$this.blur(function() {
					if(!this.value.match(/^\-?\d*$/) || this.value > settings.max) {
						this.value = settings.max;
					}
				});
			}
												
			if($.browser.safari || $.browser.msie) {
				$(this).keydown(function(e) {
					keyHandler(e, $(this));
					$.fn.jInputValue.callback();
				});
			} else {
			 	$(this).keypress(function(e) { 
			 		keyHandler(e, $(this)); 
			 		$.fn.jInputValue.callback();
			 	});
			}
		});
		
		return this;
	};
	
	$.fn.jInputValue.defaults = {
		step: 1,
		shiftStep: 10,
		min: 'false',
		max: 'false'
	};
	
	$.fn.jInputValue.callback = function() {  };
})(jQuery);
