
var AdHandler = Class.create({

    init: function() {
        this.ads = new Array();
		this.ready = false;
		$(window).ready(function() {
			this.placeAll();
			this.ready = true;
		}.bind(this));
    },

	append: function(zone_id, uniq_id) {
		this.ads.push({'zone_id': zone_id, 'uniq_id': uniq_id});
		if (this.ready) {
			this.placeAll();
		} 
	},

	placeAll: function() {
		this.place();
	},

    place: function() {
		this.actual = this.ads.pop();
        this.oldFunction = document.write;
        document.write = this.documentWrite.bind(this);
		
        $.ajax({
        	url: this.getUrl(),
        	dataType: "script",
        	async: false,
        	success: function(js){if(jQuery.browser.safari){eval(js);}}
        });
    },

    documentWrite: function(text) {
		$('#advertise_' + this.actual['uniq_id']).replaceWith(text);
		document.write = this.oldFunction;
		if (this.ads.length > 0) this.placeAll();
    },

    getUrl: function() {
        var m3_u = (location.protocol=='https:'?'https://ads.mikekoedinger.com/www/delivery/ajs.php':'http://ads.mikekoedinger.com/www/delivery/ajs.php');
        var m3_r = Math.floor(Math.random()*99999999999);
        if (!document.MAX_used) document.MAX_used = ',';

        url = m3_u;
        url += '?zoneid=' + this.actual['zone_id'];
        url += '&amp;cb=' + m3_r;
        if (document.MAX_used != ',') url += '&amp;exclude=' + document.MAX_used;
        url += '&amp;loc=' + escape(window.location);
        if (document.referrer) url += '&amp;referer=' + escape(document.referrer);
        if (document.context) url += '&context=' + escape(document.context);
        if (document.mmm_fo) url += '&amp;mmm_fo=1';

        return url;
    }

});

