var Goodinson = {
	delay1: 500,
	delay2: 2000,
	active: null,
	timer1: null,
	timer2: null,
	activeForm: null,
	activeButton: null,
	
	initialize: function()
	{
		var projects = $('main').getElements('div[class=project]');
		for (var i=0; i<projects.length; i++)
		{
			projects[i].addEvent('mouseenter', Goodinson.onMouseOver.bindWithEvent(projects[i]));
			projects[i].addEvent('mouseleave', Goodinson.stopSlideshow.bindWithEvent(projects[i]));
		}
	},
	
	onMouseOver: function()
	{
		this.addClass('active');
		if (!this.images)
		{
			this.images = $('images' + (this.id.substr(this.id.indexOf('-')))).getElements('[class=item]');
		}
		this.image = 0;
		Goodinson.active = this;
		
		if (Goodinson.timer1)
		{
			clearTimeout(Goodinson.timer1);
		}
		Goodinson.timer1 = setTimeout('Goodinson.startSlideShow()', Goodinson.delay1);
	},
	
	startSlideShow: function()
	{
		Goodinson.onTimer(); // start immediately
		if (Goodinson.timer2)
		{
			clearInterval(Goodinson.timer2);
		}
		Goodinson.timer2 = setInterval('Goodinson.onTimer()', Goodinson.delay2);
	},
	
	onTimer: function()
	{
		Goodinson.nextImage(Goodinson.active);
	},
	
	pauseSlideshow: function()
	{
		// stop slideshow
		Goodinson.active.fire('mouseleave');
	},
	
	stopSlideshow: function()
	{
		this.removeClass('active');
		Goodinson.active = null;
		clearInterval(Goodinson.timer);
		Goodinson.nextImage(this, 0);
	},
	
	nextImage: function(project, force)
	{
		if (!project) {
			// stop slideshow
			clearInterval(Goodinson.timer);
			return;
		}
		
		var now = project.image;
		var total = project.images.length;
		var next = (force != null ? force : ((now+1 == total) ? 0: now+1));
		project.image = next;
		
		if (now == next) 
		{
			return;
		}
		
		// fade out active image
		fx1 = new Fx.Style(project.images[now], 'opacity');
		fx1.start(1, 0);
		
		// fade in next image
		fx2 = new Fx.Style(project.images[next], 'opacity');
		fx2.start(0, 1);
	},
	
	submitTo: function(dept)
	{
		Goodinson.activeForm = $('form-'+dept);
		Goodinson.activeButton = $('submit-'+dept);
		Goodinson.activeButton.innerHTML = 'Please wait...';
		new Ajax(Goodinson.activeForm.action, {method: 'post', update:$('contact-'+dept), data: Goodinson.activeForm.toQueryString(), onComplete:Goodinson.onSubmit }).request();
	},
	
	onSubmit: function()
	{
		Goodinson.activeButton.innerHTML = 'Submit &raquo;';
		Goodinson.autoFocus(Goodinson.activeForm);
	},
	
	autoFocus: function(form)
	{
		var el = form.elements;
		for (var i=0; i<el.length; i++)
		{
			if (el[i].value == '' && (el[i].type == 'text' || el[i].type == 'textarea'))
			{
				el[i].focus();
				break;
			}
		}
	}
};
