GalleryPromo = Class.create({
	options: {
		json: 'gallery-promo.json', // Path to promo json file
		spanId: 'gallery-promo-', // string prepended to ID of each element (followed by their index #)
		spanClass: 'case-' // string prepended to class attribute of each element (followed by the case number; 0-4)
	},

	initialize: function(container, options) {
		// Merge options with defaults
		if(!options) options = {};
		Object.extend(this.options,options);

		// Define container
		this.container = container;
		
		// If container exists, start building the promo
		if(this.container){
			// Get json data from file
			this.getData();
		}
	},

	getData: function(){
		new Ajax.Request(this.options.json, {
			method: 'get',
			onSuccess: function(rsp){
				// If file returns json, then store it as this.data
				this.data = rsp.responseJSON ? rsp.responseJSON : rsp.responseText.evalJSON();
				this.data = this.data.promo ? this.data.promo : this.data;

				// If data exists
				if(this.data){
					// Find out which case we’re dealing with
					this.getCase();
					
					// Build span for each image
					this.data.each(function(obj, i){ this.buildImage(obj, i); }.bind(this));
					
					// Add 'more' link after images
					this.container.insert(new Element('em',{ 'class': 'more' }).update('View gallery'));
				}
			}.bind(this)
		});
	},

	buildImage: function(obj, i){
		// Create span element
		var el = new Element('span', {
			'id': this.options.spanId + i,
			'class': 'img ' + this.options.spanClass + this._case
		})

		// Apply styles as per data
		el.setStyle({
			'backgroundImage': 'url('+obj.thumb+')',
			'width': obj.promoWidth + 'px',
			'height': obj.promoHeight + 'px'
		});

		// If data object has a margin style, set it
		// This happens with two short/wide images
		if(obj.promoMargin && obj.promoMargin !== null && obj.promoMargin !== ''){
			el.setStyle({
				'margin': obj.promoMargin
			});
		}

		// Inject it into the container
		this.container.insert(el);
	},

	getCase: function(){
		// If you have three images, you’re in case 0
		if(this.data.length === 3){
			this._case = 0;

		// If you have 2 images, you’re either in case 1 or 2
		} else if (this.data.length === 2){
			// If the width is smaller than the height, you’re in case 1
			if(parseFloat(this.data[0].promoWidth) < parseFloat(this.data[0].promoHeight)){
				this._case = 1;
			
			// If the width is bigger than height, case 2
			} else {
				this._case = 2;
			}

		// If you have 1 image, you’re either in case 3 or 4
		} else {
			// If the width is smaller than the height, you’re in case 3
			if(parseFloat(this.data[0].promoWidth) < parseFloat(this.data[0].promoHeight)){
				this._case = 3;
			
			// If the width is bigger than height, case 4
			} else {
				this._case = 4;
			}
		}
	}
});
