/*--------------------------------------------------------------------------*
 * 
 * Alternate Photos Quick Preview (Diversion)
 * 
 * Version 1.0.4
 * 
 * Copyright (C) 2010 Brand Labs LLC
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  
 * 02110-1301  USA
 * 
 *--------------------------------------------------------------------------*/

/*--------------------------------------------------------------------------*
 * Settings
 *--------------------------------------------------------------------------*/
var DiversionSettings = {
	ENABLED: true,
		
	PHOTOS_PATH: '/v/vspfiles/photos',
	MAIN_PHOTO_ID: 'product_photo',
	ALTERNATE_PHOTO_ID_TEMPLATE: new Template('alternate_product_photo_#{photoIndex}'),
	NOT_EQUAL_SIZE_IGNORE: false,
	FORCE_QUICK_PREVIEW_WINDOW: false,
	FORCE_MAIN_PREVIEW: false,
	QUICK_PREVIEW_WINDOW_OFFSET_TOP: 0,
	QUICK_PREVIEW_WINDOW_OFFSET_LEFT: 0,
	PHOTO_SIZE_NAME: 'T' /*Medium Photo*/
};
/*--------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------*
 * Main module to initiate
 *--------------------------------------------------------------------------*/
var Diversion = {
	load: function() {
		//Make sure enabled, if not exit
		if(!DiversionSettings.ENABLED) {
			return;
		}
		
		//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) {
			
			//Setup everything
			Diversion.setup();
		}		
	},
	
	setup: function() {
		var photoIndex = 2;
		var element = null;
		var elements = new Array();
		var width;
		var height;
		var equalSize = true;
		var productCode = null;
		var mainPhotoElement = null;
		
		try {
			//Get the main photo element
			mainPhotoElement = $(DiversionSettings.MAIN_PHOTO_ID);
			//Exit if no element is available
			if(mainPhotoElement == null) {
				return;
			}
			
			element = $(DiversionSettings.ALTERNATE_PHOTO_ID_TEMPLATE.evaluate({photoIndex: photoIndex}));					
			//No starting element, skip
			if(element == null || !element.getWidth || !element.getHeight) {
				return;
			}
			//Get first height and width
			width = element.getWidth();
			height = element.getHeight();
		
			while($( DiversionSettings.ALTERNATE_PHOTO_ID_TEMPLATE.evaluate({photoIndex: photoIndex}) ) != null) {
				element = $( DiversionSettings.ALTERNATE_PHOTO_ID_TEMPLATE.evaluate({photoIndex: photoIndex}) );						
				elements.push(element);						
				
				//See if there is any variation in the size
				if(element.getWidth() != width || element.getHeight() != height) {
					equalSize = false;
				}						
				
				photoIndex++;
			}
	
			//Change setting if forcing window
			if(DiversionSettings.FORCE_QUICK_PREVIEW_WINDOW && DiversionSettings.FORCE_MAIN_PREVIEW) {
				//Cannot use both settings at once
				throw 'Incorrect configuration for Diversion';
			}
			if(DiversionSettings.FORCE_QUICK_PREVIEW_WINDOW) {
				equalSize = false;
			}
			if(DiversionSettings.FORCE_MAIN_PREVIEW) {
				equalSize = true;
			}

			//Create the new objects based on what was discovered
			elements.each(function(item, index) {
				var matches = null;
				//Get Product Code from the image source
				matches = item.readAttribute('src').match(/\/v\/vspfiles\/.*\/(.*)\-\d+S\.\w*/i);
				if (matches != null && matches.length > 0 && matches[1] != null) {
					productCode = matches[1];
				} else {
					return;
				}
				
				if(equalSize) {					
					new DiversionMainImageQuickPreview(productCode, (index+2), item, mainPhotoElement); /*Starting at 2*/	
				}
				else {
					if(!DiversionSettings.NOT_EQUAL_SIZE_IGNORE) { //Setting turns off pop-out
						new DiversionQuickPreview(productCode, (index+2), item); /*Starting at 2*/
					}
				}			
			});			
		}
		catch(e) {/*Ignore*/}		
	}
};
/*--------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------*
 * Start up the module
 *--------------------------------------------------------------------------*/
Event.observe(window, 'load', Diversion.load);
/*--------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------*
 * Display alternate image in separate area
 *--------------------------------------------------------------------------*/
