
var WorkPage = Class.create ({
	
	initialize: function()
	{
		this.selected = false;		
		this.links = new Array();
		this.images = new Array();
		
		this.start();
	},
	
	start: function()
	{
		
		this.currentElement = $('workTopImage');
		this.nextElement = new Element ('img');
		
		this.currentElement.ancestors()[0].setStyle({position: 'relative'});
		this.currentElement.setStyle({position: 'absolute'});
		this.nextElement.setStyle({position: 'absolute', zIndex: 100}).setOpacity(0);
		
		
		this.currentElement.ancestors()[0].appendChild(this.nextElement);
		
		this.build();
	},
	
	build: function()
	{
		$$('a').each (function(link) {
			if (link.rel.match('project'))
			{
				if (this.selected == false)
				{
					this.selected = link.name;
				}
				
				link.observe ('click', this.linkClicked.bindAsEventListener(this, link.name));
				link.observe ('mouseout', this.markSelected.bindAsEventListener(this));
				link.observe ('mouseover', this.hover.bindAsEventListener(this, link.name));
				
				i = this.images.length;
				this.images[i] = new Image(773,296);
				this.images[i].src = link.href;

				this.links[this.links.length] = link;
			}
		}.bind(this));
		
		this.markSelected();
	},
	
	linkClicked:function(ev, name)
	{
		ev.stop();
		
		this.selected = name;
		this.markSelected();
		
		element = ev.element();
		element = element.href && !element.src ? element : element.ancestors()[0];
		
		this.showNext(element.href, element.title);		
	},
	
	markSelected: function()
	{
		for (var i = 0; i<this.links.length; i++)
		{
			if (this.links[i].name != this.selected)
			{
				this.links[i].removeClassName('selected');
			}
			else
			{
				this.links[i].addClassName('selected');
			}
		}
	},
	
	hover: function(ev)
	{
		element = ev.element();
		element = element.href ? element : element.ancestors()[0];
		
		for (var i = 0; i<this.links.length; i++)
		{
			if (this.links[i].name == element.name)
			{
				this.links[i].addClassName('selected');
			}
		}
		
	},
	
	showNext: function(src, alt)
	{
		
		this.currentElement.alt = alt;
		this.nextElement.alt = alt;
		
		this.nextElement.src = src;
		
		Effect.Appear(this.nextElement, {
			duration: 0.3,
			afterFinish: this.updateElements.bind(this)
			});
	},
	
	updateElements: function()
	{
		this.currentElement.src = this.nextElement.src;
		this.nextElement.setOpacity(0);
	}
});

document.observe ('dom:loaded', function() {
	if ($('work'))
	{
		workPage = new WorkPage();
	}
});
