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,
			// whether to show next and prev buttons
			useNavButtons:false,
			// array of images to get
			imgArray:null,
			//dimensions
			slideWidth:0,
			slideHeight:0
		}, 
	
	log: function(){
		if(window['console']) console.log.apply(null, 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('img.default');
		if(defaultImg){
			
			this.slides[0] ='';
			
			this.options.imgArray.unshift('');
		}
		
		this.totalImg =  this.options.imgArray.length;
		
			
		this.StartPeriodical(this.delayms);
		
		//$('article-viewport').getElement('div.articles').tween('left',0);
		
	},
	
	NextSlide:function(event,paramArray){
		// 'this' == ClassPromo
		// boolean isNext determines if moving forwards or back
		if(event) event.stop();

		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
		//this.imgSpinner = new Spinner(this.options.viewPort);
		//this.imgSpinner.show();
		var myHTMLRequest = new Request.JSON({url:'ajax-miniphoto', 'onSuccess' : this.LoadImg.bind(this) , 'onFailure': function(){}  });
		myHTMLRequest.get({'file': filePath, 'width': this.options.slideWidth,'height':this.options.slideHeight,'fill':'1'});
		myHTMLRequest.send();

	},
	
	LoadImg:function(responseJSON, responseText){
		// loads image via HTTP
		
		if(responseJSON.success){
			
			this.tempImg = new Asset.image(responseJSON.img,{'onload':this.LoadImgSuccess.bind(this)});
		}else{
			
		}
	},
	
	
	
	LoadImgSuccess:function(){
		
			//this.imgSpinner.hide();
			//this.tempImg.fade('hide');
			var tempImg = new Element('div');
			
			
			
			tempImg.setStyle('background-image','url("'+this.tempImg.getProperty('src')+'")');
			tempImg.fade('hide');
			// insert
			
			this.options.viewPort.grab(tempImg);
			
			this.slides[this.nextImg] = tempImg;
			
		
		
			//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);
						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);
			
			
			
		}else{
			fadeOutCurrSlide();
		}
			
		
		
		
	},
	
	StartPeriodical:function(delayms){
		//console.log(delayms);
		this.periodID = this.NextSlide.bindWithEvent(this,{'isNext':true,'clickIsFromUser':false}).periodical(delayms);
		
	}
	
	
});

var Fixable = new Class({
	/* adds class to element when it leaves the viewport 
		used to turn an regular element into position:fixed
	*/
	Implements: [Options,Events, Chain], 						  
	
	/* menu options. don't put a comma after the last option! */
	options: {
		/* class to add */
		'css':null,
		/* target element  */
		'element':null,
		/* if offset != 0, will be added to element coord */ 
		'offset':0
		
		
		
	},
	log: function(){
		if(console) console.log.apply(null, arguments);
	}, 
	/* this function runs whenever a new instance of this class is made. */
	initialize: function(options){ 
		/* use the options specified */
		this.setOptions(options);
		//this.log(options);
		
		if(!this.options.element) return false;
		
		
		
		this.targetElement = document.getElement(this.options.element);
		
		
		
		if(!this.targetElement) return false;
		
		
		this.targetElementOffsetParent = this.targetElement.getOffsetParent();
		//if(this.targetElementOffsetParent){
				//this.log('offsetParent=',offsetParent);
	//			this.offsetParentPos = this.targetElementOffsetParent.getPosition();
				
				//this.log('this.offsetParentPos=',this.offsetParentPos);
		//}

		this.targetElementOrigPos = this.targetElement.getPosition(this.targetElementOffsetParent);
		//this.log('this.targetElementOrigPos=',this.targetElementOrigPos);

		
		//this.log('this.targetElement=',this.targetElement);
		
		window.addEvent('scroll',
			this.monitor.bindWithEvent(this)
		);
		
		window.addEvent('resize',
			this.monitor.bindWithEvent(this)
		);
		
		window.addEvent('domready',
			this.monitor.bindWithEvent(this)
		);
	},
	
	
	
	monitor:function(event,paramArray){
		//this.log('hey yo');
		
		var windowScroll = window.getScroll();
		//var elPosition = this.targetElement.getPosition();
		//this.log('windowScroll.y=',windowScroll.y,'elPosition.y=',elPosition.y);
		
		//var offsetParent = this.targetElement.getOffsetParent();
		if(this.targetElementOffsetParent){
				//this.log('offsetParent=',this.targetElementOffsetParent);
				this.offsetParentPos = this.targetElementOffsetParent.getPosition();
				
				//this.log('this.offsetParentPos=',this.offsetParentPos);
		}

		//this.targetElementOrigPos = this.targetElement.getPosition(offsetParent);

		//alert(Boolean(windowScroll.y > (Number(this.targetElementOrigPos.y) + Number(this.options.offset)) ))
		//alert('windowScroll.y='+windowScroll.y+'elPosition.y=' + (Number(this.targetElementOrigPos.y)+Number(this.options.offset)));
		
		if(Number(windowScroll.y) > (Number(this.targetElementOrigPos.y) + Number(this.options.offset))){
			/* element is off top of screen */
			/* add offset parent X coord */
			this.targetElement.setStyle('left', this.targetElementOrigPos.x + this.offsetParentPos.x ); 
			this.targetElement.addClass(this.options.css);
			//alert('FIXED windowScroll.y='+windowScroll.y+'elPosition.y=' + (Number(this.targetElementOrigPos.y)+Number(this.options.offset)));
		}else{
			//alert('NOT FIXED windowScroll.y='+windowScroll.y+'elPosition.y='+(Number(this.targetElementOrigPos.y)+Number(this.options.offset)));
			this.targetElement.removeClass(this.options.css);
			this.targetElement.setStyle('left', this.targetElementOrigPos.x);
			
		}
		
	}

});

