/**
 * @author ricky
 */

var QuantityToggler = new Class({
			/**
			 * @type Element
			 * @private
			 */
			_element : null,
			/**
			 * @type Element
			 * @private
			 */
			_input : null,
			/**
			 * @type String
			 * @private
			 */
			_behaviour : 'add',
			/**
			 * @private
			 */
			_delay : null,
			/**
			 * @private
			 */
			_timeout : null,
			/**
			 * @constructor
			 * @param {Element}
			 *            element
			 * @param {Element}
			 *            input
			 * @param {String}
			 *            behaviour
			 * @public
			 */
			initialize : function(element, input, behaviour) {
				this._element = $(element);
				this._input = $(input);
				if ($defined(behaviour) && behaviour.trim() === 'substraction') {
					this._behaviour = 'substraction';
				}

				this._element.addEvent('click', this._mouseClickEvt
								.bindWithEvent(this._element));
				this._element.addEvent('mousedown', this._mouseDownEvt
								.bindWithEvent(this._element, this));
				this._element.addEvent('mouseup', this._mouseUpEvt
								.bindWithEvent(this._element, this));
			},
			/**
			 * @param {Event}
			 *            e
			 * @private
			 */
			_mouseClickEvt : function(e) {
				var evt = new Event(e);
				evt.stop();
			},
			/**
			 * @param {Event}
			 *            e
			 * @private
			 */
			_mouseDownEvt : function(e, obj) {
				var evt = new Event(e);
				evt.stop();
				obj._doChange();

				obj._delay = (function() {
					obj._timeout = (function() {
						obj._doChange();
					}).periodical(150);
				}).delay(800);
			},
			/**
			 * @param {Event}
			 *            e
			 * @private
			 */
			_mouseUpEvt : function(e, obj) {
				var evt = new Event(e);
				evt.stop();
				$clear(obj._delay);
				$clear(obj._timeout);
			},
			/**
			 * @private
			 */
			_doChange : function() {
				var val = this._input.value.toInt(), new_val;
				switch (this._behaviour) {
					case 'add' :
						new_val = val + 1;
						break;
					case 'substraction' :
						if (val > 1) {
							new_val = val - 1;
						} else {
							new_val = val;
						}
						break;
				}
				this._input.value = new_val;
			}
		});

window.addEvent('domready', function() {
			var qty_tables = $$('.qty_table');
			$each(qty_tables, function(item) {
						var qty = item.getElement('.qty');
						new QuantityToggler(item.getElement('.qty_substract'),
								qty, 'substraction')
						new QuantityToggler(item.getElement('.qty_add'), qty);
						qty.addEvent('focus', function(e) {
									this.selectionStart = 0;
									this.selectionEnd = this.value.length;
								});
					});
		});
