window.addEvent('domready', function(){
  	var Ads = new Class({
	    initialize: function(url, dest) {
			this.resizeSpeed = 7;
			this.displayTime = 4; //seconds
			


			var jSonRequest = new Json.Remote(url,{
				onComplete: function(ads){
					dest.each(function(item, index){
						this.imageLink = new Element('a').injectInside(item);
						this.image = new Element('img').injectInside(this.imageLink);
						
						this.getAd(ads, item);
						var timer = this.getAd.pass([ads, item], this).periodical(this.displayTime * 1000);
						
					}, this);
				}.bind(this)
			}).send();

		}		
	});
	Ads.implement({
		getAd: function(ads, dest){
			var random = $random(0,ads.length-1);
			var ad = ads[random];
			
			this.preload = new Image();
			this.preload.onload = this.showAd.pass([ad, dest], this);
			this.preload.src = ad.ad_url;
		}
	});
	Ads.implement({
		showAd: function(ad, dest) {
			var ad_url = ad.ad_url;
			var link_url = ad.link_url;
			var title = ad.event_title;
			
			// fade current image
			this.imageLink.setProperty('href', link_url);
			this.image.setProperties({
			    src: ad_url,
			    alt: title
			});
		}
	})
	
	var myAds = new Ads('?script=calendar&parameters=display=ads', $('body').getElements('div[class=ad]'));	
});