var stock = {
	out_form: null,
	in_form: null,
	
	init: function(){

		// Out stock form
		
		if(document.forms["theform"]){
			this.out_form = document.forms["theform"];
		}
		
		// In stock form
		
		if(document.forms["theform2"]){
			this.in_form = document.forms["theform2"];
		}
		
		if(this.in_form){
			
			// Bind handlers to inputs
			
			this.add_events();
		}
	},
	
	// Cross browser event adding with IE scope fix (aka 'this')
	
	add_event: function(obj, type, fn){
		if(obj.attachEvent){
			obj["e" + type + fn] = fn;
			obj[type + fn] = function(){
				obj["e" + type + fn](window.event);
			}
			
			obj.attachEvent("on" + type, obj[type + fn]);
		} else {
			obj.addEventListener(type, fn, false);
		}
	},

	// Add onchange handlers to all quantity fields
	
	add_events: function(){
		
		// Loop through form elements and set handler on correct one
			
		for(var e = 0, l = this.in_form.elements.length; e < l; e ++){
			if(this.in_form.elements.item(e).className == "_quan"){
					
				// Add handler to inputs
					
				this.add_event(this.in_form.elements.item(e), "change", function(){
						
					// Fix scope of function and send 2 arguments
						
					stock.in_form_change.apply(this, [stock.in_form, stock.out_form]);
				});
			}
		}
	},
	
	// Loop through and update fields so PHP gets the right quantity
	
	in_form_change: function(a, b){
		if(a){
			for(var e = 0, l = a.elements.length; e < l; e ++){
				if(a.elements.item(e).className == "_quan"){
					var out_num = 0;
					var q = a.elements.item(e).name.split("_")[1];
					
					if(b && b.elements[q]){
						out_num = parseInt(b.elements[q].value, 10);
					}

					a.elements[q].value = parseInt(a.elements.item(e).value, 10) + out_num;
				}
			}

			if(this && a.elements[this.name.split("_")[1]]){
				a.elements[this.name.split("_")[1]].value = this.value;
			}
		}
	}
	
}

