// JavaScript Document

/**
* Ad Manager v1.0
* Written by Nelis Elorm Duhadzi
* Base2 Technologies, Ghana
*/

(function () {
	var b2 = window.b2 = function () {
		return new b2.prototype;	
	}
	
	b2.adManager = {
		_uid: 0,
		aduid: 0,
		ads: [],
		snippet: "",
		timeout: 0,
		start: null,
		starttime: null,
		end: null,
		lifespan: null,
		active: null,
		container: ""
	}
	
	b2.adManager.first = function () {
		return this._que[0];
	}
	
	b2.adManager.next = function () {
		return this._que[this.ad.key+1] || this.first();
	}
	
	b2.adManager.previous = function () {
		return this._que[this.ad.key-1] || this.last();
	}
	
	b2.adManager.last = function () {
		return this._que.reverse()[0];
	}
	
	b2.adManager.set = function (a) {
		this.ad = a;	
	}
	
	b2.adManager.init = function () {
		function _f() {
			var ds=new Date(), de=new Date();
			
			this._uid = 0;
			this.uid = "_init"+b2.adManager._uid;
			b2.adManager._uid++;
			
			var k, opt=arguments[0];
			for (k in opt) {
				if (opt[k] && opt.propertyIsEnumerable(k) && k!="uid") {
					this[k] = opt[k];	
				}	
			}
			
			this.ads = [];
			return this;			
		}
		_f.prototype = this;
		return new _f(arguments[0]);
	}
	
	b2.adManager.create = function () {
		var init = this;
		function _f(){
			var k, opt=arguments[0],
			ds=new Date(), de=new Date();
			
			this.uid = "_ad"+init._uid;
			init._uid++;
			
			for (k in opt) {
				if (opt[k] && opt.propertyIsEnumerable(k) && k!="uid") {
					this[k] = opt[k];	
				}	
			}	
			
			ds.setHours(this.starttime.hour);
			ds.setMinutes(this.starttime.minute);
			ds.setSeconds(0);
			de.setHours(ds.getHours()+this.lifespan.hours);	
			de.setMinutes(ds.getMinutes()+this.lifespan.minutes);	
			de.setSeconds(0);
			
			this.start = ds;			
			this.end = de;
			this.timeout = this.timeout*1000;
			this.snippet = unescape(decodeURIComponent(this.snippet));
			
			init.ads.push(this);
			return this;
		}
		_f.prototype = this;
		return new _f(arguments[0]);
	}
	
	b2.adManager.process = function () {
		var o=this;	
		o.que();
		if (!o._que.length) return;
		o.ad = o.ad||o.first();
		
		setTimeout(function () {
			if (!document.getElementById(o.ad.container)) return;
			document.getElementById(o.ad.container).innerHTML = o.ad.snippet;
			o._timeout = o.ad.timeout;
			o.set(o.next());
			o.process();
		}, (o._timeout||0));
	}
	
	b2.adManager.que = function () {
		var i, a=this.ads, o, t, ad, dt=new Date();
		this._que = [];
		
		for (i=0; i<a.length; i+=1) {			
			ad = a[i];
			
			var laps = {
				maximum: Math.abs(ad.end.getTime()-ad.start.getTime()),
				current: Math.abs(dt.getTime()-ad.start.getTime())
			}
			
			if (laps.maximum > laps.current) {
				ad.key = i;
				this._que.push(ad);
			}
		}
	}
	
})();