var Sponsors = Class.create({
	script_location: 'http://websites.stack.nl/~theta/sponsor_banner/',

	initialize: function() {
		// Request all sponsor data we need on the page from the server
		this.requestSponsorData();
		
		// Make all sponsor links open in new windows
		$$('.sponsor_link').each(function(link) {
			link.target = '_blank';
		});
	},

	processSponsorData: function(transport) {
		// Populate the sponsor items

		this.sponsor_data = $H(transport.responseJSON);

		// Prefetch all images to be used in the rotator
		this.sponsor_data.each(function(type) {
			type[1].each(function(sponsor) {
				var logo_name = sponsor['logo'];
				sponsor['logo'] = new Image();
				sponsor['logo'].src = this.script_location + 'sponsor_images/' + logo_name;
			}.bind(this));
		}.bind(this));

		// Start the sponsor rotator
		this.rotateSponsors();
		new PeriodicalExecuter(this.rotateSponsors.bind(this), 10);
	},

	requestSponsorData: function() {
		// Get all sponsor images in the page
		var sponsors = $$('.sponsor');
		var sponsor_types = $A();

		// Get types of the sponsor images on the page
		sponsors.each(function(sponsor) {
			var sponsor_type = sponsor.id.split('_').pop();
			sponsor_types.push(sponsor_type);
		});

		// Request the sponsor data from the server
		new Ajax.Request(
			'sponsor_banner/sponsors.php?types=' + sponsor_types.join(','),
			{
				method: 'get',
				onSuccess: this.processSponsorData.bind(this)
			}
		);
	},

	rotateSponsors: function() {
		this.sponsor_data.each(function(type) {
			var sponsor_type = type[0];
			var sponsor_amount = type[1].length;
			var sponsor_selected = type[1][Math.floor(Math.random()*sponsor_amount)];

			// If a different sponsor comes out of the random process, update the sponsor in the page
			var sponsor_element = $('sponsor_' + sponsor_type);
			var sponsor_link = $('sponsor_link_' + sponsor_type);

			// Only change the logo if a new sponsor has been selected
			if(sponsor_element.title != sponsor_selected.name) {
				// Fade the old logo out
				new Effect.Fade(sponsor_element, 
								{
									duration: 3,
									afterFinish: function(obj) {
										// Replace the logo
										sponsor_element.src = sponsor_selected.logo.src;
										sponsor_element.title = sponsor_selected.name;
										sponsor_link.href = sponsor_selected.url;						
										
										// Fade the logo back in
										new Effect.Appear(obj.element,
											{
												duration: 3
											});
									}
								});
			}
		});
	}
});

var sponsors = new Sponsors();