/**
 * MooFlow - Image gallery
 *
 * Dependencies: MooTools 1.2
 *
 * @version			0.2.1
 *
 * @license			MIT-style license
 * @author			Tobias Wetzel <info [at] outcut.de>
 * @copyright		Author
 * @docmentation	http://outcut.de/MooFlow/Docmentation.html
 */ 

var MooFlow = new Class({
	Implements: [Events, Options],
	options: {
		onStart: $empty,
		onClickView: $empty,
		onAutoPlay: $empty,
		onAutoStop: $empty,
		onRequest: $empty,
		onResized: $empty,
		onEmptyinit: $empty,
		reflection: 0.4,
		heightRatio: 0.4,
		offsetY: 0,
		maxImageHeight: 0,
		startIndex: 0,
		interval: 3000,
		factor: 115,
		useCaption: false,
		useResize: false,
		useSlider: false,
		useWindowResize: false,
		useMouseWheel: true,
		useKeyInput: false,
		useViewer: false,
		firstLoad: true,
		lastDirection: false
	},
	
	initialize: function(element, options){
		//set roll over div width and override if in germex site
		this.rollOverWidth = 400;
		if(typeof germex != 'undefined') {
			this.rollOverWidth = 500;
		}
		this.MooFlow = element;
		// Set styles for slide show div
		this.MooFlow.addClass('mf').setStyles({
			'overflow':'hidden',
			'background-color':this.options.bgColor,
			'position':'relative',
			'height': 521,
			// 'height':this.MooFlow.getSize().x*this.options.heightRatio,
			'opacity':0
		});
		this.setOptions(options);
		this.MooFlowHalfWidth = this.MooFlow.getStyle('width').toInt() / 2;
		this.currentSlide = $('currentSlide');
		this.slideNumber = $('slideNumber');
		this.foc = this.MooFlowHalfWidth;
		this.inset = 60;
		this.factor = this.options.factor;
		this.offY = this.options.offsetY;
		this.maxImageHeight = this.options.maxImageHeight;
		this.isFull = false;
		this.isAutoPlay = false;
		this.isLoading = false;
		this.inMotion = false;
		if(document.implementation && document.implementation.createDocument) {
			// Firefox and Safari need a serializer, IE just has an .xml property
			this.serializer = new XMLSerializer();
		}
		
		
		// Create div that the image details content will go in.
		this.imageDetail = new Element('div').set('id', 'rollOver').inject($('slide_show_container'), 'top');
		this.imageDetail.setStyles({
			'left': this.foc - (this.rollOverWidth / 2),
			'bottom': this.options.offsetY,
			'visibility' : 'hidden',
			'opacity' : '0',
			'cursor' : 'pointer'
		});


		if(this.options.useWindowResize) window.addEvent('resize', this.update.bind(this, 'init'));
		if(this.options.useMouseWheel || this.options.useSlider) this.MooFlow.addEvent('mousewheel', this.wheelTo.bind(this));
		if(this.options.useKeyInput) document.addEvent('keydown', this.keyTo.bind(this));

		this.getElements(this.MooFlow);
		


	},
	// Funcion to create the prev/next navigation that spans the entire height of the slideshow
	createRollOverNavigation: function() {		
		if (!$chk(this.nextImage) && !$chk(this.prevImage)) {
			
			this.nextImage = new Element('a').set({'class':'slideNext', 'href':'#'}).inject($('slide_show_container'), 'top');
			this.prevImage = new Element('a').set({'class':'slidePrev', 'href':'#'}).inject($('slide_show_container'), 'top');
			
			this.nextImage.addEvents({'click':this.next.bind(this)});		
			this.prevImage.addEvents({'click':this.prev.bind(this)});
		}
		
		// finds out whether to hide the previous button
		if (this.options.startIndex == 0) {
			this.prevImage.setStyle('display', 'none');
		} else {
			this.prevImage.setStyle('display', 'block');
		}
		
		if (this.loadedImages.length > 1) {
			this.nextImage.setStyle('display', 'block');
		} else {
			this.nextImage.setStyle('display', 'none');
		}
	},
	clearInit: function(){
		this.fireEvent('emptyinit');
	},
	
	getElements: function(el){
		this.master = {'images':[]};
		var els = el.getChildren();
		if(!els.length) {this.clearInit(); return;}
		$$(els).each(function(el){
			var hash = $H(el.getElement('img').getProperties('src','title','alt','longdesc', 'itemid'));
			if(el.get('tag') == 'a') hash.combine(el.getProperties('href','rel','target'));
			this.master['images'].push(hash.getClean());
			el.dispose();
		}, this);
		this.clearMain();
	},

	// Function to parse the RSS XML (with some cross browser testing),
	// and return a JavaScript array of image objects	
	getElementsFromRSS: function(el){
		data = {'images':[]};
		var prevRSS = false;
		var nextRSS = false;
				
		if (el.getElementsByTagName('atom:link').length > 0) {
			var linkTags = el.getElementsByTagName('atom:link');
		} else {
			var linkTags = el.getElementsByTagName('link');
		}

		for (i=0;i <linkTags.length;i++) {
			var linkTag = linkTags[i];
			if (linkTag.getAttribute('rel') == 'slideshow_next') {
				nextRSS = linkTag.getAttribute('href');
			}
			else if (linkTag.getAttribute('rel') == 'slideshow_previous') {
				prevRSS = linkTag.getAttribute('href');
			}
		}
		data['prevRSS'] = prevRSS + '&slideshow=true';
		data['nextRSS'] = nextRSS + '&slideshow=true';

		var els = el.getElementsByTagName('item');

		if(!els.length) {this.clearInit(); return;}
		for (i=0;i <els.length;i++) {
			var node = els[i];
			
			var itemidTag = node.getElementsByTagName('itemid')[0];
			var itemid = this.serializeNode(itemidTag).toInt();

			if (node.getElementsByTagName('media:content').length > 0) {
				var contentTag = node.getElementsByTagName('media:content')[0];
			} else {
				var contentTag = node.getElementsByTagName('content')[0];
			}

			var src = contentTag.getAttribute('url');
			
			var titleTag = node.getElementsByTagName('title')[0];
			var title = this.serializeNode(titleTag);

			var linkTag = node.getElementsByTagName('link')[0]
			if (linkTag.text) {
				var href = linkTag.text;
			} else {
				var href = linkTag.textContent;
			}

			if (node.getElementsByTagName('media:description').length > 0) {
				var descTag = node.getElementsByTagName('media:description')[0];
			} else {
				var descTag = node.getElementsByTagName('description')[0];
			}

			var alt = this.serializeNode(descTag);

			var hash = new Hash({src: src, title: title, href: href, alt: alt, itemid: itemid});

			data['images'].push(hash.getClean());

		}
		// If we're not on page 1 at start, slide to middle of slideshow
		if (pageNumber > 1) this.options.startIndex = (data['images'].length) / 2;
		return data;
	},
	
	serializeNode: function(node){
		var txt = '';
		for (j=0;j<node.childNodes.length;j++) {
			nownode=node.childNodes[j];
			if (nownode.xml) {
				txt = txt + nownode.xml;
			} else {
				txt = txt + this.serializer.serializeToString(nownode);
			}
		}
		txt = txt.replace(/\<\!\[CDATA\[/g, '');
		txt = txt.replace(/\]\]\>/g, '');
		return txt;
	},
	
	clearMain: function(){
		if(this.cap){this.cap.fade(0);}
		/* if(this.nav){
			new Fx.Tween(this.nav, {
				'onComplete': function(){
					this.MooFlow.empty();
					this.createAniObj();
				}.bind(this)
			}).start('bottom', -50);
		}*/
		if(!this.cap){
			this.MooFlow.empty();
			this.createAniObj();
		}
	},
	getMooFlowElements: function(key){
		var els = [];
		this.master.images.each(function(el){ 
			els.push(el[key]); 
		});
		return els;
	},
	
	createAniObj: function(){
		this.aniFx = new Fx.Value({
			'transition': Fx.Transitions.Expo.easeOut,
			'link': 'cancel',
			'duration': 750,
			onMotion: this.process.bind(this),
			'onStart': this.flowStart.bind(this),
			'onComplete': this.flowComplete.bind(this)
		});
		this.addLoader();
	},
	
	addLoader: function(){
		this.MooFlow.store('height', this.MooFlow.getSize().y);
		this.loader = new Element('div').set({'class':'loader'}).inject(this.MooFlow);
		new Fx.Tween(this.MooFlow, {
			'duration': 800,
			'onComplete': this.preloadImg.bind(this)
		}).start('opacity', 1);
	},
	
	preloadImg: function(){
		this.imageContainer = new Element('div').setProperty('id', 'slideImages').inject(this.MooFlow);
		// Work around - grab all the images, but don't do anything with them
		this.loadedImages = new Asset.images(this.getMooFlowElements('src'), {
			'onProgress': this.showCount.bind(this),
			'onComplete': function(){
				// Then run through them again (should be cached), and output them				
				this.loadedImages = new Asset.images(this.getMooFlowElements('src'), {
					'onComplete': this.loaded.bind(this),
					'onProgress': this.createMooFlowElement.bind(this)
				});				
			}.bind(this)
		});
	},
	
	showCount: function(counter, i){
		var img = this.loadedImages[counter];
		this.loader.set('text', (counter+1) + ' / ' + this.loadedImages.length);
	},
	
	createMooFlowElement: function(counter, i){
		var obj = this.getCurrent(counter);
		var img = this.loadedImages[counter];
		
		obj['width'] = img.width;
		obj['height'] = img.height;

		img.removeProperties('width','height');
		
		obj['div'] = new Element('div').setStyles({
			'position':'absolute',
			'display':'none'
			//'height': this.MooFlow.getSize().y
		}).setProperty('class', 'slideImage').inject(this.imageContainer);

		obj['con'] = new Element('div').inject(obj['div']);
		img.addEvents({'click': this.clickTo.bind(this, counter), 'dblclick': this.viewCallBack.bind(this, counter)});
		img.inject(obj['con']);
	},
	appendLoader: function(){
		this.MooFlow.store('height', this.MooFlow.getSize().y);
		this.loader = new Element('div',{'class':'loader'}).inject(this.MooFlow);
		new Fx.Tween(this.MooFlow, {
			'duration': 800,
			'onComplete': this.appendImg.bind(this)
		}).start('opacity', 1);
	},
	// Same function as preloadImg, but calls the appendMooFlowElement function instead
	appendImg: function(){		
		this.loadedImages = new Asset.images(this.getMooFlowElements('src'), {
			'onProgress': this.showCount.bind(this),
			'onComplete': function() {
				// Then run through them again (should be cached), and output them
				this.loadedImages = new Asset.images(this.getMooFlowElements('src'), {
					'onComplete': this.appendLoaded.bind(this),
					'onProgress': this.appendMooFlowElement.bind(this)
				});
			
			}.bind(this)
		});
	},
	appendLoaded: function(){
		this.index = this.index + this.newImageCount;
		this.glideTo(this.index)
		this.iL = this.master.images.length-1;
		new Fx.Tween(this.loader, {
			'duration': 800,
			'onComplete': this.createUI.bind(this)
		}).start('opacity', 0);
	},
	// Same as CreateMooFlowFunction, but sifts out the new slideshow images from the images object
	appendMooFlowElement: function(counter, i){
		/* if (counter > this.lastImageCount) { */
			var obj = this.getCurrent(counter);
			var img = this.loadedImages[counter];
			obj['width'] = img.width;
			obj['height'] = img.height;
			img.removeProperties('width','height');
			
			obj['div'] = new Element('div').setStyles({
				'position':'absolute',
				'display':'none'
				//'height': this.MooFlow.getSize().y
			}).setProperty('class', 'slideImage').inject(this.imageContainer);
			obj['con'] = new Element('div').inject(obj['div']);
			img.addEvents({'click': this.clickTo.bind(this, counter), 'dblclick': this.viewCallBack.bind(this, i)});
			img.inject(obj['con']);
		/* } */
	},
	fadeImages: function(viewType){
		if (viewType == "in") {
			this.nextImage.setStyle('display', 'block');
			this.prevImage.setStyle('display', 'block');
		} else if (viewType == "out") {
			this.nextImage.setStyle('display', 'none');
			this.prevImage.setStyle('display', 'none');			
		}
	},
	loaded: function(){
		if (!$chk(this.index)) {
			this.index = this.options.startIndex;
		} else {
			this.index = this.index;
		}
		
		this.iL = this.master.images.length-1;
		new Fx.Tween(this.loader, {
			'duration': 800,
			'onComplete': this.createUI.bind(this)
		}).start('opacity', 0);
		this.createRollOverNavigation();
	},
	
	createUI: function(){
		this.loader.dispose();
		if(this.options.useCaption && !$chk(this.cap)){
			// New container to show the caption of the current slide
			this.cap = new Element('div')
						.addClass('caption')
						.setStyles({
							'opacity': 0,
							'width': this.MooFlow.getStyle('width').toInt() - 100
						}).inject(this.MooFlow);
		}
		// We don't use any navigation
		//this.nav = new Element('div').addClass('mfNav').setStyle('bottom','-50px');
		/* this.autoPlayCon = new Element('div').addClass('autoPlayCon');
		this.sliderCon = new Element('div').addClass('sliderCon');
		this.resizeCon = new Element('div').addClass('resizeCon');		
		if(this.options.useAutoPlay){
			this.autoPlayCon.adopt(
				new Element('a',{'class':'stop','events': {'click':this.stop.bind(this)}}), 
				new Element('a',{'class':'play','events': {'click':this.play.bind(this)}})
			);
		}
		if(this.options.useSlider){
			this.sliPrev = new Element('a',{'class':'sliderNext','events': {'click':this.prev.bind(this)}});
			this.sliNext = new Element('a',{'class':'sliderPrev','events': {'click':this.next.bind(this)}});
			this.knob = new Element('div',{'class':'knob'});
			this.knob.adopt(new Element('div',{'class':'knobleft'}));
			this.slider = new Element('div',{'class':'slider'}).adopt(this.knob);
			this.sliderCon.adopt(this.sliPrev,this.slider,this.sliNext);
			this.slider.store('parentWidth', this.sliderCon.getSize().x-this.sliPrev.getSize().x-this.sliNext.getSize().x);
		}
		if(this.options.useResize){
			this.resizeCon.adopt(new Element('a',{'class':'resize','events': {'click':this.setScreen.bind(this)}}));
		}*/
		//this.MooFlow.adopt(this.nav.adopt(this.autoPlayCon, this.sliderCon, this.resizeCon));	
		this.showUI();
	},
	
	showUI: function(){
		if(this.cap) this.cap.fade(1);
		if (this.slideNumber) this.slideNumber.style.display = "block";
		//this.nav.tween('bottom', 20);
		this.fireEvent('start');
		this.update();
	},
	
	update: function(e){
		if(e == 'init') return;
		this.oW = this.MooFlow.getSize().x;
		this.sz = this.oW * 0.5;
		/*  if(this.options.useSlider){	
			this.slider.setStyle('width',this.slider.getParent().getSize().x-this.sliPrev.getSize().x-this.sliNext.getSize().x-1);
			this.knob.setStyle('width',(this.slider.getSize().x/this.iL));
			this.sli = new SliderEx(this.slider, this.knob, {steps: this.iL}).set(this.index);
			this.sli.addEvent('onChange', this.glideTo.bind(this));
		}*/

		if ($chk(this.lastImageCount)) {
			this.imageContainer.fade('in');
			this.fadeImages('in');
		}
		
		this.glideTo(this.index)
		this.isLoading = false;
	},
	
	setScreen: function(){
		if(this.isFull = !this.isFull){
			this.holder = new Element('div').inject(this.MooFlow,'after');
			this.MooFlow.wraps(new Element('div').inject(document.body));
			this.MooFlow.setStyles({'position':'absolute','z-index':'100','top':'0','left':'0','width':window.getSize().x,'height':window.getSize().y});
			if(this.options.useWindowResize){
				this._initResize = this.initResize.bind(this);
				window.addEvent('resize', this._initResize);
			}
		} else {
			this.MooFlow.wraps(this.holder);
			window.removeEvent('resize', this._initResize);
			delete this.holder, this._initResize;
			this.MooFlow.setStyles({'position':'relative','z-index':'','top':'','left':'','width':'','height':this.MooFlow.retrieve('height')});
			this.slider.setStyle('width',this.slider.retrieve('parentWidth'));
		}
		this.fireEvent('resized', this.isFull);
		this.update();
	},
	
	initResize: function(){
		this.MooFlow.setStyles({'width':window.getSize().x,'height':window.getSize().y});
		this.update();
	},
	
	getCurrent: function(index){
		return this.master.images[$chk(index) ? index : this.index];
	},
	
	loadJSON: function(url){
	
		if(!url || this.isLoading) return;
		this.isLoading = true;
		new Request.JSON({
			'onComplete': function(data){
				if($chk(data)){
					this.master = data;
					this.clearMain();
					this.fireEvent('request', data);
				}
			}.bind(this)
		}, this).get(url);
	},
	// New function to pull in JSON content and add it without reloading the slideshow
    applyJSON: function(url, direction){
    
		if(!url || this.isLoading) return;
		this.isLoading = true;
		new Request.JSON({
			'onComplete': function(data){
				if($chk(data)){
					// Hide navigation and all images
					this.fadeImages("out")
					// Set new array to build up images
					newMaster = new Array();
					
					new Fx.Tween(this.imageContainer, {
						'duration': 750,
						
						// Left in 'onComplete' as it uses too 'data' and the passed in 'direction'
						'onComplete': function(){
							// Save count of the last set of images
							this.lastImageCount = this.master.images.length;
							
							// Remove all HTML for current images
							for(var i = 0; i < this.master.images.length; i++) {
								this.master.images[i].div.dispose();
							}
							
							if (direction == "next") {
								// Store the amount of images backwards or forwards we need to move the slideshow position
								this.newImageCount = -data.images.length
								
								this.master.images.each(function(item, intIndex){
									if (intIndex >= data.images.length) {
										newMaster[intIndex] = item
									}
								});
								
								// Remove all old images
								this.master.images = newMaster.clean();
								
								// Merge the current images with the newly acquired ones
								this.master.images.extend(data.images);
								
							} else if (direction == "prev"){
								this.newImageCount = data.images.length
								this.master.images.each(function(item, intIndex){
									if (intIndex < data.images.length) {
										newMaster[intIndex] = item
									}
								});
								this.master.images = newMaster.clean();
								this.master.images = data.images.extend(this.master.images);
							}
					
							// Add the images into the slide show
							this.appendLoader();
					
							this.fireEvent('request', data);
						}.bind(this)
					}).start('opacity', 0);
				}
			}.bind(this)
		}, this).get(url);
	},
	loadHTML: function(url, filter){
		if(!url || !filter || this.isLoading) return;
		this.isLoading = true;
		new Request.HTML({
			'onSuccess': function(tree, els, htm){
				var result = new Element('div', {'html': htm}).getChildren(filter);
				this.getElements(result);
				this.fireEvent('request', result);
			}.bind(this)
		}, this).get(url);
	},
	loadRSS: function(url){
		pageNumber = url.match(/page_number=([0-9]+)/g);
		pageNumber = pageNumber[0].substring(pageNumber[0].indexOf("=") + 1, pageNumber[0].length);
		
		if(!url || this.isLoading) return;
		this.isLoading = true;
		new Request({
			'onSuccess': function(responseText, responseXML){
				//var result = new Element('div', {'html': responseText});
				var result = responseXML.documentElement;
				this.master = this.getElementsFromRSS(result);
				this.clearMain();
				this.fireEvent('request', result); //TODO is this needed?
			}.bind(this)
		}, this).get(url);
	},
	// New function to pull in RSS content and add it without reloading the slideshow
    applyRSS: function(url, direction, lastDirection){
    	// Get current page number
    	pageNumber = url.match(/page_number=([0-9]+)/g);
		pageNumber = parseInt(pageNumber[0].substring(pageNumber[0].indexOf("=") + 1, pageNumber[0].length));
		
    	// On first new load we double the page number and half the quantity of objects to grab 
    	if(this.options.firstLoad) {
			if (direction == "next") {
				url = url.replace(/page_number=([0-9]+)/g, "page_number=" + ((pageNumber * 2) - 1));
			} else {
				url = url.replace(/page_number=([0-9]+)/g, "page_number=" + ((pageNumber * 2)));
			}
  			this.options.firstLoad = false;
		}
		
		// If changing direction we need to add or minus one to the pageNumber 
		if ((lastDirection != false) && (direction != lastDirection) && (direction == "next")) {
			url = url.replace(/page_number=([0-9]+)/g, "page_number=" + (pageNumber + 1));
		} else if ((lastDirection != false) && (direction != lastDirection) && (direction == "prev")) {
			url = url.replace(/page_number=([0-9]+)/g, "page_number=" + (pageNumber - 1));
		}
		
		// Set last direction
		this.options.lastDirection = direction;
		
    	if(!url || this.isLoading) return;
		this.isLoading = true;
		new Request({
			'onSuccess': function(responseText, responseXML){
				if($chk(responseXML)){
					// Hide navigation and all images
					this.fadeImages("out");

					// Set new array to build up images
					newMaster = new Array();
					
					new Fx.Tween(this.imageContainer, {
						'duration': 750,
						
						// Left in 'onComplete' as it uses too 'data' and the passed in 'direction'
						'onComplete': function(){
							var result = responseXML.documentElement;
							data = this.getElementsFromRSS(result);

							// Save count of the last set of images
							this.lastImageCount = this.master.images.length;
							
							// Remove all HTML for current images
							for(var i = 0; i < this.master.images.length; i++) {
								this.master.images[i].div.dispose();
							}
							
							if (direction == "next") {
								// Store the amount of images backwards or forwards we need to move the slideshow position
								this.newImageCount = -data.images.length
								
								this.master.images.each(function(item, intIndex){
								
									if (intIndex >= data.images.length) {
										newMaster[intIndex] = item
									}
								});
								
								// Remove all old images
								this.master.images = newMaster.clean();
								
								// Merge the current images with the newly acquired ones
								this.master.images.extend(data.images);
								
							} else if (direction == "prev"){
								this.newImageCount = data.images.length
								this.master.images.each(function(item, intIndex){
									if (intIndex < data.images.length) {
										newMaster[intIndex] = item
									}
								});
								this.master.images = newMaster.clean();
								this.master.images = data.images.extend(this.master.images);
							}
							// set up new links
							this.master.prevRSS = data.prevRSS;
							this.master.nextRSS = data.nextRSS;
					
							// Add the images into the slide show
							this.appendLoader();
					
							this.fireEvent('request', data);
						}.bind(this)
					}).start('opacity', 0);
				}
			}.bind(this)
		}, this).get(url);
	},
	getQuerystring: function(key, default_)
	{
	  if (default_==null) default_="";
	  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
	  var qs = regex.exec(window.location.href);
	  if(qs == null)
	    return default_;
	  else
	    return qs[1];
	},
	flowStart: function(){
		this.inMotion = true;
	},
	
	flowComplete: function(){
		this.inMotion = false;
	},
	
	viewCallBack: function(index){
		if(this.index != index || this.inMotion) return;
		var el = $H(this.getCurrent());
		var returnObj = {};
		returnObj['coords'] = el.div.getElement('img').getCoordinates();
		el.each(function(v, k){
			if($type(v) == 'number' || $type(v) == 'string') returnObj[k] = v;
		}, this);
		this.fireEvent('clickView', returnObj);
	},
	prev: function(e){
		e.stop().preventDefault();
		if(this.index > 0) this.clickTo(this.index-1);
		if (this.index == 1 && this.master.prevRSS != "false&slideshow=true") this.applyRSS(this.master.prevRSS, "prev", this.options.lastDirection);
		return false;
	},
	next: function(e){
		e.stop().preventDefault();
		if(this.index < this.iL) this.clickTo(this.index+1);
		if (this.index == this.iL - 1 && this.master.nextRSS != "false&slideshow=true") this.applyRSS(this.master.nextRSS, "next", this.options.lastDirection);
		return false;
	},
	stop: function(){
		$clear(this.autoPlay);
		this.isAutoPlay = false;
		this.fireEvent('autoStop');
	},
	play: function(){
		this.autoPlay = this.auto.periodical(this.options.interval, this);
		this.isAutoPlay = true;
		this.fireEvent('autoPlay');
	},
	auto: function(){
		if(this.index < this.iL) this.next();
		else if(this.index == this.iL) this.clickTo(0);
	},
	keyTo: function(e){
		switch (e.code){
			case 37: e.stop(); this.prev();	break;
			case 39: e.stop(); this.next();
		}
	},
	wheelTo: function(e){
		if(e.wheel > 0) this.prev();
		if(e.wheel < 0) this.next();
		e.stop().preventDefault();
	},
	clickTo: function(index){		
		// Hide and show navigation bars depending on which image the user is on		
		if (index == 0) {
			this.prevImage.setStyle('display', 'none');
		} else if (index == 1) {
			this.prevImage.setStyle('display', 'block');
			
		}

		if (index == this.iL) {
			this.nextImage.setStyle('display', 'none');
		} else if (index == (this.iL -1)) {
			this.nextImage.setStyle('display', 'block');
		}
		
		if(this.index == index) {
			this.setImageDetails(this.index, index)
			this.showDetails(index)
			
		} else {
			// added 'else' to animate back to image upon glide
			this.imageDetail.setStyles({
				'visibility':'hidden',
				'opacity' : 0
			})
			this.master.images[this.index].div.fade('in');
		}
		
		//this.aniFx.cancel();
		if(this.sli) this.sli.set(index);
		this.glideTo(index);
	},
	// function to set the content of the image details
	setImageDetails:function(currentIndex, lastIndex){
		currentImage = this.getCurrent(currentIndex);
	

		this.imageDetail.set('html', currentImage.alt);
		//this.imageDetailFooter = new Element('div', {'id': 'rollOverFooter'}).inject(this.imageDetail, 'bottom');
		
		/* var a = new Element('a',{
			'class':'description',
			'href':currentImage.href,
			'html':'Full Description'
		}).inject(this.imageDetailFooter, 'top'); */
	},
	
	// function to reveal/hide image/details on click
	showDetails: function(index){
		this.imageDetail.fade('in');
		this.master.images[index].div.fade('out');
		
		// If you click the image details, it'll go back to the master image
		this.imageDetail.addEvent('click', function(){
			this.imageDetail.fade('out');
			this.master.images[index].div.fade('in');
		}.bind(this))
	},
	glideTo: function(index){
		this.index = index;
		this.aniFx.start(this.aniFx.get(), index*-this.foc);		
		if(this.cap) this.cap.set('html', this.getCurrent().title);
		this.currentSlide.set('html', this.getCurrent().itemid);	
	},
	process: function(x){
		var z,W,H,zI=this.iL,foc=this.foc,inset=this.inset,f=this.factor,sz=this.sz,oW=this.oW,offY=this.offY,div,elh,elw;
		//console.log(z + " - " + W + " - " + H + " - " + zI + " - " + foc + " - " + inset + " - " + f + " - " + sz + " - " + oW + " - " + offY + " - " + div + " - " + elh + " - " + elw)
		// direction >= 0:  moving left, direction <=0: moving right
		var direction = ((this.index * foc) + x);

		// zI: Amount of gaps
		// foc: gap to move between images
		for (var i = 0; i < this.master.images.length; i++) {
			div = this.master.images[i].div.style;
			elw = this.master.images[i].width;
			elh = this.master.images[i].height;
			
			// vertically align and center image
			var vertAlignImage = ((this.maxImageHeight - elh) / 2);
			var centerImage = ((this.MooFlowHalfWidth) - (elw / 2));

			if(x>-foc*3 && x<foc*3){
				if ((x < 0 && x >= -foc && direction >= 0) || (x < -foc && x >= -2*foc && direction <= 0) ) {
					centerImage = foc + inset - elw;
				}
				else if ((x > 0 && x <= foc && direction <= 0) || (x > foc && x <= 2*foc && direction >= 0) ) {
					centerImage = foc - inset;
				}
				with (Math) {
					div.left = round(x) + round(centerImage) + 'px';
					//console.log(i + ':' + 'c:'+ centerImage + 'x:' + x);
					div.bottom = offY + round(vertAlignImage) + "px";
				}	
				
				div.zIndex = x < 0 ? zI++ : zI--;
				div.display = 'block';
			} else {
				div.display = 'none';
			}
			x += foc;
		}
	}
});

