/*
 * jQuery Stepper
 * http://designpunct.com/projects/jquery.stepper.js
 *
 * Copyright 2010, Andrei Eftimie
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 */
(function($){
	$.fn.stepper = function(options) {
	
		var defaults = {
			step 			: 1,		//Step size
			defaultValue 	: 1,		//Default stepper value. If input is empty, it will be given this value as a starting value
			min				: 0,		//Default minimum value. Stepper won't go below this value
			max				: false		//Default maximum value. Stepper won't go above this value
		};
		
		var options = $.extend(defaults, options);
		
	    return this.each(function() {
			
	    	//Element
			var $input = $(this);	
			if(!$input.parent().is('.stepper')){
				$input.wrap('<span class="stepper" />');
			}
			
			//Context
			var $context = $input.parent();
			
			//Init
			if ($input.val() == '') $input.val(options.defaultValue); 			
			
			//Plus / minus triggers
			$context.append('<a class="stepper-plus" href="#">+</a><a class="stepper-minus" href="#">-</a>')
			var $plus = $('.stepper-plus', $context);
			var $minus = $('.stepper-minus', $context);
			var $buttons = $plus.add($minus);
			
			//Adding events
			//on the buttons
			$buttons.click(function(event){
				el = event.target;				
				go($(el).is('.stepper-plus')?'up':'down');
				return false;
			});
			
			//We should also work with the up / down arrow keys
			$input.bind('keypress', function(event){
			
				console.log(event.keyCode);
						
				switch (event.keyCode){
					case 38:
						go('up');
						break;
					case 40:
						go('down');
						break;
					default:
						break;					
				}
			});
			
			//Public function.
			//Should be used whenever we change the value (programatically or trough events)
			function go(where){
				
				var value = parseInt($input.val());
				
				switch (where){
					case 'up':
						value = value + options.step;
						if (options.max) {
							if (value > options.max) value = options.max;
						}
						$input.val(value);
						break;
					case 'down':
						value = value - options.step;
						if (options.min) {
							if (value < options.min) value = options.min;
						}
						$input.val(value);
						break;
					default:
						break;	
				}
			}
			
		});
	};
})(jQuery);
