/**
 * Collection
 */
var GPR_COLLECTION = function(){
	var _collection = new Array;
	return {
		/**
		 * Add an item to the collection.
		 * If the key references to an existing object, an Error instance is thrown.
		 */
		add: function(key, obj){
			/* Ensure that the key is not already used */
			if(typeof _collection[key] != "undefined") throw new Error("The key " + key + " is already being used.");
			_collection[key] = obj;							
		},
		/**
		 * Gets an item from the collection, or null, if the key does not reference to any object.
		 */
		get: function(key){
			return _collection[key];
		}
	}
}();

/**
 * Ensures that the value entered in the qutantity field is multiple of 'multof' before sending the form.
 * If not, a message indicating the first of the mismatched conditions is shown.
 * Requieres the GPR_COLLECTION singleton.
 *
 * @param minqty (Integer) Minimuy orderable quantity.
 * @param itemid (String) Item internal id.
 *
 * @return void.
 */
function addToCartByMultiples(multof, itemid){
    var form = document.forms['form' + itemid];
	if (form){
		var _onsubmit = form.onsubmit;
		GPR_COLLECTION.add(itemid, {onsubmitHandler: _onsubmit, mult: multof});
		form.onsubmit = function(){
			var qty = parseInt(this.elements.qty.value),
				id = this.id.match(/\d+/)[0];
			if ((qty > 0) && (qty % GPR_COLLECTION.get(id).mult == 0)){
				return GPR_COLLECTION.get(id).onsubmitHandler();
			}else{
				alert("Must order in multiples of " + multof + ".");
				return false;
			}
		}		
	}else{
		alert("Error: Form not found.");
	}
}
