var OverlayAd = Class.create({
	initialize: function(ad, width, height, timerLength) {
		this.ad = ad;
		this.adWidth = width;
		this.adHeight = height;
		this.timerIndex = timerLength;
		this.adPadding = 10;
		this.titlebarHeight = 30;
		
		// Build overlay elements
		this.overlay = new Element("div", {"class": "overlay"});
		this.holder = new Element("div", {"class": "overlay-holder"});
		this.titlebar = new Element("div", {"class": "overlay-titlebar"});
		this.timer = new Element("div", {"class": "overlay-timer"}).update("This advertisement will close automatically in " + this.timerIndex + " seconds.");
		this.closeButton = new Element("button", {"class": "overlay-close"}).update("Close");
		
		// Set styles
		this.overlay.setStyle({position: "absolute", top: "0px", left: "0px", width: "100%", height: document.viewport.getHeight() + "px", backgroundColor: "#000", opacity: 0.75, zIndex: "1000"});
		this.holder.setStyle({position: "absolute", top: "50%", left: "50%", width: this.adWidth + "px", height: (this.adHeight + this.titlebarHeight) + "px", marginTop: "-" + ((this.adHeight + this.titlebarHeight) / 2) + "px", marginLeft: "-" + (this.adWidth / 2) + "px", padding: this.adPadding + "px", backgroundColor: "#fff", zIndex: "1001"});
		this.titlebar.setStyle({width: this.adWidth + "px", height: this.titlebarHeight + "px", paddingTop: "5px", overflow: "hidden"});
		this.timer.setStyle({cssFloat: "left"});
		this.closeButton.setStyle({cssFloat: "right"});
		
		// Append to document
		this.titlebar.appendChild(this.timer);
		this.titlebar.appendChild(this.closeButton);
		this.holder.appendChild(this.ad.remove());
		this.holder.appendChild(this.titlebar);
		document.body.appendChild(this.overlay);
		document.body.appendChild(this.holder);
		
		// Assign event handlers
		this.timerExecuter = new PeriodicalExecuter(this.updatetimer.bind(this), 1);
		this.closeButton.observe("click", function(){this.hide();}.bind(this));
		
		// Done, show it
		this.overlay.show();
		this.holder.show();
		this.ad.show();
	},
	updatetimer: function(){
		if (this.timerIndex > 1) {
			this.timerIndex--;
			this.timer.update("This advertisement will close automatically in " + this.timerIndex + " seconds.");
		} else {
			this.hide();
		}
	},
	show: function(){
		this.overlay.show();
	},
	hide: function(){
		this.timerExecuter.stop();
		this.holder.hide();
		this.overlay.hide();
	}
});
