/*--------------------------------------------------------------------------*
 * 
 * Copyright (C) 2010 Brand Labs LLC
 * 
 * Change Product Photo Fix 
 * 	Intended to remedy the Volusion bug associated with alternate view images
 * 	that may have file extension differences between sizes. 
 * 
 * Version 1.0.0
 * 
 *--------------------------------------------------------------------------*/
var ChangeProductPhotoFix = {
	LOADED: false,
	
	load: function() {
		//PRODUCT				
		//Only load on the product detail page (per Volusion KB)
		if (location.pathname.toLowerCase() == '/productdetails.asp' ||
		location.pathname.toLowerCase().indexOf('-p/') != -1 ||
		location.pathname.toLowerCase().indexOf('_p/') != -1) {				
		
			//Make sure not to load twice
			if (ChangeProductPhotoFix.LOADED) {
				return;
			}
			ChangeProductPhotoFix.LOADED = true;
			
			//Start when DOM is loaded
			document.observe('dom:loaded', ChangeProductPhotoFix.domLoaded);				
		}
	},
	
	domLoaded: function() {
		try {
			//Create photo gallery			
			new AlternateImageHandler();
		}
		catch(e) {/*Ignore*/}		
	}
};

var AlternateImageHandler = Class.create({
	initialize: function() {
		try {			
			//If the change product photo function is not defined, just exit
			if (typeof change_product_photo == 'undefined') {
				return;
			}
			this.changeProductPhotoFunction = change_product_photo;
			//Proxy the change product photo function
			change_product_photo = this.changeProductPhotoProxy.bind(this);
			
			//Setup event listener
			Event.observe(window, 'load', this.load.bind(this));
		}
		catch(e){/*Ignore*/}
	},
	
	load: function() {
		try {
			//Locate the main product photo, exit if not available
			this.productPhotoImg = $('product_photo');
			if (this.productPhotoImg == null) {
				return;
			}

		}
		catch(e){/*Ignore*/}				
	},
	
	changeProductPhotoProxy: function(arg_photo_number) {
		try {			
			//var thisObj = this;
			var photoElement = new Element('img', {});
			
			//Call proxied function
			this.changeProductPhotoFunction(arg_photo_number);
			
			Event.observe(photoElement, 'error', this.checkAlternateExtension.bind(this, photoElement));
			//Add the source of the image, so it can start to load
			photoElement.writeAttribute('src', this.productPhotoImg.readAttribute('src'));
		}
		catch(e){/*Ignore*/}
	},
	
	checkAlternateExtension: function(photoElement) {
		//Make sure we have an element
		if(photoElement == null) {
			return;
		}
			
		//Remove events
		Event.stopObserving(photoElement);
		
		matches = photoElement.readAttribute('src').match(/(\/v\/vspfiles\/.*\/.*\-\d[a-zA-z])(\.\w*)/i);
		if (matches != null && matches.length > 1 && matches[1] != null && matches[2] != null) {
			extension = matches[2];
			
			imgURL = matches[1] + (extension.toLowerCase() == '.gif' ? '.jpg' : '.gif'); 

			this.productPhotoImg.writeAttribute('src', imgURL);
		}
	}

});

//Attempt to load CPPF
try {
	ChangeProductPhotoFix.load();
}
catch(e) {/*Ignore*/}