var ExpressShop = Class.create();
ExpressShop.prototype = {
	initialize: function(shop) {
		this.shop = shop;
		this.tabs = shop.getElementsBySelector('.tabs a');
		this.content = shop.getElementsBySelector('.data').first();
		this.groupName = shop.down('h1').innerHTML;
		
		this.tabify(this.tabs);
		this.setup();
	},

	tabify: function(tabs) {
		tabs.each(function(tab) {
			tab.onclick = function() {
				var match = tab.href.match(/product_id=(.+)$/);
				this.getProduct(match[1]);
				
				tabs.each(function(e) {
					(e==tab) ? e.addClassName('active') : e.removeClassName('active');
				});
				
				var tabName = tab.innerHTML.replace(/<br( \/)?>/i, '');
				var label = this.groupName + ' - ' + tabName;
				GoogleAnalytics.trackEvent('Express Shop', 'Tab', label);
				
				return false;
			}.bind(this);
		}.bind(this));
	},

	setup: function() {
		this.prices  = this.content.getElementsBySelector('.qtyPrice').first();
		this.spinner = this.content.getElementsBySelector('.spinner').first();
		this.spin();
		
		var sel = this.content.getElementsByTagName('select')[0];
		sel.onchange = function() {
			this.getProduct(sel.value);
		}.bind(this);
		
		this.form = this.content.getElementsByTagName('form')[0];
		new Form.Element.RadioEventObserver(this.form, 'colorsFront', this.getPrices.bind(this));
		new Form.Element.RadioEventObserver(this.form, 'colorsBack', this.getPrices.bind(this));
		new Form.Element.RadioEventObserver(this.form, 'prodTime', this.getPrices.bind(this));
		
		this.content.getElementsBySelector('a.help').each(function(e){
			new Tip(e, e.rel, {title : ' ', fixed: true});
		});
	},

	getProduct: function(productId) {
		this.spin();
		
		this.productId = productId;
		var params = {
			product_id: this.productId,
			priceTab: 'Print',
			prodTime: 'Standard',
			colorsFront: 'P1C',
			colorsBack: 'NONE'
		}
		var myAjax = new Ajax.Updater(this.content, '/ae/control/expressShopProduct',
			{method: 'get', parameters: params, onComplete: this.setup.bind(this)});
	},

	getPrices: function() {
		this.spin();
		
		var params = Form.serialize(this.form, true);
		params['priceTab'] = 'Print';
		var myAjax =  new Ajax.Updater(this.prices, '/ae/control/expressShopPrice',
			{method: 'get', parameters: params, onComplete: this.spin.bind(this)});
	},

	spin: function() {
		if (!this.spinner) return;
		if (!this.spinner.visible()) {
			this.spinner.show();
		} else {
			setTimeout(function() {
				this.spinner.hide();
			}.bind(this), 150);
		}
	}
};

/*--------------------------------------------------------------------------*/

Event.onDOMReady(function(){
	$$('.expressShop').each(function(e){
		new ExpressShop(e);
	});
});

