window.addEvent('domready', function(){	
	//globals	
	var currentIndex = -1;
	var lastIndex = -2;
	var darkness = .6;
	

	//Hide all the info boxes
	$$('.moduleInfoWrapper').fade('hide');
	//Fade all the module shields
	$$('.moduleShield').fade(darkness);
	
	
	//impliment function kill - Fade out and remove from the DOM
	Element.implement({
		kill: function(){
			this.get('tween').start('opacity',0).chain(function() {
				this.destroy();
			}.bind(this));
			return this;
		}
	});

	//Check for changes in the hash(bookmark) every 100ms
	var bookmarkChecker = function(){
		if(document.location.hash){ //only do this if there is a bookmark set
			div = document.location.hash.substring(2);
			if($(div)) move($(div).get('name'));
		}
	}.periodical(100);	
	
	
	//This defines system for the scroll from project to project
	var windowMover = new Fx.Scroll('content', {
		duration: 1000, //time you want it to take to get from point a to be... in miliseconds
		link: 'cancel', //Makes it so if anyone clicks a menu item when it is already in motion it will cancel the old and go to the new place
		transition: Fx.Transitions.Back.easeInOut //the type is acceleration
	});
		
	//------------------------------------------------------------------------------------------------------------		
	//fire on first load for bookmark purposes, or random if not
	//------------------------------------------------------------------------------------------------------------
	if(document.location.hash && $(document.location.hash.substring(2)) ){ //only do this if there is a bookmark set, and the project is available	
		var div = document.location.hash.substring(2);
		move($(div).get('name'));
	}else{
		//choose project at random	
		//move($random(0,$$('.mtip').length));
		move(0);
	}
	//---------------------------------------------------------------------------------------------------------------------------------------
		
	//------------------------------------------------------------------------------------------------------------
	//Setup the tips offset - IE(6/7) needs -100px
	//------------------------------------------------------------------------------------------------------------

	var xOffset = 0;
	
	//var xOffset = (Browser.Engine.trident == true && Browser.Engine.trident6 != true)? -100: 0;
			
			
	var floatingLabel = new Tips('.mtip', {
		className: 'centerFix',
		offset: {'x': xOffset,'y': -40},
		title: 'html'
	});
	//---------------------------------------------------------------------------------------------------------------------------------------	


	//------------------------------------------------------------------------------------------------------------
	//When a nav item, or an unselected project is clicked
	//------------------------------------------------------------------------------------------------------------
	$$('.mtip', '.contentModule').addEvent('click', function(e){
		e.stop();		
		if(!this.hasClass('empty')) move(this.get('name'));
	});
	//------------------------------------------------------------------------------------------------------------

	
	//------------------------------------------------------------------------------------------------------------
	// If a user clicks to see more text
	//------------------------------------------------------------------------------------------------------------
	$$('.viewMoreText').addEvent('click', function(e){	
		
		var getText = new Request.JSON({
			url: 'includes/php/getProjectMedia.php',
			
			onRequest: function(txt){
				//fade out the info box
				if($$('.contentModule')[currentIndex +1].getElement('.moduleInfoWrapper'))$$('.contentModule')[currentIndex +1].getElement('.moduleInfoWrapper').fade('out');
			},
			
			onSuccess: function(obj){
					//Create the new DOM elements needed
					var textWrapper = new Element('div', {'class': 'textWrapper'}).inject(this.getParent('.contentModule')).fade('hide');
					var textHeadWrapper = new Element('div', {'class': 'textHeadWrapper'}).inject(textWrapper);
					var textLeft = new Element('div', {'class': 'textLeft'}).inject(textWrapper);
					var textLeftImg = new Element('img', {'src':obj.textImage ,'class': 'textLeftImg'}).inject(textLeft);
					var textRight = new Element('div', {'class': 'textRight'}).inject(textWrapper);
					var textRightText = new Element('div', {'class': 'textRightText', 'html': obj.moreText}).inject(textRight);
					var textNavClose = new Element('a', {'class': 'textNavClose', 'html': 'x close'}).inject(textHeadWrapper);	
					var textPrint = new Element('a', {'class': 'print', 'target': 'blank', 'href': 'print.php?p='+(currentIndex +1), 'html': 'print friendly version'}).inject(textLeft);
					
					textPrint.addEvent('click', function(){
						window.open(this.get('href'));	
					});
					
									
					textWrapper.fade('in');
					
					var scrollbars = new UvumiScrollbar(textRightText);
					
			
					textNavClose.addEvent('click', function(){
						textWrapper.kill();
						if($$('.contentModule')[currentIndex +1].getElement('.moduleInfoWrapper'))$$('.contentModule')[currentIndex +1].getElement('.moduleInfoWrapper').fade('in');
					});	
				

			}.bind(this)
		
		});
		
		//Ajax query to find the video locations
		getText.post({'need': 'text', 'project': this.getParent('.contentModule').get('id')});
		
	});
	
	
	if(Browser.Plugins.Flash.version < 8){
		$$('.viewVideo').destroy();
	}
	
	
	
	//------------------------------------------------------------------------------------------------------------
	//When view video is selected
	//------------------------------------------------------------------------------------------------------------
	$$('.viewVideo').addEvent('click', function(e){	
		
		var getMedia = new Request.JSON({
			url: 'includes/php/getProjectMedia.php',
			
			onRequest: function(txt){
				//fade out the info box
				if($$('.contentModule')[currentIndex +1].getElement('.moduleInfoWrapper'))$$('.contentModule')[currentIndex +1].getElement('.moduleInfoWrapper').fade('out');
			},
			
			onSuccess: function(obj){
					//Create the new DOM elements needed
					
					
					var videoWrapper = new Element('div', {'class': 'videoWrapper'}).inject(this.getParent('.contentModule')).fade('hide');
					var videoNavWrapper = new Element('div', {'class': 'videoNavWrapper'}).inject(videoWrapper);
					var videoHeadWrapper = new Element('div', {'class': 'videoHeadWrapper'}).inject(videoWrapper);
					
					
					var videoNavClose = new Element('a', {'class': 'videoNavClose', 'html': 'x close'}).inject(videoHeadWrapper);
					
					//If no flash found
					if(Browser.Plugins.Flash.build > 0){
						var vimeo = obj.vimeo;
						var videoObject = new Element('div', {'class': 'videoObject', 'width': '660', 'height': '371', 'html':'<object width="660" height="371"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id='+vimeo+'&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=3399cc&amp;fullscreen=1&amp;autoplay=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id='+vimeo+'&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=3399cc&amp;fullscreen=1&amp;autoplay=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="660" height="371"></embed></object>'});		
					}else{
						var address = obj.html5;
						var videoObject = new Element('div', {'class': 'videoObject', 'width': '660', 'height': '371', 'html': '<video width="660" height="371" controls autoplay><source src="'+address+'" type="video/mp4"></source></video>'});
					}
					
					videoWrapper.get('tween').start('opacity',1).chain(function() {
						videoObject.inject(videoWrapper);
					});
					
			
					videoNavClose.addEvent('click', function(){
						videoWrapper.kill();
						if($$('.contentModule')[currentIndex +1].getElement('.moduleInfoWrapper'))$$('.contentModule')[currentIndex +1].getElement('.moduleInfoWrapper').fade('in');
					});	
				

			}.bind(this)
		
		});
		
		//Ajax query to find the video locations
		getMedia.post({'need': 'video', 'project': this.getParent('.contentModule').get('id')});
		
	});
	//------------------------------------------------------------------------------------------------------------
		
		
	//------------------------------------------------------------------------------------------------------------	
	//When a slideshow is started
	//------------------------------------------------------------------------------------------------------------
	$$('.viewSlideshow').addEvent('click', function(e){
	
	
		
		//request the list of images
		var getMedia = new Request.JSON({
			url: 'includes/php/getProjectMedia.php',
			
			
			onRequest: function(txt){
				//fade the infowrapper out
				if($$('.contentModule')[currentIndex +1].getElement('.moduleInfoWrapper'))$$('.contentModule')[currentIndex +1].getElement('.moduleInfoWrapper').fade('out');
			},
			
			
			onSuccess: function(obj){

				var images = obj.images;
				
				var slideshowWrapper = new Element('div', {'class': 'slideshowWrapper'}).inject(this.getParent('.contentModule')).fade('hide');
					var slideshowNavWrapper = new Element('div', {'class': 'slideshowNavWrapper'}).inject(slideshowWrapper);
					var slideshowHeadWrapper = new Element('div', {'class': 'slideshowHeadWrapper'}).inject(slideshowWrapper);
						var slideshowCaption = new Element('div', {'id': 'slideshowCaption'}).inject(slideshowHeadWrapper);			
					
					slideshowHeadWrapper
					
				var slideshowImages = [];
				var currentSlideshowIndex = 0;
				
				var slideshowProgress = new Element('div', {'class': 'slideshowProgress'}).inject(slideshowWrapper).fade('hide');
				slideshowProgress.fade('in');
					
						
				// preload images
				var loader = new Asset.images(images, {
					onProgress: function(counter,index) {
						var percent = (counter + 1) * (100 / images.length);
						var intermed = map(percent, 0, 100, 8, 1);
						//var bgPos = (Math.floor(intermed) * -80) -3;
						var bgPos = (Math.floor(intermed) * -40);
						
						slideshowProgress.setStyle('background-Position', bgPos);
					},
					
					onComplete: function() {
						var slideshowNavBack = new Element('a', {'class': 'slideshowNavBack', 'html': '<< previous'}).inject(slideshowNavWrapper);
							var slideshowNavinfo = new Element('span', {'class': 'slideshowNavInfo', 'html': '| <strong id="currentImageNum">1</strong> of <strong>'+images.length+'</strong> |'}).inject(slideshowNavWrapper);
							var slideshowNavForward = new Element('a', {'class': 'slideshowNavForward', 'html': 'next >>'}).inject(slideshowNavWrapper);
						var slideshowNavclose = new Element('a', {'class': 'slideshowNavClose', 'html': 'x close'}).inject(slideshowHeadWrapper);
						var slideshow = new Element('div', {'class': 'slideshow'}).inject(slideshowWrapper);
						
					
						images.each(function(image, index){
						    slideshowImages[index] = new Element('img', {'class': 'slideshowImage', 'src': image}).inject(slideshow).fade('hide');
						});
						
						slideshowProgress.kill();
						slideshowImages[currentSlideshowIndex].fade('in');
						$('slideshowCaption').set('html', obj.captions[currentSlideshowIndex]);
						
						
						slideshowNavclose.addEvent('click', function(){
							slideshowWrapper.kill();
							if($$('.contentModule')[currentIndex +1].getElement('.moduleInfoWrapper'))$$('.contentModule')[currentIndex +1].getElement('.moduleInfoWrapper').fade('in');
						});	
				
						slideshowNavForward.addEvent('click', function(){
							slideshowImages[currentSlideshowIndex].fade('out');
							
							currentSlideshowIndex = (currentSlideshowIndex != images.length - 1)? currentSlideshowIndex +1: 0;
														
							slideshowImages[currentSlideshowIndex].fade('in');
							$('currentImageNum').set('html', currentSlideshowIndex +1);
							$('slideshowCaption').set('html', obj.captions[currentSlideshowIndex]);
										
						});	
						
								
						slideshowNavBack.addEvent('click', function(){
							slideshowImages[currentSlideshowIndex].fade('out');
							
							currentSlideshowIndex = (currentSlideshowIndex != 0)? currentSlideshowIndex -1: images.length - 1;
							
							slideshowImages[currentSlideshowIndex].fade('in');
							$('currentImageNum').set('html', currentSlideshowIndex +1);
							$('slideshowCaption').set('html', obj.captions[currentSlideshowIndex]);
										
						});
						
					}
				});
					
				slideshowWrapper.fade('in');
					
			}.bind(this)
			
		
		});
		
		getMedia.post({'need': 'slideshow', 'project': this.getParent('.contentModule').get('id')});
		
	});
	//------------------------------------------------------------------------------------------------------------



	//------------------------------------------------------------------------------------------------------------
	// This function takes an index number and moves us there. It also fades in/out everything, and closes anything needed
	// All cleanup is done here as well as bookmark setting and noting all the nav utems that need it
	//------------------------------------------------------------------------------------------------------------
	function move(index){
		index = parseInt(index);
	
		
		if(index != currentIndex){ 
			lastIndex = currentIndex;
			currentIndex = index;
			
			var location = $$('.mtip')[index].get('href').substring(1);
			var title = $$('.mtip')[index].get('html');
			
			document.location.assign('#-'+location); //change url and add history item.
			document.title = 'tellart | '+ title; //Change the title of the page
			
			if($$('.contentModule')[lastIndex +1].getElement('.videoWrapper')) $$('.contentModule')[lastIndex +1].getElement('.videoWrapper').destroy();
			if($$('.contentModule')[lastIndex +1].getElement('.slideshowWrapper')) $$('.contentModule')[lastIndex +1].getElement('.slideshowWrapper').kill();		
			if($$('.contentModule')[lastIndex +1].getElement('.textWrapper')) $$('.contentModule')[lastIndex +1].getElement('.textWrapper').kill();		
			if($$('.contentModule')[lastIndex +1].getElement('.moduleInfoWrapper'))$$('.contentModule')[lastIndex +1].getElement('.moduleInfoWrapper').fade('out');
						
			el = $$('.contentModule')[index + 1];
			
			$$('.moduleShield').fade(darkness);
			el.getElement('.moduleShield').fade('out');
			
			$$('.mtip').removeClass('selected');
			$$('.mtip')[index].addClass('selected');
			
			//caculate needed offset, home (index 0) has no offset
			var offset = (currentIndex == 0)? 0:  0 - ( ( $('content').getSize().x - el.getSize().x ) /2 );		
			windowMover.setOptions({offset: { 'x': offset}});
			
			if($$('.contentModule')[currentIndex +1].getElement('.preview')){
				var preview = $$('.contentModule')[currentIndex +1].getElement('.preview');
				var highRez = preview.get('name');
			}else{
				var preview = new Element('img');
			}
			
			var myImage = new Asset.image(highRez);
			
			//move to the desired project
			windowMover.toElement(el).chain(function() {
				if(el.getElement('.moduleInfoWrapper')) el.getElement('.moduleInfoWrapper').fade('in');
				
				preview.set('src', highRez);
				
				$$('.mtip')[index].addClass('selectedInThePast');
			});	
			
		}
	
	
	}
	//------------------------------------------------------------------------------------------------------------
});




