var GalleryAtm = new Class({
	Implements: [Options,Events, Chain], 						  
	 /* menu options. don't put a comma after the last option! */
	options: {
		/* selector */
		'container':'',
		/* selector */
		'thumb':'',
		/* selector */
		'bgContainer':'',
	}, 
	
	log: function(){
		return false;
		if('console' in window && 'log' in window.console) console.log.apply(console, arguments);

		
	},
	/* this function runs whenever a new instance of this class is made. */
	initialize: function(options){ 
		
		this.setOptions(options);
		this.log('1 this.options=',this.options);
		
		if(!this.options.container || !this.options.thumb || !this.options.bgContainer)return false;
		
		this.largeImgWidth = 780;
		this.currentImgIndex = 0;
		/* overlay */
		this.Overlay = new Element('div',{'class':'overlay'});
		
		this.OverlayFx = new Fx.Tween(this.Overlay,{'property':'opacity'});
		this.OverlayFx.set(0);
		
		//this.log('this.options.bgContainer=',this.options.bgContainer);
		
		
		this.log('this.Overlay=',this.Overlay);
		//this.Overlay.fade('in');
		
		/* image portal */
		this.ImgPortal = new Element('div',{'id':'gallery-portal'});
		this.ImgPortal.fade('hide');
		
		this.LargeImages = [];
		
		
		if(this.Container = document.getElement(this.options.container)){
			this.log('this.Container=',this.Container);
			
			if(this.Thumbs = this.Container.getElements(this.options.thumb)){
				this.log('this.Thumbs=',this.Thumbs);
				/* process all thumbs */
				this.Thumbs.each(
								function(item, index, array){
									var Link, LargeImage;
									if(Link = item.getElement('a')){
										//this.log('Link=',Link);
										/* add click handler */
										Link.addEvent('click',function(event){ event.stop();this.ThumbClick({'imgIndex':index}) }.bind(this));
									}
									/* add corresponding large image */
									LargeImage = new Element('div',{'class':'image'});
									LargeImage.setStyle('background-image','url(\'' + Link.href + '\')');
									this.LargeImages.push(LargeImage);

									
									
								},this
							);
			}
		}
		
		this.log('LargeImages=',this.LargeImages);
		
		this.ImgScrollFx = new Fx.Scroll(this.ImgPortal);
		
		this.ImgWrapper = new Element('div',{'class':'image-wrapper'});
		this.ImgWrapper.setStyle('width',this.LargeImages.length * this.largeImgWidth)
		this.ImgPortal.grab(this.ImgWrapper);
		/* insert into portal */
		this.ImgWrapper.adopt(this.LargeImages);
		
		/* gallery nav controls */
		this.Nav = new Element('div',{'id':'gallery-nav'});
		this.Nav.fade('hide');
		this.Nav.Next = new Element('a',{'text':'Next','title':'Next Image','class':'next'});
		this.Nav.Prev = new Element('a',{'text':'Previous','title':'Previous Image','class':'prev'});	
		this.Nav.Close = new Element('a',{'text':'Close','title':'Close Large Image','class':'close'});	
		
		this.Nav.Next.addEvent('click',this.ScrollImage.bind(this,{'next':true}));
		this.Nav.Prev.addEvent('click',this.ScrollImage.bind(this,{'prev':true}));
		this.Nav.Close.addEvent('click',this.CloseGallery.bind(this));
		
		this.Nav.grab(this.Nav.Close);		
		this.Nav.grab(this.Nav.Prev);
		this.Nav.grab(this.Nav.Next);	

		if(el = document.getElement(this.options.bgContainer)){
			//this.Nav.inject(el,'after');
			//this.ImgPortal.inject(el,'after');
			
			//var portalWrap = new Element('div',{'id':'gallery-portal-wrap'});
			//portalWrap.grab(this.ImgPortal);
			//portalWrap.inject(el,'after');
			
			this.Overlay.inject(el,'after').grab(this.ImgPortal).grab(this.Nav);
		}

		
	},
	
	ThumbClick:function(params){
		this.log('CLICK');
		
		/* queue functions */
		this.chain(
			this.SetScroll.pass(params,this),
			this.ShowOverlay,
			this.ShowImagePortal,
			this.ShowNav,	
			function(){this.clearChain(); this.log('CHAIN COMPLETE')}
		);
		
		/* update current img index */
		this.currentImgIndex = params.imgIndex;
		/* begin */
		this.callChain();
	},
	
	SetScroll:function(params){
		/* positions portal to view required image */
		this.log('params=',params);
		if (params.imgIndex < 0){
			params.imgIndex = 0;
		}
		this.log('SetScroll',params);
		
		/* set to img immediately */
		this.ImgScrollFx.set(params.imgIndex * this.largeImgWidth, 0);
		
		this.callChain();
	},
	
	ShowOverlay:function(){
		/* fades in dark overlay */
		this.log('ShowOverlay');
		this.OverlayFx.start(1).chain(
			/* will run on complete */
			function(){
				this.callChain(); /* the chain of GalleryAtm */
			}.bind(this)
		);
	},
	
	ShowImagePortal:function(event){
		/* shows large image */
		var ImgPortalTween = new Fx.Tween(this.ImgPortal,{'property':'opacity'});
		this.log('ShowImagePortal');
		ImgPortalTween.start(1).chain(
			/* will run on complete */
			function(){
				this.callChain(); /* the chain of GalleryAtm */
			}.bind(this)
		);
	},
	ShowNav:function(event){
		/* shows gallery nav controls  */
		
		var NavTween = new Fx.Tween(this.Nav,{'property':'opacity'});
		this.log('ShowNav');
		NavTween.start(1).chain(
			/* will run on complete */
			function(){
				this.callChain(); /* the chain of GalleryAtm */
			}.bind(this)
		);
	},


	ScrollImage:function(params){
		/* scrolls to a given image */

		if(params.prev){
			/* back */
			this.currentImgIndex--;	
		}else{
			/* forward */
			this.currentImgIndex++;
		}
		
		if(this.currentImgIndex >= this.LargeImages.length){
			/* reset */
			this.currentImgIndex=0;
			this.log('RESET');
		}else if(this.currentImgIndex < 0){
			/* reset */
			this.currentImgIndex=this.LargeImages.length;
			this.log('RESET');
		}
		
		
		this.log('SCROLL TO ', this.currentImgIndex, ' OF ', this.LargeImages.length, this.LargeImages[this.currentImgIndex]);
		
		//this.ImgScrollFx.toElement(this.LargeImages[this.currentImgIndex]);
		
		this.ImgScrollFx.start( this.largeImgWidth * this.currentImgIndex, 0);
	},
	
	CloseGallery:function(params){
		this.log('CLOSE');
		this.OverlayFx.start(0);
		this.ImgPortal.tween('opacity',0);
		this.Nav.tween('opacity',0);
	}
});