var IntraPageMenu = new Class({
	/* creates menu of links to Headings on page */
	Implements: [Options,Events, Chain], 						  
	
	/* menu options. don't put a comma after the last option! */
	options: {
		/* element to search inside */
		'container':null,
		/* element after which TOC will appear */
		'insertAfter':null
		
	},
	log: function(){
		if(console) console.log.apply(null, arguments);
	}, 
	/* this function runs whenever a new instance of this class is made. */
	initialize: function(options){ 

		/* use the options specified */
		this.setOptions(options);
		
		//this.log(options);
		
		
		
		/* initial vars */
		//var finders = ['h1','h2','h3','h4','h5','h6'];
		var finders = 'h2';
		var matches = [];
		var finalMatches=[];
		//var backToTopArray = [];
		var anchorArray=[];
		
		matches = document.getElement(this.options.container).getElements(finders);
		//this.log(matches);
		
		/* a single FX to be controlled by all anchors */
		this.windowScrollFx = new Fx.Scroll(window,{'link':'cancel'});
		
		//return false;
		
		matches.each(function(el,i) {
			//this.log(el);
			/* add span for hilite */
			if(el.get('text')=='')return false;
			
			var span = new Element('span',{'html':el.get('html')})
			el.set('html', '').grab(span);
			
			
			var anchorText = el.get('text');
			
			/* prepend anchor with 'hide_' and it will not be used */
			if(namedAnchor = el.getElement('a[name!=""]')){
				//this.log('namedAnchor.name=',namedAnchor.name);
				if(String(namedAnchor.name).substr(0,5) != 'hide_'){
					anchorText = namedAnchor.name;
				}
			}
			
			
			
			
			
			//this.log('anchorText',anchorText);
			
			/* if contains named anchor */
				
			//finalMatches.include(el);
			
			//create anchor
			var anchor = new Element('a', {
				'class': el.get('tag'),
				'text': anchorText,
				'href': 'javascript:;'
			});

			/* click event */
			anchor.addEvent('click', this.scrollTo.bindWithEvent(this,el));
			
			//add into our matches array
			anchorArray.include(anchor);
		}.bind(this));
		
		
			
		//should we show the toc?
		if(anchorArray.length)
		{
			/* create toc div, inject */

			var toc = new Element('div', {
				'id': 'auto-toc'
			}).inject(document.getElement(this.options.insertAfter),'after');

	
			//inject the matches
			anchorArray.each(function(el) {
				el.inject(toc);
			});
		}
	},
	
	scrollTo:function(event,el){
		/* don't ask how, but variable el works in this context */
		this.chain(function(){this.hiliteHeading(el)}.bind(this));
		
		//this.log(window.getScroll().y);
		//this.log('el.getPosition()[y]-35=',el.getPosition()['y']-35);
		
		if(window.getScroll().y == el.getPosition()['y']-35 ){
			/* already there */
			this.callChain();
		}else{
			/* scroll */
			this.windowScrollFx.start(el.getPosition()['x'],el.getPosition()['y']-35).chain(function(){this.callChain()}.bind(this));
		}
		
		
	},
	
	hiliteHeading:function(el){
/*
		Note how variables are scoped to el
		This allows us to bind the chain func to the common scope (el) and access both variables
*/
		el.myFx = new Fx.Tween(el, {'property':'color','link':'cancel','duration': 'normal','transition': Fx.Transitions.Sine.easeInOut});
		el.origColor = el.getStyle('color');
		el.myFx.start('#FFF').chain(function(){this.myFx.start(this.origColor)}.bind(el));
	}
	
	

});


	


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));
	
}

