

var AVHome = new Class({
	
	active_class: null,
	thumbs_width: 0,
	
	initialize: function() {
		$$(".imagenav")[0].getElements('li a').each(this.addNavEvents.bind(this));
		this.distributeThumbs.apply(this);
		this.setHashClass();
		this.preloadMainImages();
	},
	addNavEvents: function(section, i) {
		section.addEvent('mouseover', this.navMouseOver.bindWithEvent(this, section));
	},
	navMouseOver: function(e, section) {
		this.hideInstructions();
		
		var body = $(document.body);
		var BODY_CLASS_NAME = "home";
		
		body.className = "";
		this.active_class = section.className;
		body.addClass(this.active_class);
		body.addClass(BODY_CLASS_NAME);
		
		//distribute thumbs horizontal space
		
		this.distributeThumbs.apply(this);
		
		
		av_common.hijackLinks();
	},
	setHashClass: function() {
		if(location.hash) {
			var hash = location.hash.substr(1);
			$(document.body).addClass(hash);
		}
		
	},
	checkDisplayTrue: function(item, i) {
		return item.getStyle('display') != 'none';
	},
	distributeThumbs: function() {
		
		var container = $$('.thumbs')[0];
		var thumbs = container.getElements('a').filter(this.checkDisplayTrue);
		var w = container.getSize().x;
		
		this.thumbs_width = Math.floor( w / Math.max(thumbs.length, 1) );
		thumbs.each(this.setThumbsWidth, this);
	},
	setThumbsWidth: function(item, width) {
		item.setStyles({
			margin: "0",
			width: this.thumbs_width
		});
	},
	preloadMainImages: function() {
		
		var arr = [];
		var main_images = ['cycling', 'fitness', 'golf', 'running', 'strength', 'swimming'];
		var bg_url = $$('.main')[0].getStyle('background-image').replace(/^url\(/, '').replace(/\)$/, '');
		var path = bg_url.substr(0, bg_url.lastIndexOf('/') + 1);
		path = (path.indexOf(this.baseURL()) == 0) ? path.substr(this.baseURL().length) : path;
		
		
		main_images.each(function(str) {
			new Asset.image(path + str + ".jpg");
		})
		
		
		
		
	},
	hideInstructions: function() {
		var instructions
		if(instructions = $$('.imagenav-container p')[0]) {
			instructions.tween('opacity', 0);
		}
		
	},
	baseURL: function() {
		var base_url = null;

		if( document.getElementsByTagName ) {
			var elems = document.getElementsByTagName( 'base' );

			if( elems.length ) {
			base_url = elems[ 0 ].href;
			}
		}

		return base_url;
	}
});

document.addEvent("domready", function() {
	new AVHome();
});