window.addEvent('domready', function(){
	var featureBoxes = $$('div.column.animatedFeature');

	if (featureBoxes) {
		featureBoxes.each(function(box){
			box.store('featureCount', box.getElements('div.feature, a.feature').length);
		});

		var animateFeatures = function(){
			featureBoxes.each(function(box){
				if (box.retrieve('featureCount') > 1) {
					var newMargin;
					var feature = box.getElement('.feature');
					var marginTop = feature.getStyle('marginTop').toInt();
					var boxHeight = box.getStyle('height').toInt() + feature.getStyle('marginBottom').toInt();

					if (marginTop / (box.retrieve('featureCount') - 1) <= boxHeight * -1) {
						newMargin = 0;
					} else {
						newMargin = marginTop - boxHeight;
					}

					feature.tween('marginTop', newMargin);
				}
			});
		}

		var animationTimer = animateFeatures.periodical(5000);

		featureBoxes.each(function(box){
			box.addEvents({
				mouseenter: function(){
					box.getElement('.feature').get('tween').pause();
					$clear(animationTimer);
				},
				mouseleave: function(){
					box.getElement('.feature').get('tween').resume();
					animationTimer = animateFeatures.periodical(5000);
				}
			});
		});
	}
});


window.addEvent('domready', function(){

	// homepage feature block
	var homeFeature = $('homeFeature');

	if (homeFeature) {

		var animateTo = function(whichFeature){
			var highestZIndex = 0;
			var thisZIndex = 0;

			featureImages.each(function(el, i){
				var zIndex = el.getStyle('zIndex').toInt();

				if (zIndex > highestZIndex) {
					highestZIndex = zIndex;
				}

				if (i == whichFeature) {
					thisZIndex = zIndex;
				}
			});

			if (highestZIndex > thisZIndex) {
				featureImages[whichFeature].setStyles({
					opacity: 0,
					zIndex: highestZIndex + 1
				}).tween('opacity', 1);
			}

			// advance to next image
			nextFeature = whichFeature;
			if (++nextFeature >= featureTabs.length) nextFeature = 0;
		}

		var animateFeature = function(){
			animateTo(nextFeature);
		}

		// get the images in the feature
		var featureImages = homeFeature.getElements('div');

		// add tab list
		var featureTabList = new Element('ul');
		featureTabList.inject(homeFeature);

		// set the feature to it's "starting" state
		featureImages.each(function(el, i){
			el.setStyle('zIndex', i);

			// add tabs
			var alt = el.getElement('img').get('alt');
			var li = new Element('li', {
				id: 'homeFeatureTab'+alt,
				html: alt,
				events: {
					click: function(e){
						nextFeature = i;
						animateTo(i);
					}
				}
			});

			featureTabList.adopt(li);
		});

		var featureTabs = featureTabList.getElements('li');


		// set the animate to run periodically
		var nextFeature = 0;
		var animationTimer = animateFeature.periodical(5000);

		// stop the animation when the user mouses over
		homeFeature.addEvents({
			mouseenter: function(){
				$clear(animationTimer);
			},
			mouseleave: function(){
				animationTimer = animateFeature.periodical(5000);
			}
		});
	}
});