var WMX = WMX || { };

WMX.EvoxGallery4 = Class.create({
	initialize: function(vehicleArray, parentDiv)
	{
		//Initialize variables //
		if (vehicleArray && parentDiv && vehicleArray.length > 0)
		{		
			this.fixArray(vehicleArray);
			
			for (i=0; i<=vehicleArray.length - 1; i++)
			{
				this.fixArray(vehicleArray[i].NormalPath);
			}

			if (vehicleArray.length == 0)
			{
				return;
			}

			this.vehicles = vehicleArray;
			this.parentContainer = $(parentDiv);
			this.finishValidator = 2;
			this.checkForMinis = 0;
			
			if ($('vehicleListWrapper'))
			{
				this.fillDropDown(this.vehicles, 'vehicleListWrapper');
				$('vehicleListWrapper').hide();
			}
			
			this.currentVehicle = 0;
			this.currentAngle = 0;
			this.reflectionEnabled = 1;
			
			if (Prototype.Browser.IE)
			{
				var isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') != -1;
				var isIE7 = navigator.userAgent.toLowerCase().indexOf('msie 7') != -1;
				
				if (isIE6 && !isIE7)
					this.reflectionEnabled = 0;
			}
			
			//Load first Image //
			this.changeImage(this.currentVehicle, this.currentAngle);
			
			//Add Events for image clicks //
			$('previousVehicleLink').observe('click', this.previousVehicle.bind(this));
			$('chooseButton').observe('click', this.showHideList.bind(this, 'vehicleListWrapper'));
			$('nextVehicleLink').observe('click', this.nextVehicle.bind(this));
		}
	},
	fixArray: function (a)
	{
		if (!a[a.length - 1])
		{
			a.pop();
		}
	},
	fillDropDown: function(vehicles, ele)
	{
		for (i=0; i<=vehicles.length - 1; i++)
		{
			var newElement = new Element('a').addClassName('modelSpan').update(vehicles[i].Descriptor).observe('click', this.changeVehicle.bind(this, i));
			newElement.href = '#';
			$(ele).insert(newElement);
		} 
	},
	insertIFrame: function(e)
	{
		var newFrame = new Element('iframe').addClassName('evoxFrameWrapper').setStyle({position: 'absolute', display: 'none', top: 0, left: 0, height: '100%', width: '100%'});
		$$('body')[0].insert(newFrame);
	},
	checkBodyOffset: function(e)
	{
		var bodyEleOffset = $$('body')[0].cumulativeScrollOffset();
		
		$$('.evoxFrameWrapper')[0].setStyle({
			top: bodyEleOffset[1] + 'px'
		});
	},
	showHideList: function(wrapperName, e)
	{
		e.stop();
		if ($(wrapperName).className == 'vehicleList_hidden')
		{
			$(wrapperName).appear({
						queue: { scope: this.parentContainer.identify() },
						duration: 0.5
					});
			$(wrapperName).className = 'vehicleList_visible';
		}
		else
		{
			$(wrapperName).fade({
						queue: { scope: this.parentContainer.identify() },
						duration: 0.5
					});
			$(wrapperName).className = 'vehicleList_hidden';
		}
	},
	hideList: function(e)
	{
		if ($('vehicleListWrapper').className == 'vehicleList_visible')
		{
			$('vehicleListWrapper').fade({
						duration: 0.25
					});
			$('vehicleListWrapper').className = 'vehicleList_hidden';
		}
	},
	checkToHideList: function(e)
	{
		if ($('vehicleListWrapper'))
		{
			this.hideList(e);
		}
	},
	preloadImages: function(vehicleIndex, imageIndex)
	{
		var nextVehicleIndex = (vehicleIndex == (this.vehicles.length - 1)) ? 0 : vehicleIndex + 1;
		var previousVehicleIndex = (vehicleIndex == 0) ? (this.vehicles.length - 1) : vehicleIndex - 1;
		var nextImageIndex = (imageIndex == (this.vehicles[vehicleIndex].NormalPath.length - 1)) ? 0 : imageIndex + 1;
		var previousImageIndex = (imageIndex == 0) ? (this.vehicles[vehicleIndex].NormalPath.length - 1) : imageIndex - 1;

		if (!this.vehicles[vehicleIndex].NormalImages[imageIndex])
		{
			var img = new Image();
			img.src = this.vehicles[vehicleIndex].NormalPath[imageIndex];
			
			this.vehicles[vehicleIndex].NormalImages[imageIndex] = $(img);
		}
		
		if (!this.vehicles[vehicleIndex].NormalImages[nextImageIndex])
		{
			var img = new Image();
			img.src = this.vehicles[vehicleIndex].NormalPath[nextImageIndex];

			this.vehicles[vehicleIndex].NormalImages[nextImageIndex] = $(img);
		}
				
		if (!this.vehicles[vehicleIndex].NormalImages[previousImageIndex])
		{
			var img = new Image();
			img.src = this.vehicles[vehicleIndex].NormalPath[previousImageIndex];
			
			this.vehicles[vehicleIndex].NormalImages[previousImageIndex] = $(img);
		}
		
		if (!this.vehicles[nextVehicleIndex].NormalImages[imageIndex])
		{
			var img = new Image();
			img.src = this.vehicles[nextVehicleIndex].NormalPath[imageIndex];
			
			this.vehicles[nextVehicleIndex].NormalImages[imageIndex] = $(img);
		}
		
		if (!this.vehicles[previousVehicleIndex].NormalImages[imageIndex])
		{
			var img = new Image();
			img.src = this.vehicles[previousVehicleIndex].NormalPath[imageIndex];
			
			this.vehicles[previousVehicleIndex].NormalImages[imageIndex] = $(img);
		}
	},
	changeEnlargeImage: function(vehicleIndex, imageIndex)
	{
		if (this.imageWaiter)
		{
			this.imageWaiter.stop();
			this.imageWaiter = null;
		}

		if (this.newimg.complete && this.finishValidator == 2)
		{
			this.finishValidator = 0;
			Effect.Queues.get(this.parentContainer.identify()).each(function(e) { e.cancel(); });

			this.newimg.hide();
			this.parentContainer.insert(this.newimg);

			if (Prototype.Browser.IE)
			{
				this.currentImage.remove();
				this.newimg.show();
				this.finishValidator++;
				this.finishValidator++;
				if (this.reflectionEnabled)
					this.reflectWaiter = new PeriodicalExecuter(this.reflect.bind(this, this.newimg), 0.01);
				$('vehicleName').innerHTML = this.vehicles[vehicleIndex].Descriptor;
			}
			else
			{
				this.newimg.appear({
					queue: { scope: this.parentContainer.identify() },
					duration: 0.5,
					afterFinish: this.afterAppearFinish.bind(this)
				});

				this.currentImage.fade({
					queue: { scope: this.parentContainer.identify()},
					duration: 0.5,
					afterFinish: this.afterFadeFinish.bind(this)
				});
				if (this.reflectionEnabled)
					this.reflectWaiter = new PeriodicalExecuter(this.reflect.bind(this, this.newimg), 0.25);
				$('vehicleName').innerHTML = this.vehicles[vehicleIndex].Descriptor;
			}
			this.currentImage = this.newimg;
			this.currentVehicle = vehicleIndex;
			this.currentAngle = imageIndex;

			this.preloadImages(vehicleIndex, imageIndex);
		}
		else
		{
			this.imageWaiter = new PeriodicalExecuter(this.changeImage.bind(this, vehicleIndex, imageIndex), 0.5);
		}
	},

	changeImage: function(vehicleIndex, imageIndex)
	{
		vehicleIndex = (vehicleIndex >= this.vehicles.length) ? 0 : vehicleIndex;
		vehicleIndex = (vehicleIndex < 0) ? (this.vehicles.length - 1) : vehicleIndex;
		imageIndex = (imageIndex >= this.vehicles[vehicleIndex].NormalPath.length) ? 0 : imageIndex;
		imageIndex = (imageIndex < 0) ? (this.vehicles[vehicleIndex].NormalPath.length - 1) : imageIndex;
		
		if(this.checkForMinis == 0)
		{		
			if (!this.currentImage)
			{
				this.currentImage = new Element('img');
				this.currentImage.src = this.vehicles[vehicleIndex].NormalPath[imageIndex];
				this.currentImage.id = "evoxImage";
				this.parentContainer.insert($(this.currentImage));

				this.currentVehicle = vehicleIndex;
				this.currentAngle = imageIndex;

				this.preloadImages(vehicleIndex, imageIndex);
				
				// Handles a bug where browsers render a blank reflection if the image isn't loaded yet.
				if (this.currentImage.complete) {
					if (this.reflectionEnabled)
						this.reflect(this.currentImage);
				}
				else
				{
					if (this.reflectionEnabled)
						this.reflectWaiter = new PeriodicalExecuter(this.reflect.bind(this, this.currentImage), 0.5);
				}
				$('vehicleName').innerHTML = this.vehicles[vehicleIndex].Descriptor;
			}		
			else
			{
				if (this.vehicles[vehicleIndex].NormalImages[imageIndex])
				{
					this.newimg = this.vehicles[vehicleIndex].NormalImages[imageIndex];
					this.changeEnlargeImage(vehicleIndex, imageIndex);
				}
			}
		}
	},
	afterAppearFinish: function(e)
	{
		this.finishValidator++;	
	},
	afterFadeFinish: function(e)
	{
		e.element.remove();
		this.finishValidator++;	
	},	
	changeVehicle: function(vehicleIndex, e)
	{
		e.stop();
		this.preloadImages(vehicleIndex, this.currentAngle);
		this.checkToHideList(this);
		if (this.currentVehicle == vehicleIndex)
		{
			return;
		}
		else
		{
			this.changeImage(vehicleIndex, this.currentAngle);
		}
	},
	nextVehicle: function(e)
	{
		e.stop();
		this.checkToHideList(this);
		this.changeImage(this.currentVehicle + 1, this.currentAngle);
	},
	previousVehicle: function(e)
	{
		e.stop();
		this.checkToHideList(this);
		this.changeImage(this.currentVehicle - 1, this.currentAngle);
	},
	reflect: function(ele) {
		ele = $(ele);
		
		if (this.currentImage.complete && this.reflectWaiter)
			this.reflectWaiter.stop();

		opt = { };
		opt.opacity = 0.5;
		opt.height = 0.5;
		opt.bottomOffset = 0;
		opt.topOffset = 0;

		try {
			var divHeight = Math.floor(ele.getHeight() * (1 + opt.height)) - opt.bottomOffset - opt.topOffset;
			var reflectionHeight = Math.floor(ele.getHeight() * opt.height);
			var reflectionWidth = ele.getWidth();

			var div = $('evoxGalleryVehicle');
			
			var canvas = $('evoxCanvas') || new Element('canvas');
			if (canvas.getContext) {
				var context = canvas.getContext("2d");

				wrapTop = ele.getHeight();
				wrapTop = wrapTop - 25; /* Fix to make reflection higher. */
				
				canvas.setStyle({
					height: reflectionHeight + 'px',
					width: reflectionWidth + 'px',
					top: wrapTop + 'px',
					position: 'relative'
				});

				canvas.id = "evoxCanvas";
				canvas.addClassName('reflection');
				canvas.height = reflectionHeight;
				canvas.width = reflectionWidth;

				div.insert(ele).insert(canvas);

				context.save();

				context.translate(0, ele.getHeight() - 1);
				context.scale(1, -1);
				context.drawImage(ele, 0, opt.bottomOffset, reflectionWidth, ele.getHeight());
				context.restore();
				context.globalCompositeOperation = "destination-out";

				var gradient = context.createLinearGradient(0, 0, 0, reflectionHeight);
				gradient.addColorStop(1, "rgba(255, 255, 255, 1.0)");
				gradient.addColorStop(0, "rgba(255, 255, 255, " + (1 - opt.opacity) + ")");
				context.fillStyle = gradient;

				context.fillRect(0, 0, reflectionWidth, reflectionHeight * 2);
			}
			else {
				var oldImgWrap = $('evoxWrap');
				if (oldImgWrap)
				{
					oldImgWrap.remove();
				}
				
				var reflection = new Element('img');
				reflection.src = ele.src;
				reflection.style.width = reflectionWidth + 'px';
				reflection.style.marginBottom = "-"+ (ele.getHeight() - reflectionHeight) + 'px';
				reflection.style.filter = 'flipv progid:DXImageTransform.Microsoft.Alpha(opacity=' + (opt.opacity * 100) + ', style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy=' + (opt.height * 100) + ')';

				ele.parentNode.replaceChild(div, ele);

				wrapTop = reflectionHeight / opt.height;
				wrapTop = wrapTop - 25; /* Fix to make drop shadow closer to image. */

				var imgWrap = new Element('div').setStyle({
					position: 'relative',
					overflow: 'hidden',
					width: reflectionWidth,
					height: reflectionHeight - opt.bottomOffset,
					top: wrapTop
				}).addClassName('reflection');
				
				imgWrap.id = "evoxWrap";
				imgWrap.insert(reflection);

				reflection.setStyle({
					position: 'relative',
					top: -opt.bottomOffset
				});

				div.appendChild(ele);
				div.appendChild(imgWrap);
			}
		}
		catch (ex) 
		{
		}
	}
});