//------------------------------------------------------------------------------------------------------------
// takes a range and formats it to a different range - Needed for the progress indicator
//------------------------------------------------------------------------------------------------------------
function map(val, min, max, minOut, maxOut){
	var base = val - min;
	var range = max - min;
	var percent = base / range;
	var rangeOut = maxOut - minOut;

	return (percent * rangeOut) + minOut;
}


var read = function(option, element){
	return (option) ? ($type(option) == 'function' ? option(element) : element.get(option)) : '';
};


this.Tips = new Class({

	Implements: [Events, Options],

	options: {
		/*
		onAttach: $empty(element),
		onDetach: $empty(element),
		*/
		onShow: function(){
			this.tip.setStyle('display', 'block');
		},
		onHide: function(){
			this.tip.setStyle('display', 'none');
		},
		title: 'title',
		text: function(element){
			return element.get('rel') || element.get('href');
		},
		showDelay: 100,
		hideDelay: 100,
		className: 'tip-wrap',
		offset: {x: 16, y: 16},
		windowPadding: {x:0, y:0},
		fixed: false
	},

	initialize: function(){
		var params = Array.link(arguments, {options: Object.type, elements: $defined});
		this.setOptions(params.options);
		if (params.elements) this.attach(params.elements);
		this.container = new Element('div', {'class': 'tip'});
	},

	toElement: function(){
		if (this.tip) return this.tip;

		return this.tip = new Element('div', {
			'class': this.options.className,
			styles: {
				position: 'absolute',
				top: 0,
				left: 0
			}
		}).adopt(
			new Element('div', {'class': 'tip-top'}),
			this.container,
			new Element('div', {'class': 'tip-bottom'})
		).inject(document.body);
	},

	attach: function(elements){
		$$(elements).each(function(element){
			var title = read(this.options.title, element),
				text = read(this.options.text, element);
			
			element.erase('title').store('tip:native', title).retrieve('tip:title', title);
			element.retrieve('tip:text', text);
			this.fireEvent('attach', [element]);
			
			var events = ['enter', 'leave'];
			if (!this.options.fixed) events.push('move');
			
			events.each(function(value){
				var event = element.retrieve('tip:' + value);
				if (!event) event = this['element' + value.capitalize()].bindWithEvent(this, element);
				
				element.store('tip:' + value, event).addEvent('mouse' + value, event);
			}, this);
		}, this);
		
		return this;
	},

	detach: function(elements){
		$$(elements).each(function(element){
			['enter', 'leave', 'move'].each(function(value){
				element.removeEvent('mouse' + value, element.retrieve('tip:' + value)).eliminate('tip:' + value);
			});
			
			this.fireEvent('detach', [element]);
			
			if (this.options.title == 'title'){ // This is necessary to check if we can revert the title
				var original = element.retrieve('tip:native');
				if (original) element.set('title', original);
			}
		}, this);
		
		return this;
	},

	elementEnter: function(event, element){
		this.container.empty();
		
		['title', 'text'].each(function(value){
			var content = element.retrieve('tip:' + value);
			if (content) this.fill(new Element('div', {'class': 'tip-' + value}).inject(this.container), content);
		}, this);
		
		$clear(this.timer);
		this.timer = (function(){
			this.show(this, element);
			this.position((this.options.fixed) ? {page: element.getPosition()} : event);
		}).delay(this.options.showDelay, this);
	},

	elementLeave: function(event, element){
		$clear(this.timer);
		this.timer = this.hide.delay(this.options.hideDelay, this, element);
		this.fireForParent(event, element);
	},

	fireForParent: function(event, element){
		element = element.getParent();
		if (!element || element == document.body) return;
		if (element.retrieve('tip:enter')) element.fireEvent('mouseenter', event);
		else this.fireForParent(event, element);
	},

	elementMove: function(event, element){
		this.position(event);
	},

	position: function(event){
	

	
	
	
		if (!this.tip) document.id(this);

		var size = window.getSize(), scroll = window.getScroll(),
			tip = {x: this.tip.offsetWidth, y: this.tip.offsetHeight},
			props = {x: 'left', y: 'top'},
			obj = {};
		
		for (var z in props){
			obj[props[z]] = event.page[z] + this.options.offset[z];
			if ((obj[props[z]] + tip[z] - scroll[z]) > size[z] - this.options.windowPadding[z]){
				obj[props[z]] = event.page[z] - this.options.offset[z] - tip[z];
			}	
			
			
			 ///*start custom by Adam*/f.left=f.left-(this.container.getSize().x/4)/*end custom*/   }this.tip.setStyles(f)},fill:function(a,b){if(typeof b=="string"){a.set("html",b)}else{a.adopt(b)}},show:function(a){this.fireEvent("show",[this.tip,a])},hide:function(a){this.fireEvent("hide",[this.tip,a])}});
		}
		
		
		
		obj.left=obj.left-(this.container.getSize().x/2)
		
		this.tip.setStyles(obj);
	},

	fill: function(element, contents){
		if(typeof contents == 'string') element.set('html', contents);
		else element.adopt(contents);
	},

	show: function(element){
		if (!this.tip) document.id(this);
		this.fireEvent('show', [this.tip, element]);
	},

	hide: function(element){
		if (!this.tip) document.id(this);
		this.fireEvent('hide', [this.tip, element]);
	}

});
