/*******************************************************************************
 * 
 * Deze code is met veel plezier geschreven, getest en met trots opgeleverd door
 * Aron Rotteveel van Vije Internetproducties. Informatie:
 * 
 * Opdrachtgever: Ontwerp Atelier Laatste update: 4 juli 2007
 * 
 * Voor vragen kunt u contact opnemen per e-mail (aron@vije.nl) of per telefoon
 * (074-2673400). Meer informatie over Vije Internetproducties vindt u op
 * http://www.vije.nl
 * 
 ******************************************************************************/
var Slideshow = Class.create();
Slideshow.prototype = {

	initialize : function(element, options) {

		this.options = {
			images : [],
			interval :4,
			speed :0.6,
			fps :40,
			itemWidth :808,
			moveBack :true,
			controls :false,
			onInit : function() {
			},
			onPreloadComplete : function() {
			}
		}

		Object.extend(this.options, options || {});

		this.container = $(element);

		if (!this.container) {
			alert('SLIDESHOW ERROR: invalid container supplied!');
			return false;
		}

		this.list = this.container.getElementsByTagName('ul')[0];
		this.images = this.options.images;
		this.numItems = this.images.length;
		this.currentID = 0;
		this.preloading = false;
		this.preloadedImages = [];
		this.createdListItems = [];
		this.init = true;
		this.inTransition = false;

		if (this.options.onInit) {
			this.options.onInit();
		}

		if (this.images.length == 0) {
			return false;
		}

		this.startSlideshow();

	},

	startSlideshow : function() {

		if (this.images && this.images.length > 0) {
			this.preload(0);
		}

	},

	preload : function(itemID, manual) {

		this.preloading = true;

		if (manual) {
			this.manual = true;
		} else {
			this.manual = false;
		}
		
		if (this.inTransition) {
			var slideshow = this;
			setTimeout(function() {slideshow.preload(itemID, manual)}, 300);
			return;
		}

		if (this.preloadedImages.indexOf(this.images[itemID].image) != -1) {
			this.pl = {};
			this.pl.src = this.images[itemID].image;
			this.preloadComplete(itemID);
			return true;
		} else {
			this.pl = new Image();
			this.pl.onload = ( function() {
				this.preloadComplete(itemID);
			}).bind(this);
			this.pl.src = this.images[itemID].image;
		}

	},

	preloadComplete : function(itemID) {
		this.preloading = false;
		this.preloadedImages.push(this.pl.src);
		this.nextSlide(itemID);
	},

	nextSlide : function(itemID) {

		if (this.preloading) {
			this.stop();
			this.startTimer();
		}

		if (this.createdListItems.indexOf(itemID) == -1) {
			var li = this.createListItem(itemID);
		} else {
			var li = $('photo_' + itemID);
		}

		if (this.init) {

			this.init = false;

			new Effect.Appear(li, {
				duration :this.options.speed,
				beforeStart :( function() {
					this.inTransition = true;
				}).bind(this),
				afterFinish :( function() {
					this.transitionComplete(itemID);
				}).bind(this)
			});

		} else {

			var currentIndex = this.getElementIndex('photo_' + this.currentID);
			var targetIndex = this.getElementIndex(li);

			var currentOffset = (currentIndex * this.options.itemWidth);
			var targetOffset = targetIndex * this.options.itemWidth;

			var calculatedOffset = (currentOffset - targetOffset);

			new Effect.Move(this.list, {
				x :calculatedOffset,
				duration :this.options.speed,
				fps :this.options.fps,
				beforeStart :( function() {
					this.inTransition = true;
				}).bind(this),
				afterFinish :( function() {
					this.transitionComplete(itemID);
				}).bind(this)
			});

		}

	},

	transitionComplete : function(itemID) {
		this.inTransition = false;

		Element.removeClassName('imagelink_' + this.currentID, 'active');
		Element.addClassName('imagelink_' + itemID, 'active');

		this.currentID = itemID;

		if (!this.manual) {
			this.startTimer();
		}
	},

	createListItem : function(itemID) {

		var li = document.createElement('li');
		li.id = 'photo_' + itemID;

		//=-- Retrieve item object
		var oItem = this.images[itemID]; 
		
		// =-- Create content of the new item
		var liContent;

		// =- Image item
		if (oItem.type == 'image') {
			liContent = document.createElement('img');
			liContent.src = oItem.image;
			li.appendChild(liContent);

		}
		// =- Video item
		else if (oItem.type == 'video') {
			liContent = document.createElement('div');
			liContent.setAttribute('class', 'workMovie');
			this.attachMovieContainer(liContent, itemID);
			li.appendChild(liContent);
			
		}
		
		if (this.init) {
			Element.setOpacity(li, 0);
		}

		// bepalen waar we de foto plaatsen
		var max = this.createdListItems.max();

		if (max > itemID) {

			// er zijn 'latere' items, dus plaatsen we deze voor de
			// eerstvolgende
			for ( var i = 0; i < this.createdListItems.length; i++) {

				if (parseInt(this.createdListItems[i]) > parseInt(itemID)) {

					this.list.insertBefore(li,
							$('photo_' + this.createdListItems[i]));

					li.style.left = this.getElementIndex($('photo_' + itemID))
							* this.options.itemWidth;

				}

			}

		} else {

			// dit is het laatste item

			li.style.left = itemID * this.options.itemWidth;
			this.list.appendChild(li);

		}

		this.createdListItems.push(itemID);

		this.reIterate();

		return li;

	},

	attachFlashPlayer : function (liContent, movieContainer, itemID) {
		var slideshow = this;
		Event.stopObserving(liContent, 'click');		
		
		Event.observe(liContent,'click', function () {
			//=-- Stop the slideshow
			slideshow.stop();
			
			//=-- Remove arrow image
			Element.remove(Element.descendants(liContent)[0]);
			
			//=-- Attach the FLV player
			Element.addClassName(movieContainer, 'workMovieActive');
	        var so = new SWFObject('/swf/flvplayer.swf','player','808','428','7');
			so.addParam("allowfullscreen","true");
			so.addVariable("autostart","true");
			so.addVariable("stretching","uniform");
			so.addVariable("file",slideshow.images[itemID].info);
	        so.addVariable("image",slideshow.images[itemID].image);
			so.write(movieContainer);
		}
		);
		
	},
	
	attachMovieContainer : function (liContent, itemID) {
		var oItem = this.images[itemID];
		var divID = 'FLVplayer_'+itemID; 

		var movieContainer = document.createElement('div');
		movieContainer.id = divID;
		Element.addClassName(movieContainer, 'workMovieInactive');

		
		var moviePlaceHolder = document.createElement('img');
		moviePlaceHolder.src = oItem.image;

		var arrowImage = document.createElement('img');
		arrowImage.src = '/img/play_arrow.png';
		Element.addClassName(arrowImage, 'movieArrow');
		
		movieContainer.appendChild(moviePlaceHolder);

		liContent.appendChild(arrowImage);			
		liContent.appendChild(movieContainer);
		
		this.attachFlashPlayer(liContent, movieContainer, itemID);

		return movieContainer;
	},
	
	reIterate : function() {

		var items = $A(this.list.getElementsByTagName('li'));

		for ( var i = 0; i < items.length; i++) {
			items[i].style.left = i * this.options.itemWidth;
		}

		this.list.style.left = -(this
				.getElementIndex('photo_' + this.currentID) * this.options.itemWidth);

	},

	getElementIndex : function(element) {

		element = $(element);

		var parent = element.parentNode;
		var children = parent.getElementsByTagName(element.tagName);

		for ( var i = 0; i < children.length; i++) {
			if (children[i].id == element.id) {
				return i;
			}
		}

		return false;

	},

	startTimer : function() {
		this.timer = setTimeout(( function() {

			if (this.images[this.currentID + 1]) {
				this.preload(this.currentID + 1);
			} else {
				this.preload(0);
			}
		}).bind(this), this.options.interval * 1000);
	},

	stop : function() {
		if (this.timer) {
			clearTimeout(this.timer);
		}
	},

	
	cleanFlashPlayers : function (exceptID) {
		var slideshow = this;
		
		//=-- Iterate active movie players
		$A($$('.workMovieActive')).each(function(div) {

			if (div.id != 'FLVplayer_'+exceptID) {
				var parentDiv = Element.ancestors(div)[0];
				
				var embedElements = Element.descendants(div);
				if (embedElements.length != 0) {
					var embedElement = embedElements[0];
					Element.remove(embedElement);
					var children = Element.childElements(parentDiv);
					for (i=0; i<children.length; i++) {
						Element.remove(children[i]);
					}
					
					var itemID = div.id.split('_')[1];

					var movieContainer = slideshow.attachMovieContainer(parentDiv, itemID);
					Effect.Appear(movieContainer.id, {duration: 0.2});
				}
			}
		});
	}

}