var MEIB_Ads = new Class({
	Implements: Options,
	options: {
		cookieName: 'MEIB_viewedAds',
		cookieExpiry: true // set to true if you want it to expire in now()+1 year, otherwise it will be a session cookie
	},
	cookie: false,
	viewedAds: [],
	
	initialize: function(ads) {
		this.ads = ads;
		
		// try to get an ad as a check to see if there are ads and they arent all expired
		// if it rerurns false disable the openAd function by making it a dummy function
		var ad = this.getAd();
		if(!ad) {
			this.openAd = function(){ return false; };
			return;
		}
		
		if(arguments.length==2) {
			this.setOptions(arguments[1]);
		}
		this.getCookie();
		if(this.cookie) {
			this.viewedAds = this.cookie.split('=')[1].split(',');
		}
	},
	
	openAd: function() {
		var ad = this.getAd();
		if(ad) {
			this.viewedAds.push(ad.id);
			this.setCookie();
			window.location = ad.url;
		}else{
			// Clear the cookie so the cycle begins again
			this.reset();
			this.openAd();
		}
	},
	
	getAd: function() {
		var ad = false;
		for(var i=0,c=this.ads.length;i<c;i++) {
			// If the ad isnt in the cookie of past viewed ads
			// and it hasn't passed the expiry date
			
			if(!ad && this.viewedAds.indexOf(this.ads[i].id)==-1 && !this.hasExpired(this.ads[i].expires)) {
				ad = this.ads[i];
			}
		}
		return ad;
	},
	
	hasExpired: function(dateString) {
		//var parts = dateString.split('/');
		var now = new Date();
		var then = new Date(dateString);
		return (now > then);
	},
	
	getCookie: function() {
		var cookies = document.cookie.split(/[; ]+/);
		for(var i=0,c=cookies.length; i<c; i++) {
			var name = cookies[i].substring(0,cookies[i].indexOf('='));
			if(name == this.options.cookieName) {
				this.cookie = cookies[i];
				return;
			}
		}
	},
	
	setCookie: function() {
		var expires = '';
		if(this.options.cookieExpiry) {
			d=new Date();
			d.setYear(d.getFullYear() + 1);			
			expires = ";expires=" + d.toGMTString()
		}
		var strCookie = this.options.cookieName + "=" + this.viewedAds + expires + ";path=/";
		document.cookie = strCookie;
	},
	
	reset: function() {
		this.viewedAds = [];
		this.setCookie();
	}

});