var Screen = function(id) {

	var images = [];
	var links = [];
	var captions = [];
	var slideshow = null;
	
	$$('#'+id + ' .images a').each(function(el, i) { 
		links[links.length] = el; 
		if(el.title != "")
			captions[captions.length] = el.title; 
	});
	
	$$('#'+id + ' .images img').each(function(el, i) { 

		images[images.length] = el.src!=''?el.src:el.getProperty('title'); 
		el.removeProperty('title', '');
	});

	
	return {
	
		id: id,
		div: $(id),				
		hide: function() {
		
			this.div.setStyle('display', 'none');
			if(slideshow != null) {
				slideshow.stop();
			}
		},
		
		show: function() {
			this.div.setStyles({display: 'block'});
			$E('.content', this.div).setStyle('opacity', 0);
			new Fx.Style($E('.content', this.div), 'opacity', {duration: 500}).start(1);
			$E('body').setProperty('class', this.id);
			$ES('.images img', this.div).each(function(el, i) {
				el.src = images[i];
			});
			this.highlightCurrent();
		},
		
		startSlideshow: function() {
			if(images.length > 1) {
				if(slideshow == null) {
					slideshow = new Slideshow('#'+this.id+' .images', { height: 493, width: 365, hu: '', images: images, captions: captions, links: links, type: 'push', duration: [900, 2500]});
					slideshow.start();
				} else {
					slideshow.restart();
				}			
			}
		},
				
		highlightCurrent: function() {
			
			$ES('ul#mainnav li a').each( function(el) {		
				if(el.hash == '#'+id) {
					el.getParent().addClass('current');
				}else if(el.href != location.href) {
					el.getParent().removeClass('current');
				}			
			}.bind(this));
		}
	
	}
	

};

var screens = new Hash();
var visibleScreen = null;

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

	$$('.screen').each(function(el, i) {
	
		var fragment = (window.location.hash==""?$E('body').getProperty('class'):window.location.hash.slice(1));
		
		var screen = new Screen(el.id);
		screens.set(el.id, screen);
		if(el.id != fragment) screen.hide();
		else {
			visibleScreen = screen;
			screen.show();
			screen.highlightCurrent();
		}
	});
	

	$$('.screenlink').each(function(el) {
		el.addEvent('click', function(e) {
			$ES('#mainnav li').each(function(n) { n.removeClass('current'); n.removeClass('nav-active');});
			
			if (el.href.lastIndexOf('#') > -1) {
				var screenId = el.href.substr(el.href.lastIndexOf('#')+1);
				var myScreen = screens.get(screenId);
				if(myScreen == null) return;
			}else { return; }
					
			if(visibleScreen == null) visibleScreen = myScreen;
						
			if(visibleScreen != myScreen) {
				visibleScreen.hide();
				visibleScreen = myScreen;	
				visibleScreen.show();
				visibleScreen.startSlideshow();
			}
			visibleScreen.highlightCurrent();

		});
	});
	
	$ES('#mainnav li').each(function(n,i) {
		n.addEvent('mouseover', function() {
			n.addClass('nav-active');
		});
		n.addEvent('mouseout', function() {
			n.removeClass('nav-active');
		});
	});	

	setTimeout(function() {if(visibleScreen != null) { visibleScreen.startSlideshow() }}, 200);

});