var SliderEx = new Class({
	Extends: Slider,
	set: function(step){
		this.step = Math.round(step);
		this.fireEvent('tick', this.toPosition(this.step));
		return this;
    },
	clickedElement: function(event){
		var dir = this.range < 0 ? -1 : 1;
		var position = event.page[this.axis] - this.element.getPosition()[this.axis] - this.half;
		position = position.limit(-this.options.offset, this.full -this.options.offset);
		this.step = Math.round(this.min + dir * this.toStep(position));
		this.checkStep();
		this.fireEvent('tick', position);
	}
});

Fx.Value = new Class({
	Extends: Fx,
	compute: function(from, to, delta){
		this.value = Fx.compute(from, to, delta);
		this.fireEvent('motion', this.value);
		return this.value;
	},
	get: function(){
		return this.value || 0;
	}
});

Element.implement({
	reflect: function(arg){
		i = arg.img.clone();
		if(Browser.Engine.trident){
			i.style.filter = 'flipv progid:DXImageTransform.Microsoft.Alpha(opacity=20, style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy='+100*arg.ref+')';
			i.setStyles({'width':'100%', 'height':'100%'});
			return new Element('div').adopt(i);
		} else {
			var can = new Element('canvas').setProperties({'width':arg.width, 'height':arg.height});
			if(can.getContext){
				var ctx = can.getContext("2d");
				ctx.save();
				ctx.translate(0,arg.height-1);
				ctx.scale(1,-1);
				ctx.drawImage(i, 0, 0, arg.width, arg.height);
				ctx.restore();
				ctx.globalCompositeOperation = "destination-out";
				ctx.fillStyle = arg.color;
				ctx.fillRect(0, arg.height*0.5, arg.width, arg.height);
				var gra = ctx.createLinearGradient(0, 0, 0, arg.height*arg.ref);					
				gra.addColorStop(1, "rgba(255, 255, 255, 1.0)");
				gra.addColorStop(0, "rgba(255, 255, 255, "+(1-arg.ref)+")");
				ctx.fillStyle = gra;
				ctx.rect(0, 0, arg.width, arg.height);
				ctx.fill();
				delete ctx, gra;
			}
			return can;
		}
	}
});

window.addEvent('domready', function(){
	$$('.MooFlowieze').each(function(mooflow){
		new MooFlow(mooflow);
	});
});
