var FormLabelFader = new Class({
	/* places an input's label directly above it. fades label out on focus, back in on blur (if empty)  */
	Implements: [Options,Events, Chain], 						  
 
 
	options: {
		/* css selector */
		formElement:null
	}, 
 
	log: function(){
		//console.log.apply(console, arguments);
 
	},
	// this function runs whenever a new instance of this class is made.
	initialize: function(options){ 
		this.setOptions(options);
 
		if(!this.options.formElement) return false;
 
		this.log(this.options.formElement);
 
		if(this.fieldElement = document.getElement(this.options.formElement)){
			this.log( this.fieldElement);	
 
			if(this.fieldElementParent = this.fieldElement.getParent()){
				this.fieldLabel = this.fieldElementParent.getElement('label[for='+this.fieldElement.get('id')+']');
				this.fieldLabel.FadeFx = new Fx.Tween(this.fieldLabel,{'property':'opacity','duration':'short'});
				this.fieldLabel.FadeFx.set(0);
 
				this.fieldLabel.addClass('fader');
 
				/* position */
				this.fieldLabel.setPosition( this.fieldElement.getPosition(this.fieldElementParent) ); 
 
				this.showLabel();
			}
 
			this.fieldElement.addEvent('focus',this.hideLabel.bind(this));
			this.fieldElement.addEvent('blur',this.showLabel.bind(this));
 
			if(this.fieldElement.value) this.hideLabel();
 
 
 
		}
 
	},
 
	hideLabel:function(){
		//empty
		//this.fieldLabel.setStyle('display','none');
		this.fieldLabel.FadeFx.start('0');
 
	},
 
	showLabel:function(){
		if(this.fieldElement.value != ''){
			//has text
 
		}else{
			//empty
			//this.fieldLabel.setStyle('display',this.fieldLabel.retrieve('display_original'));
			this.fieldLabel.FadeFx.start('1');
		}
 
	}
});

