// Test if jQuery is loaded
if( $ ) {
	_slideshows = {
		_slideshowColl : null,
		slides : [],
		
		activate : function() {
			this.getSlideshows().each( function(i) {
		   		_slideshows.add( (new slideShow(this)) );
		   	})
		},
		
		add : function( slide, maxNumLinks ) {
			slide.id = this.uniqueID();
			if( !isNaN(maxNumLinks) && maxNumLinks > 0 )
				slide.maxNumLinks = maxNumLinks;
			
			slide.build();
			this.slides[ slide.id ] = slide;
		},
		
		get : function(id) {
			return this.slides[id];
		},
		
		findSlideshows : function() {
			return $(".slideshow");
		},
		
		getSlideshows : function() {
		    if (!this._slidehowColl)
				this._slideshowColl = this.findSlideshows();
			
			return this._slideshowColl;
		},
		
		uniqueID : function() {
			var d = new Date();
			return "slide:T"+ String(Number(d)) +"R"+ Math.round((Math.random() * 9999));
		}
	};
	
	function slideShow( node ) {
		this.id = "";
		this.maxNumLinks = 10;
		this.DOMnode = $(node);
		
		this._currentIndex = 1;
		this._numLinks = [];
		this._itemcount = 0;
		this._selector = null;
		
		this.build = function() {
			this.buildItems();
			this.buildSelector();
		}
		
		this.buildItems = function() {
			var maxNumLength = String(this.count()).length;
			var slideId = this.id;
			
			// Add images from json objects, and remove the container afterwards
			$(".slideshow-image-json", this.DOMnode).each(function( i ) {
				$( eval($(this).text()) ).each(function( i ) {
					var json = $(this)[0];
					var img = $('<img src="'+ json.url +'" alt="'+ json.alt +'" />');
					
					// Append the image to the container
					this.DOMnode.append(img);
				});
			}).remove();
			
			// Give each image an id + the classname "img"
			var items = $("> :not(.selector)", this.DOMnode).each(function( i ) {
				$(this)
				.addClass("img")
				.get(0).id = slideId +"_item"+ addLeadingZeroes( (i +1), maxNumLength );
			});
		}
		
		this.buildSelector = function() {
			this.removeSelector();
			
			var itemCount = this.recount();
			
			if( itemCount > 1 ) {
				var items = this.getAll();
				
				// Add the selector div
				var selClass = "selector";
					if( this.DOMnode.hasClass("slideshow-large") )
						selClass += " "+ selClass +"-large";
						
				this.setSelector( $("<div></div>").addClass(selClass) );
				var sel = this.getSelector();
				
				// Add numbers if not the slideshow should show text instead
				if(!this.showText()) {
					for( var i=0; i < this.count(); i++ ) {
						this.addNumLink( i );
						
						var opac = ( i != (this.getIndex() -1) )? 0 : 1;
						var currItem = items.eq(i);
							currItem.css( { "position" : "absolute", "top" : "0", "left" : "0", "z-index" : "0", "opacity" : opac } );
									
					}
				} else {
					sel.append($('<div class="text-area"></div>'))	
				}
				
				this.selectItem();
				
				var a = $("<a></a>");
				a.clone().addClass("slide-left").prependTo(sel).click( this.go("prev") );
				a.clone().addClass("slide-right").appendTo(sel).click( this.go("next") );
				
				this.DOMnode.append(sel);
			}
		}
		
		this.removeSelector = function() {
			var sel = this.getSelector();
			if( sel.length > 0 ) {
				sel.remove();
				this.setSelector(null);
			}
		}
		
		this.setSelector = function( obj ) {
			this._selector = obj;	
		}
		
		this.getSelector = function() {
			return $([]).add(this._selector);
		}
		
		this.recount = function() {
			this._itemcount = this.getAll().length;
			return this._itemcount;
		}
		
		this.count = function() {
			if( this._itemcount < 0 )
				return this.recount();
			
			return this._itemcount;
		}
		
		this.getAll = function() {
			return this.DOMnode.children(":not(.selector)");
		}
		
		this.get = function( index ) {
			return this.getAll().eq( (this.correctIndex(index) -1) );
		}
		
		this.getNumLink = function( num ) {
			return this._numLinks[ this.correctIndex(num) ];
		}
		
		this.addNumLink = function( index ) {
			if( this.showNumLinks() ) {
				var num = index +1;
				var nl = $("<a></a>").addClass("slide-number").html( num ).click( this.go(num) ).appendTo(this.getSelector());
				this._numLinks[ num ] = nl;
			}
		}
		
		this.go = function( index ) {
			var jsObj = this;
			var id = jsObj.id;
			
			var func = function( e ) {
				if( index != jsObj.getIndex() )
					_slideshows.get( id ).slideTo( index );
					
				e.preventDefault();
			}
			
			return func;
		}
		
		this.slideTo = function( index ) {
			switch( index ) {
				case "prev":
					index = this.getIndex() -1;
					break;
				case "next":
					index = this.getIndex() +1;
					break;
			}
			
			var oldItem = this.deselectItem();
			this.setIndex( index );
			var selItem = this.selectItem();
			
			selItem
			.stop()
			.fadeTo(1000, 1);
			
			oldItem
			.stop()
			.fadeTo(1000, 0);
		}
		
		this.getIndex = function() {
			return this._currentIndex;
		}
		
		this.setIndex = function( index ) {
			this._currentIndex = this.correctIndex(index);
		}
		
		this.correctIndex = function( index ) {
			if( isNaN(index) ) index = this.getIndex();
			if( index < 1 ) index = this.count();
			if( index > this.count() ) index = 1;
			
			return index;
		}
		
		this.showCurrentText = function( index ) {
			var alt = this.get(index).attr("alt");
			if(!alt) alt = "No descriptive text";
				
			$(".text-area", this.getSelector()).text(alt);
		}
		
		this.selectNumLink = function( index ) {
			if( this.showNumLinks() )
				this.getNumLink(index).addClass("sel");
		}
		
		this.deselectNumLink = function( index ) {
			if( this.showNumLinks() )
				this.getNumLink(index).removeClass("sel");
		}
		
		this.selectItem = function( index ) {
			if( this.showText() )
				this.showCurrentText( index );
			else
				this.selectNumLink( index );
				
			return this.get( index ).css({"z-index" : 10});
		}
		
		this.deselectItem = function( index ) {
			this.deselectNumLink( index );
			return this.get( index ).css({"z-index" : 0});
		}
		
		this.showNumLinks = function() {
			return ((this.count() <= this.maxNumLinks) && !this.showText());
		}
		
		this.showText = function() {
			return this.DOMnode.hasClass("slideshow-text");
		}
	}
	
	function addLeadingZeroes( num, len ) {
		var divideNum = Math.pow(10, len);
		if( num >= divideNum ) return String(num);
		
		return String((num / divideNum)).replace(/^0\./, "");
	}
	
	$(function() { _slideshows.activate(); });
}