/*
* Class for tweening between a number of images that are linked to different urls or returning a random image
*/
var Slideshow = new Class({
	Implements: [Options],
	
	containerWidth: 100, // this is set to the width of the widest image in the slideshow
	
	// the default options
	options: {
		container: null, // a dom element that acts as the container for the slideshow
		items: [], // array of objects: {url: 'url to link to', image: 'the source of the image', width: 'image width', height: 'image height', altText: 'alt/title text of the image'}
		type: 'slideshow', // can be "slideshow" or "random"
		slideshowOptions: {
			slideDuration: 1000, // duration for the tween effect in milliseconds
			waitDuration: 5000, // the duration that each image is shown in milliseconds
			nextPrevNav: true,
			autoSlide: false,
			useThumbnails: false,
			useDots: false, // display a row of dots below the slideshow that can be used to navigate between images
			transitionType: 'fade', // fade or slide
			transitionFx: Fx.Transitions.Cubic.easeOut
		}
	},
	
	// constructor
	initialize: function(options) {
		this.setOptions(options, this.getOptions); 
		
		this.currentItemIndex = 0;
		this.newItemIndex = 0;
		this.zIndex = 1000;
		
		switch (this.options.type) {
			case 'slideshow':
				this.slideshow();
			break;
			case 'random':
				this.random();
			break;
			default: 
				this.slideshow();
			break;
		}
	},
	
	// type = slideshow
	slideshow: function() {
		if ($chk($(this.options.container)) && this.options.items) {
			// build DOM
			this.options.items.each(function(item, index) { 
				if (index > 0 && $chk($(this.options.items[0].id))) { // if the first element already exists
					var image = new Asset.image(item.image, {
						onload: function(item, index) {
							var linkedImage;
							if (item.url) {
								linkedImage = new Element('a', { href: item.url });
								image.inject(linkedImage);
							} else {
								linkedImage = image;
							}
							var itemDiv = new Element('div', {
								id: item.id,
								'class': 'tx-byggfabriken-slideshow-item',
								styles: {
									width: item.width
								}
							});
							linkedImage.inject(itemDiv);
							itemDiv.inject($(this.options.container, 'bottom'));
							itemDiv.set('tween', { 
								duration: this.options.slideshowOptions.slideDuration, 
								transition: this.options.slideshowOptions.transitionType == 'fade' ? Fx.Transitions.Linear : this.options.slideshowOptions.transitionFx,
								fps: 40
							});
							if (this.options.hasCaptions) {
								var caption = new Element('p', {text: ' ' + item.text}).inject(itemDiv);
								var dot = item.title && item.text ? '.' : '';
								new Element('span', {'class': 'tx-byggfabriken-slideshow-title' , text: item.title + dot}).inject(caption, 'top');
							}
						}.bind(this, [item, index]),
						border: 0,
						width: item.width,
						height: item.height,
						alt: item.altText,
						title: item.altText
					});
				} else {
					// the first item that already exists
					$(item.id).set('tween', { 
						duration: this.options.slideshowOptions.slideDuration, 
						transition: this.options.slideshowOptions.transitionType == 'fade' ? Fx.Transitions.Linear : this.options.slideshowOptions.transitionFx,
						fps: 40
					});
				}
				if (item.width > this.containerWidth) {
					this.containerWidth = item.width;
				}
			}, this);
			
			// inject next and prev links if we want this
			if (this.options.slideshowOptions.nextPrevNav) {
				new Element('div', {
					'class': 'tx-byggfabriken-slideshow-prev tx-byggfabriken-slideshow-nav',
					styles: {
						top: (this.options.items[0].height / 2) - 32
					},
					events: {
						'click': this.slidePrevious.bind(this)
					}
				}).inject($(this.options.container), 'bottom');
				new Element('div', {
					'class': 'tx-byggfabriken-slideshow-next tx-byggfabriken-slideshow-nav',
					styles: {
						top: (this.options.items[0].height / 2) - 32
					},
					events: {
						'click': this.slideNext.bind(this)
					}
				}).inject($(this.options.container), 'bottom');
				
				// hide nav on mouseout
				$(this.options.container).addEvent('mouseenter', function() {
					this.showNextPrevNav();
				}.bind(this)).addEvent('mouseleave', function() {
					this.hideNextPrevNav();
				}.bind(this));
			}
			
			// add events to thumbnails and dots
			if (this.options.slideshowOptions.useThumbnails || this.options.slideshowOptions.useDots) {
				$$('#tx-byggfabriken-slideshow-' + this.options.id + '-thumbs li', '#tx-byggfabriken-slideshow-' + this.options.id + '-dots li').addEvent('click', function(event) {
					var element;
					if (event.target.get('tag') == 'li') {
						element = event.target;
					} else {
						element = event.target.getParent();
					}
					var index = this.getIndexFromId(element.id)
					if (index != this.currentItemIndex) {
						this.slideTo(index);
					}
					this.hideNextPrevNav();
				}.bindWithEvent(this)).set('tween', {duration: this.options.slideshowOptions.slideDuration});
			}
			
			// set the width of the container element 
			$(this.options.container).setStyle('width', this.containerWidth);
			
			// start slide
			if (this.options.slideshowOptions.autoSlide) {
				this.slideNext.periodical(this.options.slideshowOptions.waitDuration, this);
			}
		}
	},
	
	// slides to the next/previous image
	slide: function(direction) {
		var indexToSlideTo;
		// if we're at the last item and direction is forward, we want to go to the first item
		if (this.currentItemIndex == this.options.items.length - 1 && direction > 0) {
			indexToSlideTo = 0;
		// if we're at the first item and direction is backword, we want to go to the last item
		} else if (this.currentItemIndex == 0 && direction < 1) {
			indexToSlideTo = this.options.items.length - 1;
		} else {
			indexToSlideTo = this.currentItemIndex + direction;
		}
		this.slideTo(indexToSlideTo);
	},
	
	slideNext: function() { 
		this.slide(1);
	},
	
	slidePrevious: function() { 
		this.slide(-1);
	},
	
	// slides to a specific image
	slideTo: function(index) {
		var previousIndex = this.currentItemIndex;
		if (this.options.slideshowOptions.transitionType == 'fade') {
			// fade out old and fade in new
			$(this.options.items[this.currentItemIndex].id).tween('opacity', 1, 0);
			$(this.options.items[index].id).tween('opacity', 0, 1);
			// increase x-index (so the right link and title text is on top)
			// we'll delay the call to this function so it happens after the slide is finished
			this.increaseZIndex.delay(this.options.slideshowOptions.slideDuration, this, $(this.options.items[index].id));
		} else {
			// slide out old and slide in new
			if ((this.currentItemIndex < index  && !(this.currentItemIndex == 0 && index == this.options.items.length - 1)) || (index == 0 && this.currentItemIndex == this.options.items.length - 1)) {
				// slide right to left
				var newItemStartPosition = (this.containerWidth + 10) + 'px';
				var currentItemEndPosition = '-' + (this.containerWidth + 10) + 'px';
			} else {
				// left to right
				var newItemStartPosition = '-' + (this.containerWidth + 10) + 'px';
				var currentItemEndPosition = (this.containerWidth + 10) + 'px';
			}
			$(this.options.items[index].id).setStyles({left: newItemStartPosition, visibility: 'visible', opacity: 1});
			this.increaseZIndex($(this.options.items[index].id));
			$(this.options.items[index].id).tween('left', 0);
			$(this.options.items[this.currentItemIndex].id).setStyle('left', 0);
			$(this.options.items[this.currentItemIndex].id).tween('left', currentItemEndPosition);
			
		}
		
		// set current to new
		this.currentItemIndex = index;
		
		this.markCurrentThumbOrDot(this.options.items[index], this.options.items[previousIndex]);
	},
	
	// increases the z-index so the link points to the right place
	increaseZIndex: function(element) { 
		element.setStyle('z-index', this.zIndex++); 
	},
	
	markCurrentThumbOrDot: function(item, previousItem) {
		if (this.options.slideshowOptions.useThumbnails) {
			// tween previous to inactive
			$('tx-byggfabriken-slideshow-' + previousItem.hash + '-' + previousItem.index + '-thumb').getFirst('img').tween('border-color', '#fff');
			// tween current to active
			$('tx-byggfabriken-slideshow-' + item.hash + '-' + item.index + '-thumb').getFirst('img').tween('border-color', '#666');
		}
		if (this.options.slideshowOptions.useDots) {
			// tween previous to inactive
			$('tx-byggfabriken-slideshow-' + previousItem.hash + '-' + previousItem.index + '-dot').tween('color', '#bbb');
			// tween current to active
			$('tx-byggfabriken-slideshow-' + item.hash + '-' + item.index + '-dot').tween('color', '#000');
		}
	},
	
	showNextPrevNav: function() {
		if (Browser.ie) {
			$$('#tx-byggfabriken-slideshow-' + this.options.id + '-container .tx-byggfabriken-slideshow-nav').fade('show'); // IE is having trouble fading png with alpha
		} else {
			$$('#tx-byggfabriken-slideshow-' + this.options.id + '-container .tx-byggfabriken-slideshow-nav').fade('in');
		}
	},
	
	hideNextPrevNav: function() {
		if (Browser.ie) {
			$$('#tx-byggfabriken-slideshow-' + this.options.id + '-container .tx-byggfabriken-slideshow-nav').fade('hide');
		} else {
			$$('#tx-byggfabriken-slideshow-' + this.options.id + '-container .tx-byggfabriken-slideshow-nav').fade('out');
		}
	},
	
	getHashFromId: function(id) {
		return id.substring(17, 27);
	},
	
	getIndexFromId: function(id) {
		return id.substring(37, 38).toInt();
	},
	
	// type = random
	random: function() {
		var imageToShow = this.options.items.getRandom();
		var image = new Asset.image(imageToShow.image, {
			onload: function(imageToShow) {
				var linkedImage;
				if (imageToShow.url) {
					linkedImage = new Element('a', { href: imageToShow.url });
					image.inject(linkedImage);
				} else {
					linkedImage = image;
				}
				var itemDiv = new Element('div', {
					id: imageToShow.id,
					'class': 'tx-byggfabriken-slideshow-item'
				});
				linkedImage.inject(itemDiv);
				itemDiv.inject($(this.options.container, 'bottom'));
				//itemDiv.set('tween', { duration: this.options.slideDuration });
				//itemDiv.tween('opacity', 0, 1);
				itemDiv.setStyle('opacity', 1).setStyle('visibility', 'visible');
				this.increaseZIndex(itemDiv);
			}.bind(this, [imageToShow]),
			border: 0,
			width: imageToShow.width,
			height: imageToShow.height,
			alt: imageToShow.altText,
			title: imageToShow.altText
		});
	}
});
