enjoyImageTransition = {};

if (typeof(Prototype) == 'undefined')
{
	this.errors = 'enjoyImageTransition: Prototype is not loaded - it is required';
}

enjoyImageTransition = Class.create(
{
	errors: '',
	
	initialize: function()
	{
		// First grab configuration options
		this.options = Object.extend(
		{
			containerId:				null,								// ID of Container - DIV to hold the images
			containerElement:			undefined,							// actual container element - extended by Prototype
			staticImageId:				null,								// ID for the static image
			staticImageElement:			undefined,							// actual static img element - extended by Prototype
			linkContainerId:			null,								// ID for element that contains the A tags that point to the images
			linkContainerElement:		undefined,							// actual element containing the A tags - extended by Prototype
			imageCount:					0,									// determined number of images
			imagesLoaded:				0,									// count of images actually loaded
			switchInterval:				1500,								// time in milli-seconds between interchanges
			transitionTime:				1.2,								// time in seconds for EFFECT
			randomOrder:				false,								// show images in a random order
			debugMode:					false,								// alert you when it encounters an error
			maxHeight:					0,									// if not 0, images will be scaled to a maximum height (keeping aspect ratio)
			maxWidth:					0,									// if not 0, images will be scaled to a maximum width (keeping aspect ratio)
			uniqueIndex:				Math.floor(Math.random()*1000),		// used to provide unique IDs to elements created by the script when used more than once on a page
			currentImageIndex:			0,									// index of currently shown image - provide this value when not starting from the first image in the list
			activeImageIndex:			0,
			lowestZIndex:				500,								// alter this if your images need to be above/below other elements on the page
			callbackName:				null								// declared name in javascript so we can use a simple call-back
			
		}, arguments[0] || {});
		
		// Check callback name specified
		this.checkCallbackName();
		if (this.errors != '') return;
		
		// Check libraries are loaded
		this.libraryCheckResult = this.libraryCheck();
		if (this.errors != '') return;
		
		// Identify elements
		this.identifyElements();
		if (this.errors != '') return;
		
		this.images = {};
		
		// Pre-Load images
		this.preLoadImages();
		if (this.errors != '' && this.options.debugMode) { alert(this.errors); return; }
	},
	
	checkCallbackName: function()
	{
		if (this.options.callbackName == null)
		{
			this.errors = 'enjoyImageTransition: No callback name defined - unable to continue';
		}
		
		if (this.errors != '' && this.options.debugMode)
		{
			alert(this.errors);
		}
	},
	
	libraryCheck: function()
	{
		var result = {pVersion: 0, sVersion: 0};
		
		if (typeof(Prototype) == 'undefined')
		{
			this.errors = 'enjoyImageTransition: Prototype is not loaded - it is required';
		}
		if (typeof(Scriptaculous) == 'undefined')
		{
			this.errors = 'enjoyImageTransition: Scriptaculous is not loaded - it is required';
		}		

		if (this.errors == '')
		{
			result.pVersion = Prototype.Version;
			result.sVersion = Scriptaculous.Version;
		}
		else if (this.options.debugMode)
		{
			alert(this.errors);
		}
		return result;
	},
	
	identifyElements: function()
	{
		// CONTAINER
		if (this.options.containerId != null)
		{
			this.options.containerElement = $(this.options.containerId);
		}
		else if (this.options.containerElement != null)
		{
			this.options.containerId = this.options.containerElement.id;
		}
		else this.errors = 'enjoyImageTransition: Unknown Container';
		
		// STATIC IMAGE
		if (this.options.staticImageId != null)
		{
			this.options.staticImageElement = $(this.options.staticImageId);
		}
		else if(this.options.staticImageElement != null)
		{
			this.options.staticImageId = this.options.staticImageElement.id;
		}
		else this.errors = 'enjoyImageTransition: Unknown Static Image';
		
		// LINK CONTAINER
		if (this.options.linkContainerId != null)
		{
			this.options.linkContainerElement = $(this.options.linkContainerId);
		}
		else if(this.options.linkContainerElement != null)
		{
			this.options.linkContainerId = this.options.linkContainerElement.id;
		}
		else this.errors = 'enjoyImageTransition: Unknown Link Container';
		
		if (this.errors != '' && this.options.debugMode)
		{
			alert(this.errors);
		}
	},
	
	preLoadImages: function()
	{
		var aTags = this.options.linkContainerElement.select('a');
		this.options.imageCount = aTags.length;
		
		for(var i=0; i<aTags.length; i++)
		{
			this.images[i] = 
				{
					url: aTags[i].href, 
					alt: aTags[i].title, 
					img: new Image(),
					staticId: 'njIT_' + this.options.uniqueIndex + '_s_' + i
				};
			
			// Create a static image for this
			var t = document.createElement('img');
			t.id = 'njIT_' + this.options.uniqueIndex + '_s_' + i;
			t.alt = aTags[i].title;
			t.src = '';
			t.style.display = 'none';
			t.style.position = 'absolute';
			t.style.left = '0px';
			t.style.top = '0px';
			
			// Drop NEW static image into the container
			Element.insert(this.options.containerId, { bottom: t });
			
			// Configure the pre-load image
			this.images[i].img.id = 'njIT_' + this.options.uniqueIndex + '_j_' + i;
			this.images[i].img.title = 'njIT_' + this.options.uniqueIndex + '_s_' + i;
			this.images[i].img.alt = i;
			
			// Arrange call-back once the image is loaded
			Event.observe(this.images[i].img, 'load', this.imgLoadedHandler.bindAsEventListener(this));
			Event.observe(this.images[i].img, 'error', this.imgLoadedHandler.bindAsEventListener(this));
			
			// Begin loading the image into the pre-loader
			this.images[i].img.src = this.images[i].url;
		}		
	},
	
	imgLoadedHandler: function(eventArgs)
	{
		var img = Event.element(eventArgs);
		
		if (eventArgs.type == 'load')
		{
			if (img.title != null && $(img.title) != undefined)
			{
				$(img.title).src = img.src;
				
				// Determine size
				var size = this.newImageSize(img);
				
				$(img.title).height = size.height;
				$(img.title).width = size.width;
				// Show elements but make them transparent
				new Effect.Opacity(img.title, {from: 0, to: 0.0, duration: 0});
				//$(img.title).style.display = '';
			}
		}
		else if(eventArgs.type == 'error')
		{
			this.errors = 'Failed to load: ' + img.src + '\n';
			delete this.images[parseInt(img.alt)];
		}
		
		this.options.imagesLoaded++;
		if (this.options.imagesLoaded == this.options.imageCount)
		{
			//setTimeout(this.options.callbackName + '.beginTransitions();', this.options.switchInterval);
		}
	},
	
	newImageSize: function(img)
	{
		var w = img.width;
		var h = img.height;
		var ar = h/w;
		
		var newW = w;
		var newH = h;
		
		if ((this.options.maxWidth > 0 && w > this.options.maxWidth) || (this.options.maxHeight > 0 && h > this.options.maxHeight))
		{
			// Resize
			if (w > h)
			{
				// Landscape
				newW = this.options.maxWidth;
				newH = this.options.maxWidth * ar;
			}
			else
			{
				// Portrait
				newH = this.options.maxHeight;
				newW = this.options.maxHeight / ar;
			}
		}
		
		return { width: newW, height: newH };
	},
	
	beginTransitions: function()
	{
		var nextIndex = -1;
		var curIndex = this.options.currentImageIndex;
		var activeIndex = this.options.activeImageIndex;
		
		while (this.images[nextIndex] == undefined || nextIndex == this.options.currentImageIndex)
		{
			nextIndex = this.nextImageIndex(curIndex);
			curIndex++;
			if (curIndex >= this.options.imageCount) curIndex = -1;
		}
				
		if (this.options.staticImageElement.style.display != 'none')
		{
			// Transition from original static
			this.options.staticImageElement.style.zIndex = this.options.lowestZIndex;
			new Effect.Opacity(this.options.staticImageId, {from: 1, to: 0, duration: this.options.transitionTime});
			
			setTimeout(this.options.callbackName + '.hideOriginal();', this.options.switchInterval);
		}
		else
		{
			$(this.images[this.options.activeImageIndex].staticId).style.zIndex = this.options.lowestZIndex;
			new Effect.Opacity(this.images[this.options.activeImageIndex].staticId, {from: 1, to: 0, duration: this.options.transitionTime});
		}
		
		$(this.images[nextIndex].staticId).style.display = '';
		$(this.images[nextIndex].staticId).style.zIndex = this.options.lowestZIndex+1;
		new Effect.Opacity(this.images[nextIndex].staticId, {from: 0, to: 1, duration: this.options.transitionTime});
		this.options.activeImageIndex = nextIndex;

		resetBrands();

		strImage  = document.getElementById('logo_'+(nextIndex+1)).src
		newstrImage = strImage.replace("_off", "_on");		
		
		document.getElementById('logo_'+(nextIndex+1)).src = newstrImage;
		
		
		
		this.options.currentImageIndex = nextIndex;
	},
	
	hideOriginal: function()
	{
		this.options.staticImageElement.style.display = 'none';
	},
	
	nextImageIndex: function(curIndex)
	{
		var nextIndex = 0;
		if (this.options.randomOrder)
		{
			nextIndex = Math.floor(Math.random()*this.options.imageCount);
		}
		else nextIndex = curIndex+1;
		
		if (nextIndex >= this.options.imageCount) nextIndex = -1;
		
		return nextIndex;
	}
});
