/**
 * Input increment/decrement widget
 * Add increment/decrement spinner button to the input field
 *
 * @param  min  {Integer}  Minimum value for spinner
 * @param  max  {Integer}  Maximem value for spinner
 *
 * @version  1.2
 * @author  Mista K.
 */
(function($) {
	$.fn.incdec = function() {
		var eles = this;
		var opts = arguments[0] || {};

        var checkMinMax = function (input, opts, increment) {
            var v = parseInt(input.value) + (increment ? parseInt(increment) : 0);
            if (isNaN(v)) {
                v = 0;
            }
            if (typeof opts.min !== "undefined" && opts.min > v) {
                v = opts.min;
            }
            if (typeof opts.max !== "undefined" && opts.max < v) {
                v = opts.max;
            }
            input.value = v;
        };

        var updateValue = function (obj, inc) {
			var data = $(obj).data("incdec") || {};
            var i = $("input", obj).get(0);
            if (!i.disabled) {
                checkMinMax(i, data, inc);
                $(i).change();
            }
        };
		
		var clickHandler = function (e) {
			var offset = $(this).offset();
			var x = e.pageX - offset.left;
			var y = e.pageY - offset.top;
			if (x > $(this).width()) {
				if (y > $(this).outerHeight() / 2) {
					// decrement
					updateValue(this, -1);
				} else {
					// increment
					updateValue(this, 1);
				}
				return false;
			}
		};
		
		return(
			eles.each(function() {
                if (this.nodeName === 'INPUT') {
                    var ele = $(this).wrapAll('<div class="incdec" unselectable="on"></div>').parent();
                    ele.data('incdec', opts);
                    ele.click(clickHandler);
                    if ($.browser.msie === true) {
                        ele.dblclick(clickHandler);
                    }
                    checkMinMax(this, opts);
                    $(this).change();
                }
            })
		);
	};
})(jQuery);