//  Affiliate Shop Page Class - resizes display/layout of affiliate shop pages to best fit by number of products, page width
//  Author: Scott
//  Date:   18-08-09 

var affShop = new Class({
	Implements: [Options, Events],
	options: {
		shop: 			'affShop',
		padPrd: 		32,
		basePrdW:   	132,
		maxPrd: 		10
	},
	
	initialize: function(options) {
		this.setOptions(options);
		// Setup instance variables
		this.shop = $(this.options.shop);
		// Naughty IE6 - correct width for ie6 box model
		if(Browser.Engine.trident4) {this.shop.setStyle('width', '98%');}
		this.shopW = this.shop.getSize().x;
		// Let's get started
		this.init();
	},

	init: function() {
		//console.info('New Affiliate Shop Instance: ' + this.options.shop);
		var padPrd = this.options.padPrd;
		var basePrdW = this.options.basePrdW;
		var maxPrd = this.options.maxPrd;
		var prdWidth = 0;
		for (var i = 1; i <= maxPrd; i++) {
			prdWidth = i * (basePrdW + padPrd);
			//console.log('   Testing ' + i + ' Products: ' + prdWidth + ' in ' + this.shopW);
			if (prdWidth > (this.shopW)) {
				//console.log('   ' + i + ' Products FAIL: ' + (i - 1) + ' is best fit, ' + (i - 1) + ' products allowed per line');
				this.renderStyle(i - 1);
				break;
			}
		}			
	},
	
	renderStyle: function(numProducts) {
		// Override width for new ad layout
		numProducts = (this.shop.getChildren().length == 1) ? 1 : numProducts;
		var newWidth = (this.shopW - (this.options.padPrd * numProducts)) / numProducts;
		// Naughty IE6 - correct width for ie6 box model
		if(Browser.Engine.trident4) {newWidth = newWidth - (2 * numProducts);}
		// Condition for single product per row
		var needMargin = '';
		if (numProducts == 1) {
			newWidth = newWidth + 10;
			needMargin = 'margin-left: 0; margin-right: 0;';
		}
		//console.log('   Product width set to: ' + newWidth + 'px' + ((numProducts == 1) ? ', side margins dropped' : ''));
		var newStyle = '<style type="text/css">#' + this.options.shop + ' li {width: ' + newWidth + 'px;' + needMargin + '}</style>';
		this.shop.set('html', this.shop.get('html') + newStyle);
	}
	
});