var DiversionQuickPreview = Class.create({
	initialize: function(productCode, photoNumber, alternateElement) {
		var body;
		var image;
		
		try {
			body = $$('body').first();
		}
		catch(e) {}
		
		//Make sure there is a body element
		if(body == null) {
			return;
		}
		
		//Make sure we have the element
		if(alternateElement == null) {
			return;
		}
		
		this.productCode = productCode;
		this.alternateElement = alternateElement;
		this.photoNumber = photoNumber;
		
		//Store the file extensions
		this.fileExtension = this.extractFileExtension(alternateElement.src);
		this.fileExtension = this.fileExtension == null ? 'jpg' : this.fileExtension;
				
		//Create the popup element
		this.thumbnailElement = new Element('div', {
			id: 'diversion_quick_preview_' + photoNumber
		});
		this.thumbnailElement.addClassName('diversion_quick_preview');
		this.thumbnailElement.setStyle({
			position: 'absolute',					
			display: 'none',
			zIndex: 102
		});
		image = new Element('img', {
			src: this.getThumbnailFileName(),
			alt: this.alternateElement.alt,
			title: this.alternateElement.title
		});
		this.thumbnailElement.update(image);
		body.insert(this.thumbnailElement);	
		
		//Monitor events for this element
		Event.observe(
			alternateElement, 
			'mouseover', 
			this.mouseOver.bindAsEventListener(this)
		);
		Event.observe(
			alternateElement, 
			'mouseout', 
			this.mouseOut.bindAsEventListener(this)
		);
	},
	
	mouseOver: function() {
		var alternateElementPosition;
		
		//Make sure objects are available
		if(this.alternateElement == null || this.thumbnailElement == null) {
			return;
		}
		
		//Get the position of the element
		alternateElementPosition = this.alternateElement.positionedOffset();

		//Position might change, so reset the position		
		this.thumbnailElement.setStyle({
			top: (alternateElementPosition.top+DiversionSettings.QUICK_PREVIEW_WINDOW_OFFSET_TOP) + 'px',
			left: (alternateElementPosition.left+this.alternateElement.getWidth()+DiversionSettings.QUICK_PREVIEW_WINDOW_OFFSET_LEFT) + 'px'					
		});	
	
		this.showElement(this.thumbnailElement);
	},
	
	mouseOut: function() {
		//Make sure we have an element
		if(this.thumbnailElement == null) {
			return;
		}				
		
		this.hideElement(this.thumbnailElement);
	},
	
	getThumbnailFileName: function() {
		var filename;				
		
		//Construct file name
		filename = DiversionSettings.PHOTOS_PATH
			+ "/" 
			+ this.productCode
			+ "-"
			+ this.photoNumber
			+ DiversionSettings.PHOTO_SIZE_NAME
			+ '.'
			+ this.fileExtension;
		
		return filename;
	},
	
	extractFileExtension: function(url) {
		var index;
		
		try {
			if (url == null || !url.lastIndexOf) {
				return null;
			}
			
			//Get the location of index
			index = url.lastIndexOf('.');
			
			//Make sure location was found, could be -1
			if (index < 0) {
				return null;
			}
			
			//Return the extension
			return url.substring(index + 1);
		}
		catch(e) {/*No-op*/}
		
		return null;
	},
	
	showElement: function(element) {
		element.show();
	},
	
	hideElement: function(element) {
		element.hide();				
	}
});
/*--------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------*
 * Display alternate photo in main photo
 *--------------------------------------------------------------------------*/
var DiversionMainImageQuickPreview = Class.create(DiversionQuickPreview, {
	initialize: function(productCode, photoNumber, alternateElement, mainElement) {
		//Make sure we have the elements
		if(mainElement == null || alternateElement == null) {
			return;
		}				
	
		this.productCode = productCode;
		this.photoNumber = photoNumber;
		this.mainElement = mainElement;
		
		//Store the file extensions
		this.fileExtension = this.extractFileExtension(alternateElement.src);
		this.fileExtension = this.fileExtension == null ? 'jpg' : this.fileExtension;
		
		//Copy the original source
		this.originalFileName = mainElement.src;
		
		//Monitor events
		Event.observe(
			alternateElement, 
			'mouseover', 
			this.mouseOver.bindAsEventListener(this)
		);
		Event.observe(
			alternateElement, 
			'mouseout', 
			this.mouseOut.bindAsEventListener(this)
		);
		Event.observe(
			alternateElement,
			'click',
			this.click.bindAsEventListener(this)
		);
	},
	
	mouseOver: function() {
		//Make sure we have the element
		if(this.mainElement == null) {
			return;
		}
		
		//Copy the original source
		this.originalFileName = this.mainElement.src;
		
		//Change to the desired photo
		this.mainElement.src = this.getThumbnailFileName();
	},
	
	mouseOut: function() {
		//Make sure we have the element
		if(this.mainElement == null) {
			return;
		}
		
		//Revert back to the original
		this.mainElement.src = this.originalFileName;
	},
	
	click: function() {
		//Update the local file name for mouseout
		this.originalFileName = this.getThumbnailFileName();
	}			
});
/*--------------------------------------------------------------------------*/