var DelayedWelcome = new Class({
	/* hides content, then shows on mousemove */
	Implements: [Options,Events, Chain], 						  
	
	options: {
		/* array of div selectors */
		bgImgs:'',
		/* array of div selectors */
		hiddenElements:'',
		/* array of selectors */
		fadingElements:'',
		/* show fading or skip */
		showTransition:true
		
	}, 
	
	log: function(){
		return false;
		if('console' in window && 'log' in window.console) console.log.apply(console, arguments);

		
	},
	/* this function runs whenever a new instance of this class is made. */
	initialize: function(options){ 
		
		this.setOptions(options);
		this.log('this.options=',this.options);
		
		if(!this.options.hiddenElements)return false;
		/* bg img */
		this.BgImgs = new Array();
		/* all hidden elements */
		this.HiddenElements = new Array();
		/* all fading elements */
		this.FadingElements = new Array();
		/* store bound function */
		this.showElements_Bound = this.showElements.bind(this);
		
		this.fadeInTimeout = 3000;/* ms */
		
		if(this.options.bgImgs){
			this.options.bgImgs.each(
							function(item, index, array){
								if(el = document.getElement(item)){
									el.TransitionFx = new Fx.Tween(el, {'property':'opacity','duration':'long','link':'cancel'});
									el.TransitionFx.set(0);
									el.setStyle('left','0');
									this.BgImgs.push(el);					
								}
								
							},this
						);
			
			
		}
		
		this.options.hiddenElements.each(
						function(item, index, array){
							var el = false;
							if(el = document.getElement(item)){
								el.setStyle('left','-10000px');
								
								el.TransitionFx = new Fx.Tween(el, {'property':'opacity','duration':'long','link':'cancel'});
								el.TransitionFx.set(0);
								el.setStyle('left','0');
								var finalOpacity = 1;
								
//								var elBgImg = false;
//								if(elBgImg = el.getStyle('background-image')){
//									if(elBgImg.contains('bg-black-')){
//										/* is overlay */
//										/* remove */
//										el.setStyle('background-image','none');
//										el.setStyle('background-color','#000');
//										el.setStyle('left','0');
//										finalOpacity = 0.55;
//									}
//								}
								
								bgOpacity = this.replaceOverlay(el);
								if(bgOpacity !==  false){
									finalOpacity = bgOpacity;
								}

								this.log('finalOpacity=',finalOpacity);

								this.HiddenElements.push(el);
								this.chain(
									function(el){el.TransitionFx.start(finalOpacity).chain( function(){this.callChain()}.bind(this) ); }.bind(this,el)
								);
								
								if(this.options.showTransition){
									/* chain transition */
									
								}else{
									/* show immediately */
									el.TransitionFx.start(finalOpacity);
									
								}
							}
							
						},this
					);		
					
		if(this.options.fadingElements && this.options.fadingElements[0]){
			this.fadeOpacity = 0.45;
			
			this.options.fadingElements.each(
							function(item, index, array){
								if(el = document.getElement(item)){
									bgOpacity = this.replaceOverlay(el);
									if(bgOpacity !==  false){
										finalOpacity = bgOpacity;
									}else{
										finalOpacity = this.fadeOpacity;
									}
									
								
									
									if(this.options.showTransition){
										/* make all these fade in from 0 up  */
										el.setStyle('opacity','0');
										el.setStyle('left','0');
										el.TransitionFx = new Fx.Tween(el, {'property':'opacity','duration':'long','link':'cancel'});
										

										
										this.FadingElements.push(el);
										this.chain(
											function(el){el.TransitionFx.start(finalOpacity).chain( function(){this.callChain()}.bind(this) ); }.bind(this,el)
										);
									}else{
										
										/* show immediately */
										el.TransitionFx.start(finalOpacity);
									}
								}
								
							},this
						);
		
		}
		
		

		
		
		
		
		//this.log('this.HiddenElements=',this.HiddenElements);
		//this.log('this.FadingElements=',this.FadingElements);
		
		
	},
	
	replaceOverlay:function(el){
		var finalOpacity = false;
		var elBgImg = false;
		if(elBgImg = el.getStyle('background-image')){
			if(elBgImg.contains('bg-black-')){
				/* is overlay */
				/* remove */
				el.setStyle('background-image','none');
				el.setStyle('background-color','#000');
				el.setStyle('left','0');
				finalOpacity = 0.65;
			}
		}
		
		this.log('el=',el);
		
		return finalOpacity;
	},
	
	prepare:function(){
	
		/* fade in all bg imgs immediately */
		if(this.BgImgs){
			this.BgImgs.each(
							function(item, index, array){
								item.TransitionFx.start(1);					
							},this
						);
			
		}
		
		if(Browser.Platform.ios){
			/* iphone, ipad: no delay, show immediately */
			this.showElements();
		}else if(this.options.showTransition){
			/* body rollover triggers show */
			document.getElement('body').addEvent('mouseenter',this.showElements_Bound);
			/* show after fixed delay */
			this.showElements_Bound.delay(this.fadeInTimeout);
		}
	
	},
	
	showElements:function(){
		//this.log('You dun moved me');
		//this.log('arguments.callee',arguments.callee);
		document.getElement('body').removeEvent('mouseenter',this.showElements_Bound);
		
/*
		if(this.HiddenElements){
			this.HiddenElements.each(
							function(item, index, array){
								if(item.TransitionFx)item.TransitionFx.start(1);
							},this
						);
		}
*/		this.callChain();
	}
	
	
});


