document.addEvent('domready', function(){
	Element.behaviors.filterNow();
	$$('html')[0].removeClass('not-ready').addClass('ready').removeClass('no-js').addClass('js');
});

document.addEvent('load', function(){
	$$('html')[0].removeClass('loading').addClass('loaded');
});

// global extensions
SlideShow.addTransition('blinkFade', function(data){
	data.previous.setStyle('display', 'none');
	data.next.fade('hide').set('tween', {
		duration: data.duration
	}).fade('in');
});

(function(behaviors){

behaviors.tabs = function(){
	var self = this;

	var navItems = this.getElements('.tabs-nav li');
		slideshow = new SlideShow(this.getElement('.tabs-panels'), {
			duration: 10,
			transition: 'blinkFade'
		});

	navItems.each(function(item, index){
		var anchor = item.getElement('a');
		item.addEvent('click', function(event){
			slideshow.show(index);
		});
		
		anchor.addEvent('click', function(event){
			event.preventDefault();
		});
		
		// any links that have the same href as the tab will open the tab
		self.getElements('a[href=' + anchor.get('href') + ']').addEvent('click', function(){
			slideshow.show(index);
		});
		
	});

	slideshow.addEvent('show', function(data){
		navItems[data.previous.index].removeClass('active');
		navItems[data.next.index].addClass('active');
	});

	navItems[0].addClass('active');

	var showThisIndex = 0;
	var linkedTab = navItems.filter('[href='+document.location.hash+'] ! li');
	if (linkedTab.length) showThisIndex = navItems.indexOf(linkedTab[0]);
	navItems[showThisIndex].fireEvent('click');

	// links

};

behaviors.accordion = function(){
	var selectors = this.get('data-accordion-selectors').split(',');
	new Fx.Accordion(this.getElements(selectors[0]), this.getElements(selectors[1]), {
		returnHeightToAuto: true,
		initialDisplayFx: false,
		onActive: function(toggler){ toggler.addClass('expanded'); },
		onBackground: function(toggler){ toggler.removeClass('expanded'); }
	});
	this.getElement(selectors[1]).setStyle('height', 'auto');
};


behaviors.sliders = function(){
	var relay = this.get('data-sliders-selector'),
		handler = function(event, target){
			var panel = target.retrieve('panel');
			if (!panel) {
				panel = target.getNext();
				target.store('panel', panel);
			}

			var open = panel.getSize().y != 0;
			panel.morph({
				height: open ? 0 : panel.getScrollSize().y,
				opacity: open ? 0 : 1
			});

			panel.store('open', open ? false : true);
			target[(open ? 'remove' : 'add') + 'Class']('expanded')
		};

	this.addEvent('click:relay(' + relay + ')', handler)
};

behaviors.observe = function(){
	var element = this,
		query = '',
		results = document.id('finder-results'),
		update = function(){
			new Request.JSONP({
				url: '/results.js',
				data: element.toQueryString()
			}).send();
		};

	behaviors.observeCallback = function(json){
		results.set('text', json.results);
	};

	new FormObserver(this)
		.observe(this.get('data-observe').split(' '))
		.addEvents({
			change: update,
			click: update
		});
};

behaviors.sortable = function(){
	new HtmlTable(this, {
		sortable: true,
		classZebra: 'rowoff',
		zebra: true,
		onSort: function(){
			this.updateZebras();
		}
	});
};

behaviors.carousel = function(){
	var slideshow = new SlideShow(this.getElement('.slides'),{
			autoplay: true,
			delay: 5000
		}),
		navs = this.getElements('.nav > span');

	// transition logic
	slideshow.getIndex = function(){ return slideshow.slides.indexOf(slideshow.current) };

	navs[0].addEvent('click', function(){
		var transition = (slideshow.getIndex() == 0) ? 'blindLeft' : 'pushRight';
		slideshow.show('previous', {transition: transition});
	});
	
	navs[1].addEvent('click', function(){
		var transition = (slideshow.getIndex() == slideshow.slides.length - 1) ? 'blindRight' : 'pushLeft';
		slideshow.show('next', {transition: transition});
	});
	
	// indicators
	var indicator = new Element('div.indicators')
		indicators = [];
	(slideshow.slides.length).times(function(i){
		indicators.push(new Element('i').setStyle('opacity', (i == 0) ? 1 : 0.5).inject(indicator));
	});
	indicator.inject(this);
	
	slideshow.addEvent('show', function(data){
		indicators[data.previous.index].fade(0.5);
		indicators[data.next.index].fade(1);
	});
	
	document.id(slideshow).addEvents({
		mouseenter: function(){
			slideshow.pause();
		},
		mouseleave: function(){
			slideshow.play();
		}
	});	
};

behaviors['detail-toggles'] = function(){
	var toggles = this.getElements('a.toggle'),
		details = this.getElements('.section-detail div.detail');
	
	toggles.each(function(toggle, index){
		toggle.addEvent('click', function(event){
			event.stop()
			details[index].toggleClass('hidden');
			toggle.toggleClass('toggled');
		});
	});
}

behaviors['tool-filters'] = function(){
	var selects = this.getElements('select');
	selects.each(function(select, index){
		var tools = select.getParent().getElements('.tool');
		select.addEvent('change', function(){
			var value = select.value;
			if (value){
				tools.addClass('hidden');
				value.split(',').each(function(i){
					tools[i].removeClass('hidden');
				});
				return;
			}
			tools.removeClass('hidden');
		}).fireEvent('change');
	});
}

behaviors.corners = function(){
	var position = this.getStyle('position');
	if (position != 'absolute') this.setStyle('position', 'relative')
	new Element('i.corner.top-left').inject(this);
	new Element('i.corner.top-right').inject(this);
};

behaviors.bottomcorners = function(){
	var position = this.getStyle('position');
	if (position != 'absolute') this.setStyle('position', 'relative')
	new Element('i.corner.bottom-left').inject(this);
	new Element('i.corner.bottom-right').inject(this);
};

behaviors.searchbox = function(){
	var position = this.getStyle('position');
	new Element('i.searchbox.top-left').inject(this);
	new Element('i.searchbox.top-left').inject(this);
};


behaviors.modal = (function(){

	// objects in the modal behavior
	var req = new Request.HTML,
		container,
		close,
		background;

	// don't want to inject until dom is written
	document.addEvent('domready', function(){

		// create and inject elements
		container = new Element('div', {
			id: 'modal-container',
			styles: {
				display: 'none'
			}
		}).inject(document.body);
		
		background = new Element('images', {
			src: '/Atmel/img/interface/overlay/white.png',
			id: 'modal-background',
			styles: {
				display: 'none'
			},
			move: {
				onComplete: function(){
					// when the background images finishes its
					// animation, reposition the other elements
					setTimeout(function(){
						close.position({
							relativeTo: background,
							position: 'upperRight',
							offset: {
								x: -40,
								y: 10
							}
						}).setStyle('display', 'block');

						container.position({
							relativeTo: background,
							position: 'center'
						}).setStyle('display', 'block');
					}, 1)
				}
			}
		}).inject(document.body);
		
		close = new Element('div', {
			id: 'modal-close',
			styles: {
				display: 'none'
			},
			events: {
				// close everything out when this is clicked
				click: function(){
					background.setStyle('display', 'none');
					container.setStyle('display', 'none').empty();
					this.setStyle('display', 'none');
				}
			}
		}).inject(document.body);
	});

	return function(){
		this.addEvent('click', function(event){
			event.stop();
			req.cancel();
			
			background.setStyles({
				height: 10,
				width: 10,
				display: 'inline'
			}).position({
				relativeTo: this,
				position: 'center'
			}).morph({
				width: 936,
				height: 366
			}).move({
				relativeTo: document.body,
				position: 'center',
				offset: {
					x: -463,
					y: -317
				}
			});

			// request the url of the clicked element
			req.setOptions({
				url: this.get('href'),
				method: 'get',
				update: container
			}).send();
			
		});
	};

}());

})(Element.behaviors);
