/**
 * JSAmount.js - For numeric inputs with increment/decrement controls
 * 
 * @author  Webstores <info at webstores dot nl>
 *           Copyright (c) Webstores internet totaalbureau <http://www.webstores.nl/>
 * 
 * @requires webstores.js (Webstores Javascript library)
 */

var JSAmount = function(inputCls, minValue, incrStep) {
	var inputs = [],
		timeout,
		interval,
		inputCls = inputCls || 'jsamount',
		minValue = minValue || 0,
		incrStep = incrStep || 1;
	
	return {
		initialize: function() {
			inputs = WS.DOM.getElementsByClass(inputCls);
			this.initEvents();
		},
		initEvents: function() {
			if(inputs.length) {
				for(var i = 0; i < inputs.length; i++) {
					inputs[i].incrBtn = WS.DOM.next(inputs[i]);
					inputs[i].decrBtn = WS.DOM.next(inputs[i].incrBtn);
					this.bindIncrement(inputs[i]);
					this.bindDecrement(inputs[i]);
				}
			}
		},
		bindIncrement: function(el) {
			var self = this;
			WS.Event.addEvent(el.incrBtn, 'click', function(e) {
				WS.Event.stopEvent(e);
			});
			WS.Event.addEvent(el.incrBtn, 'mousedown', function() {
				self.setTimedInterval(function() {
					self.increment(el);
				}, 200, 50);
				self.increment(el);
			});
			WS.Event.addEvent(el.incrBtn, 'mouseup', function() {
				self.clearTimedInterval(timeout, interval);
			});
		},
		bindDecrement: function(el) {
			var self = this;
			WS.Event.addEvent(el.decrBtn, 'click', function(e) {
				WS.Event.stopEvent(e);
			});
			WS.Event.addEvent(el.decrBtn, 'mousedown', function() {
				self.setTimedInterval(function() {
					self.decrement(el);
				}, 200, 50);
				self.decrement(el);
			});
			WS.Event.addEvent(el.decrBtn, 'mouseup', function() {
				self.clearTimedInterval(timeout, interval);
			});
		},
		setTimedInterval: function(fn, t, i) {
			timeout = setTimeout(function() {
				interval = setInterval(function() {
					fn.call();
				}, i);
			}, t);
		},
		clearTimedInterval: function(t, i) {
			clearTimeout(t);
			clearInterval(i);
		},
		increment: function(el) {
			el.value = parseInt(el.value) + incrStep;
		},
		decrement: function(el) {
			if((el.value - incrStep) > minValue)
				el.value -= incrStep;
		}
	}
}();

WS.Event.addEvent(window, 'load', function() {
	JSAmount.initialize();
});