var DynamicSlideshow = new Class({
	// home page slideshow
	Implements: [Options,Events, Chain], 						  
	
	 // menu options. don't put a comma after the last option!
	options: {
	 	// whether to enable the first item. This is generally only true for the home page.
			
			// which viewport to use
			viewPort:null,
			// delay in ms
			slideDelay: 3000,
			// transition length in ms
			slideTransitionLength: 2000,
			/* delay at start? */
			startDelay: 0,
			// whether to show next and prev buttons
			useNavButtons:false,
			// array of images to get
			imgArray:null,
			/* =array(width,height) */
			imgDimensions:null
		}, 
	
	log: function(){
		return false;
		if('console' in window && 'log' in window.console) console.log.apply(console, arguments);

		
	},
	// this function runs whenever a new instance of this class is made.
	initialize: function(options){ 
		// use the options specified
		
		this.setOptions(options);
		
		// Dynamically generate navigation links from promo links
		
		if(!this.options.viewPort || !this.options.imgArray) return false;
		
		
		
		
		
		//
		this.slides = new Array('');
		this.delayms = this.options.slideDelay + this.options.slideTransitionLength;
		this.currentImg = 0;
		
		
		
		//check if default img exists
		var defaultImg = this.options.viewPort.getElement('div.slide.default');
		if(defaultImg){
			
			this.slides[0] ='';
			
			this.options.imgArray.unshift('');
		}
		
		this.totalImg =  this.options.imgArray.length;
		
			
		this.StartPeriodical.delay(this.options.startDelay, this, this.delayms);
		
		//$('article-viewport').getElement('div.articles').tween('left',0);
		
	},
	
	NextSlide:function(paramArray){
		// 'this' == ClassPromo
		// boolean isNext determines if moving forwards or back
		

		var isNext = paramArray['isNext'];
		this.clickIsFromUser = paramArray['clickIsFromUser'];
		 
		//clear timer
		if(this.clickIsFromUser) {

			$clear(this.periodID);
		}
		
		this.nextImg='';
		
		if(isNext){
			//forward
			
			if(this.currentImg == this.totalImg-1){
				//reset to 0
				this.nextImg = 0;
			}else{
				this.nextImg = this.currentImg+1;
				
			}
		}else{
			//backwards
			if(this.currentImg == 0){
				//reset to 0
				this.nextImg = this.totalImg-1;
			}else{
				this.nextImg = this.currentImg-1;
				
			}
		}
		
		
		//check if 
		if(this.nextImg==0 || this.slides[this.nextImg]){
			//slide already exists
			this.TransitionSlide();
		}else if(this.nextImg > 0){
			// load img via ajax
			this.GetImgAjax(this.options.imgArray[this.nextImg]);
		}
		
		
	},
	
	GetImgAjax:function(filePath){
		// get next img via ajax
		
		var myHTMLRequest = new Request.JSON({url:'ajax-miniphoto', 'onSuccess' : this.LoadImg.bind(this) , 'onFailure': function(e){this.log('FAIL=',filePath)}.bind(this,filePath)  });
		myHTMLRequest.get({'file': filePath, 'width': this.options.imgDimensions[0],'height':this.options.imgDimensions[1],'fill':'1'});
		myHTMLRequest.send();

	},
	
	LoadImg:function(responseJSON, responseText){
		// loads image via HTTP
		this.tempImg = '';
		if(responseJSON.success){
			
			this.tempImg = new Asset.image(responseJSON.img,{'onload':this.LoadImgSuccess.bind(this)});
		}else{
			
		}
	},
	
	
	
	LoadImgSuccess:function(){
		//this.tempImg.fade('hide');
		/* create wrapper element */
		var wrapper = new Element('div',{'class':'slide'});
		wrapper.fade('hide');
		/* set bg */
		//this.log('this.tempImg=',this.tempImg);
		wrapper.setStyle('background-image','url("'+this.tempImg.getProperty('src')+'")');
		this.log('wrapper=',wrapper);
		/* insert */
		this.options.viewPort.grab(wrapper);
		
		this.slides[this.nextImg] = wrapper;
		
	
	
		//fadein
		this.TransitionSlide();
		
		//this.slides[nextImg].fade('in');
	
		if(this.clickIsFromUser) {
			this.periodID = this.StartPeriodical.delay(this.delayms*2, this, this.delayms);

		}

	},
	
	
	
	TransitionSlide:function(){
		// actual fade transition
		
		
		
		
		
		
		var currFx = false;
		var fadeOutCurrSlide = function(){this.currentImg = this.nextImg;}.bind(this);
		
		if(this.slides[this.currentImg]) {
			//this.slides[this.currentImg].fade('out');
			var currFx = new Fx.Tween(this.slides[this.currentImg],{property: 'opacity','duration':this.options.slideTransitionLength});
			// a bound function to fade out current slide
			fadeOutCurrSlide = function(){
				if(currFx) {
					if(this.nextImg == 0) {
						//fade out curr slide
						currFx.start(1,0).chain(function(){this.currentImg = this.nextImg;}.bind(this));
					}else{
						// hide curr slide
						currFx.set(0);
						currFx = false;
						this.currentImg = this.nextImg;
					}
					
					
				}
				
				
				
			}.bind(this);
		}
		
		
		
		if(this.slides[this.nextImg]) {
			var nextFx = new Fx.Tween(this.slides[this.nextImg],{property: 'opacity','duration':this.options.slideTransitionLength});
			
			
			
			nextFx.start(0,1).chain(fadeOutCurrSlide);
			nextFx = false;
			
			
		}else{
			fadeOutCurrSlide();
		}
			
		
		
		
	},
	
	StartPeriodical:function(delayms){
		//console.log(delayms);
		this.periodID = this.NextSlide.bind(this,{'isNext':true,'clickIsFromUser':false}).periodical(delayms);
		
	}
	
	
});


