/**
 * SkiyoSpinner for jQuery
 *
 * @auth Jessica
 * @link http://demo.skiyo.cn/skiyospinner/
 */
(function($) {
	$.fn.SkiyoSpinner = function(options) {
		var opts = $.extend({}, $.fn.SkiyoSpinner.defaults, options);
		return this.each(function() {
			var target = $(this);
			
			target.css('width', opts.width).attr('maxlength', new String(opts.max).length);
			target.before($('<img />').attr('src', opts.minus).attr('alt', '减少').css({'cursor':'pointer', 'padding-right':'3px'}).click(minus));
			target.after($('<img />').attr('src', opts.plus).attr('alt', '增加').css({'cursor':'pointer', 'padding-left':'3px'}).click(plus));

			var val = parseInt(target.val());
			if(isNaN(val)){
				target.val(opts.initial);
				val = opts.initial;
			}
			
			function minus(){
				if(val==opts.min) {
					return ;	
				}
				now = val - opts.step;
				change(now);
			}
			function plus(){
				if(val==opts.max) {
					return ;	
				}
				now = val + opts.step;
				change(now);
			}
			function change(now){
				if(now > opts.min && now < opts.max) {
					val = now;
				} else if(now <= opts.min) {
					val = opts.min
				} else {
					val = opts.max
				}
				target.val(val);
				opts.change.apply(target, [val]);
			}
			target.keydown(function(e){
				if(!((e.keyCode>=48&&e.keyCode<=57)||(e.keyCode>=96&&e.keyCode<=105)||e.keyCode==8)) {
					return false;
				}
			});
			target.blur(function(){
				change(parseInt(target.val()));
			});
		});
	};
	$.fn.SkiyoSpinner.defaults = {
		minus : 'minus.gif',
		plus : 'plus.gif',
		width : '30px',
		initial : 1,  //初始值
		step : 1,     //步长
		min : 1,       //最小值
		max : 100,     //最大值
		change : function(now){}             //当数值改变时候的回调函数 now为当前值
	};
})(jQuery);