var DynamicSlideshow = new Class({
	/* ajax slideshow */
	Implements: [Options,Events, Chain], 						  
 
	/* menu options. don't put a comma after the last option! */
	options: {
		/* which viewport to use */
		viewPort:null,
		/* delay in ms */
		slideDelay: 3000,
		/* transition length in ms */
		slideTransitionLength: 1000,
		/* delay at start? */
		startDelay: 0,
		/* json array of images to get 
			in the form [ {'file': 'fileName.jpg', 'link':'URL'}, { ... } ]
		*/
		imgArray:null
 
 
	}, 
 
	log: function(){
		return false;
		//console.log.apply(console, arguments);
 
	},
	/* this function runs whenever a new instance of this class is made. */
	initialize: function(options){ 
 
		this.setOptions(options);
 
		if(!this.options.viewPort || !this.options.imgArray) return false;
 
		//this.log('this.options.imgArray=',this.options.imgArray);
 
		this.options.viewPort = document.getElement(this.options.viewPort);
 
		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){
			defaultImg.setStyle('z-index',1);
			this.slides[0] = defaultImg;
			this.options.imgArray.unshift('');
 
		}
 
		this.totalImg =  this.options.imgArray.length;
 
		/* convenience object */
		this.Nav = {};
		/* all nav links */
		this.Nav.StatusLinks = new Array();
		this.Nav.Container = new Element('div',{'id':'home-slideshow-nav'});
		//var navLinkWidth = 35;
		//this.Nav.Container.setStyle('width', this.options.imgArray.length * navLinkWidth	);
 
		/* build nav */
		this.options.imgArray.each(
						function(item, index, array){
							/* item is a json obj */
 
							/* status elements displayed inline, so store backwards */
							var css = '';
 
							if(index==0){
								/* first */
								css += 'active';
							}
							var status = new Element('a',{'class':css,'href':'javascript:','text':index+1});
							status.fade('show');
							status.addEvent('click',this.NextSlide.bind(this,{'clickIsFromUser':true,'index':index}) );
 
							this.Nav.StatusLinks.include(status);
							this.Nav.Container.grab(status,'bottom');
 
						},this
					);
 		
 		
 		
 		
		/* add mouse handler */
		this.Nav.Container.addEvent('mouseenter',function(){clearInterval(this.periodID)}.bind(this));
		this.Nav.Container.addEvent('mouseleave',function(){this.StartPeriodical.delay(this.options.startDelay, this, this.delayms);}.bind(this));
 
 		/* position */
 		this.Nav.Container.setStyle('position','absolute');
		/* hide nav */
		this.Nav.Container.setStyle('opacity',0);
		/* insert nav into DOM */
		this.options.viewPort.getParent().grab(this.Nav.Container);
		/* store original height */
		var originalHeight = this.Nav.Container.getStyle('height');
		/* collapse */
		this.Nav.Container.setStyle('height',0);
 		/* reposition */
 		this.Nav.Container.setStyle('position','relative');
		
		/* expand and fade in */
		this.Nav.Container.morph({
			'opacity' : 1,
			'height' : originalHeight
			});
		
		/* fade in */
		//this.Nav.Container.fade();
 
		this.StartPeriodical.delay(this.options.startDelay, this, this.delayms);
	},
 
	NextSlide:function(params){
		/* boolean isNext determines if moving forwards or back */
 
		var isNext = params['isNext'];
		this.clickIsFromUser = params['clickIsFromUser'];
 
		/* clear timer */
		if(this.clickIsFromUser) {
			//this.log('CLEAR TIMEOUT',this.periodID);
			clearTimeout(this.periodID);
			if(params.index != this.currentImg){
				this.nextImg = params.index;
			}else{
				return false;
			}
		}else{
			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){
					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 */
			this.LoadImg({'img':this.options.imgArray[this.nextImg]});
		}
 
	},
 
 
 
	LoadImg:function(params){
		/* loads image via HTTP */
 
 
		this.tempImg = '';
		this.tempImg = new Asset.image(params.img['file'],{'onload':function(){this.LoadImgSuccess(params)}.bind(this)});
	},
 
 
 
	LoadImgSuccess:function(params){
		/* create wrapper element 
		wrapper will be DIV for non-links and A for links
		*/
		//this.log('params=',params);
		var elType = 'div';
		var elParams = {'class':'slide'};
		if(params.img['link'] != null){
			/* has link */
			//this.log('params.img[link]=',params.img['link']);
			elType = 'a';
			elParams = Object.merge(elParams, {'href':params.img['link']});
		}else{
 
		}
		var wrapper = new Element(elType,elParams);
		wrapper.fade('hide');
		/* set bg */
		wrapper.setStyle('z-index',this.nextImg);
		wrapper.setStyle('background-image','url("'+this.tempImg.getProperty('src')+'")');
		/* insert */
		this.options.viewPort.grab(wrapper);
 
		this.slides[this.nextImg] = wrapper;
 
		/* fadein */
		this.TransitionSlide();
 
	},
 
 
 
	TransitionSlide:function(){
		/* actual fade transition */
		/* reset all z-index */
		this.slides.each(
						function(item, index, array){
							//item.setStyle('z-index',index);
						},this
					);
 
		var fadeOutCurrSlide;
		var thisSlide = this.slides[this.currentImg];
		var nextSlide = this.slides[this.nextImg];
 
		/* deactivate current nav link */
		this.Nav.StatusLinks[this.currentImg].removeClass('active');
		/* active next link */
		this.Nav.StatusLinks[this.nextImg].addClass('active');
 
 
		if(thisSlide) {
 
			if(!thisSlide.transFx){
				/* for user interaction */
				thisSlide.transFx = new Fx.Tween(thisSlide,{property: 'opacity','duration':this.options.slideTransitionLength,'link':'cancel'});
 
			}
 
			//thisSlide.setStyle('z-index',99);
 		}
 	
//		if(nextSlide){
//			/* move in front */
//			nextSlide.setStyle('z-index',100);
//		}
		/* move behind */
		//thisSlide.setStyle('z-index',99);
 
		if(nextSlide) {
			if(!nextSlide.transFx){
				nextSlide.transFx = new Fx.Tween(nextSlide,{property: 'opacity','duration':this.options.slideTransitionLength,'link':'cancel'});
			}
 			
 			if(this.clickIsFromUser){
 				/* hide */
 				//thisSlide.transFx.set(0);
 				/* start at 0.25 */
 				//nextSlide.transFx.set(0.25);
 				/* speed up */
 				nextSlide.transFx.setOptions({'duration':'short','link':'cancel'});
 				thisSlide.transFx.setOptions({'duration':'short','link':'cancel'});
 			}else{
 				nextSlide.transFx.setOptions({'duration':this.options.slideTransitionLength,'link':'cancel'});
 				thisSlide.transFx.setOptions({'duration':this.options.slideTransitionLength,'link':'cancel'});
 				//thisSlide.transFx.start(0);
 			}
 			
 			
			/* fade in */
			thisSlide.transFx.start(0);
			nextSlide.transFx.start(1);

 			
		}
 
		/* moved here since it needs to happen instantly */
		this.currentImg = this.nextImg;
	},
 
	StartPeriodical:function(delayms){
		clearTimeout(this.periodID);
		this.periodID = function(){this.NextSlide({'isNext':true,'clickIsFromUser':false})}.bind(this).periodical(delayms);
	}
 
 
});