var FlashHeader = new Class({
	/* if flash installed, change logo image and add flash object */
	Implements: [Options,Events, Chain], 						  
	
	 /* menu options. don't put a comma after the last option! */
	options: {
		/* how to get the trigger element (e.g. a link class) */
		
		'container':'',
		'image':'',
		'imageReplace':'',
		'link':'',
		'flash':'',
		'flashDimensions':''
	}, 
	
	log: function(){
		return false;
		if('console' in window && 'log' in window.console) console.log.apply(console, arguments);

		
	},
	/* this function runs whenever a new instance of this class is made. */
	initialize: function(options){ 
		
		this.setOptions(options);
		//this.log('1 this.options=',this.options);
		
		if(this.flashInstalled()){
			
			if(this.options.image && this.options.imageReplace){
				/* change logo img src */
				this.options.image.set('src',this.options.imageReplace);
			}
			
			//if(this.options.link && this.options.container){
				/* remove link */
				//this.options.link.dispose();
				/* add image back in */
				//this.options.container.grab(this.options.image);
			//}
			
			if(swfobject && this.options.flash && this.options.flashDimensions){
				/* create holder */
				this.options.container.grab(new Element('div',{'id':'flash-banner'}));
				var params = {'wmode':'transparent'};
				var attributes = {};
				var flashvars = {};
				/* add flash */
				swfobject.switchOffAutoHideShow();
				swfobject.embedSWF(this.options.flash, "flash-banner", this.options.flashDimensions[0], this.options.flashDimensions[1], "9.0.0", "expressInstall.swf", flashvars, params, attributes);

			}
			
			
		}
	},
	flashInstalled:function(){
		var r=false;
		/* http://www.featureblend.com/javascript-flash-detection-library.html */
		if(FlashDetect.installed && FlashDetect.major>=9){
			r = true;
		}
		return r;
	}
});


