// JavaScript Document
var stockChecker = new Class({
	Implements: [Options, Events],
	options: {
		form	:	'cart_quantity',//url of backend script for stockchecker to check stock
		table : 'product_stocktable',
		quantity_list : 'quantity',
		addcart_button : 'addcart',
		quantity_title : 'quantity_title',
		outofstockmsg : ''
	},
	initialize:function(options) {
		this.setOptions(options);
		if($(this.options.quantity_list)) {
			this.addcart_button = $(this.options.addcart_button);
			this.quantity_list = $(this.options.quantity_list);
			this.quantity_title = $(this.options.quantity_title);
			this.quantity_container = this.quantity_list.getParent();
			if ($(this.options.outofstockmsg)) {
				this.outofstockmsg = this.options.outofstockmsg;
			} else {
				this.outofstockmsg = new Element('span',{
					html:'Out of stock',
					styles: {
						'color':'#ff0000',
						'font-weight':'bold'
					}
				});
				this.outofstockmsg.fade('hide');
				this.outofstockmsg.inject(this.quantity_container);
			}
			if ($(this.options.table)) {
				this.table = $(this.options.table);
				this.rows = new Array();
				this.loadData();
				this.form = $(this.options.form);
				this.attributes = this.form.getElements('select');
				this.attributes.each(function(el) {
					//el.fade('show');
					el.setStyle('display','');
					el.addEvent('change', this.checkStock.bind(this));				
				},this);
				this.quantity_list.removeEvents('change');
				this.checkStock();
			}
		}
	},
	loadData:function() {
		var count = 0;
		this.table.getElements("tr").each(function(el) {
				this.rows[count] = new Array();
				el.getElements("td").each(function(td) {
					this.rows[count].push(td.get('rel'));
				},this);
				count++;
		},this);
	},
	getChoices:function() {
			var values = new Array();
			this.attributes.each(function(f) {
				values.push(f.name.substr(3,f.name.length-4)+"-"+f.value);
			},this);
			return values;
	},
	checkStock:function() {
		testArray = this.getChoices();
		testArray.pop();
		var stocked = false;
		for(var i = 0; i < this.rows.length; i++ ) {
			r = this.rows[i];
			stocked = true;
			testArray.each(function(t){
				check = r.contains(t);		
				if (!check) {
					stocked = false;
				}
			});
			if (stocked) {
				this.fillQuantity(r.getLast().toInt());
				break;
			}
		}
		if(!stocked) {
			this.showOOS(true);
		}
		return false;
	},
	fillQuantity:function(q) {
		this.quantity_list.empty();
		for (var i = 1; i < q+1; i++) {
			option =	new Element('option',{
				'value':i,
				'html':i
			}); 
			option.inject(this.quantity_list);
		}
		this.showOOS(false);
	},
	showOOS:function(b) {
		if(b) {
			this.outofstockmsg.fade('show');
			this.quantity_list.fade('hide');
			this.addcart_button.fade('out');
			this.quantity_title.fade('hide')
		} else {
			this.outofstockmsg.fade('hide');
			this.quantity_list.fade('show');
			this.addcart_button.fade('in');
			this.quantity_title.fade('show')
		}
	}
});