var FieldFocusCss = new Class({
	/* focus a field, add css to an element */
	Implements: [Options,Events, Chain], 						  

	options: {
		/* form field (css selector) */
		field : '',
		/* the target element (css selector) */
		target : '',
		/* css to add */
		css : ''
	}, 
	
	log: function(){
		return false;
		//if('console' in window && 'log' in window.console) console.log.apply(console, arguments);
	},
	
	initialize: function(options){ 
		this.setOptions(options);
		
		/* the field element */
		this.customElement = document.getElement(this.options.field);
		
		this.targetElement = document.getElement(this.options.target);
		
		if(this.customElement && this.targetElement){
			
			/* on focus */
			this.customElement.addEvent('focus',this.toggleCss.bind(this,{'focus':true}));
			/* on blur */
			var toggleCssBound = this.toggleCss.bind(this,{'focus':false});
			this.customElement.addEvents({'blur':toggleCssBound,'change':toggleCssBound});
			
			this.customElement.fireEvent('blur');
		}
	},
/*
	called when using document.id with this class as parameter
	*/
	toElement : function (){
		return this.customElement;
	},
	
	/*
		
	params['focus'] (bool) : whether to toggle on or off
	*/
	toggleCss : function (params){
		if(params.focus || (this.customElement.get('value')!='') ) {
			this.targetElement.addClass(this.options.css);
		}else{
			this.targetElement.removeClass(this.options.css);		
		}
	}	
});

function logoToolTip(){
	/* Hover effect for Logo link */
	var logoLink = document.id('atm-link');
	
	/* the tooltip DIV */
	var toolTip = document.id('atm-info');
	toolTip.setStyles({'opacity':0,'right':'0px'});
	
	if(Browser.safari || Browser.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;
		/* clear timer */
		if(this.timeoutID!==undefined) clearTimeout(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) clearTimeout(this.timeoutID);
	}
	
	logoLink.addEvent('mouseenter', showTooltip.bind(tooltipMorph));
	logoLink.addEvent('mouseleave', startHideTooltipTimer.bind(tooltipMorph));
	
	toolTip.addEvent('mouseenter', clearTimer.bind(tooltipMorph));
	toolTip.addEvent('mouseleave', startHideTooltipTimer.bind(tooltipMorph));
	
}

/* Test for position:fixed support */
Modernizr.addTest('positionfixed', function () {
    var test    = document.createElement('div'),
        control = test.cloneNode(false),
        fake = false,
        root = document.body || (function () {
            fake = true;
            return document.documentElement.appendChild(document.createElement('body'));
        }());

    var oldCssText = root.style.cssText;
    root.style.cssText = 'padding:0;margin:0';
    test.style.cssText = 'position:fixed;top:42px'; 
    root.appendChild(test);
    root.appendChild(control);
    
    var ret = test.offsetTop !== control.offsetTop;

    root.removeChild(test);
    root.removeChild(control);
    root.style.cssText = oldCssText;
    
    if (fake) {
        document.documentElement.removeChild(root);
    }

    return ret;
});