function checkIE6(){
	// adds content to the page for IE6 users.
	if(Browser.Engine.trident && Browser.Engine.version == 4 ){
		var txt = new Element('div', {'id':'ie6Warning','html':'<h2>Time to upgrade your browser!</h2><p>You are using Internet Explorer 6, an out-dated browser that cannot cope with the demands of the modern internet.</p><p>We recommend upgrading to <a href="http://www.getfirefox.com/">Mozilla Firefox</a>, <a href="http://www.apple.com/safari/">Apple Safari</a>, <a href="http://www.google.com/chrome">Google Chrome</a>, <a href="http://www.opera.com/">Opera</a> or the latest version of <a href="http://www.microsoft.com/windows/downloads/ie/getitnow.mspx">Internet Explorer</a>.</p><p>For more information, please visit <a href="http://www.browserupgrade.info/ie6/">browserupgrade.info</a>.</p>'});
		$(document.body).grab(txt);
	}
}

function logoToolTip(){
	// Hover effect for Logo link
	var logoLink = $('atm-link');
	
	//create the tooltip DIV
	var toolTip = $('atm-info');
	toolTip.setStyles({'opacity':0,'right':'0px'});
	//alert(Browser.Engine.name);
	
	if(Browser.Engine.name == 'webkit'){
		// safari, chrome
		//toolTip.setStyles({'top':'-95%'});
	}
	
	//create morph obj
	tooltipMorph = new Fx.Morph(toolTip,{'link':'cancel','duration': 'normal', 'transition': Fx.Transitions.Sine.easeInOut});
	
	var showTooltip = function(){
		var dest = 127;
		if(Browser.Platform.win && Browser.Engine.name == 'trident' && Browser.Engine.version<='5'){
			var dest = 120;
		}
		
		//clear timer
		if(this.timeoutID!==undefined) $clear(this.timeoutID);
		
		this.start({
			'opacity': 1   
		});
		
	}
	var hideTooltip = function(){
		// fade out
		this.start({
				'opacity': 0   
		});
	}
	
	var startHideTooltipTimer = function(){
		//begin timer to fade out
		this.timeoutID = hideTooltip.delay(1000,this);
	}
	
	var clearTimer = function(){
		//clear timer
		if(this.timeoutID!==undefined) $clear(this.timeoutID);
	}
	
	//console.log(hideTooltip);
	
	logoLink.addEvent('mouseenter', showTooltip.bind(tooltipMorph));
	logoLink.addEvent('mouseleave', startHideTooltipTimer.bind(tooltipMorph));
	
	toolTip.addEvent('mouseenter', clearTimer.bind(tooltipMorph));
	toolTip.addEvent('mouseleave', startHideTooltipTimer.bind(tooltipMorph));
	
}

