if (!window.wxtools) wxtools = {};

wxtools.MapAdController_GeoServer = 'http://geotarget.weather.com/geotargetserver/spatial?';
wxtools.MapAdController_targetLevels = [
	{ name:'country', level:1 },
	{ name:'state', level:6 },
	{ name:'dma', level:8 },
	{ name:'city', level:11 },
	{ name:'zipcode', level:13 }
];
wxtools.MapAdController_states = [
	'Waiting required ad refresh period',
	'Waiting for user action',
	'Map in use',
	'Updating GeoTargets',
	'Loading New Ads'
];

wxtools.MapAdController_instances = {};
wxtools.MapAdController_gotTargets = function(id, targets) { wxtools.MapAdController_instances[id].setTargets(targets); };

wxtools.MapAdController = function(map, adinfo, adDelay, actionDelay) {
	this.id = Math.floor(10000 * Math.random());
	this.adinfo = adinfo;
	
	wxtools.MapAdController_instances[this.id] = this;
	
	this.map = map;
	map.addListener(this);
	
	this.adDelayID = null;
	this.actionDelayID = null;
	this.adDelay = (adDelay!=null)?adDelay:500;
	this.actionDelay = (actionDelay!=null)?actionDelay:500;
	
	this.mode = 'geo';
	this.targetsCurrent = false;
	this.verticalCurrent = true;
	
	this.currentState = 4;
	this.advance();
	
	map.addListener(this);
	
	EventBroadcaster.initialize(this);
};

wxtools.MapAdController.prototype = {
	// EventBroadcaster stuff
	/******************************************************************************************************************/
	broadcastMessage:function() {},
	addListener:function() {},
	removeListener:function() {},
	/******************************************************************************************************************/
	
	// Delay getter/setters
	/******************************************************************************************************************/
	setAdDelay:function(value) { this.adDelay = value; },
	getAdDelay:function() { return this.adDelay; },
	setActionDelay:function(value) { this.actionDelay = value; },
	getActionDelay:function() { return this.actionDelay; },
	/******************************************************************************************************************/
	
	// Event listeners for the map object
	/******************************************************************************************************************/
	onPan:function(latitude, longitude) {
		this.targetsCurrent = false;
		this.advance();
	},
	onZoom:function(level) { this.advance(); },
	onSetLayer:function(type, layer) { this.advance(); },
	onSetTransparency:function(transparency) { this.advance(); },
	onPopUp:function(message) { this.advance(); },
	onAnimate:function() { this.advance(); },
	stopAnimate:function() { this.advance(); },
	animateStepBackward:function() { this.advance(); },
	animateStepForward:function() { this.advance(); },
	animateOnToStart:function() { this.advance(); },
	animateOnToEnd:function() { this.advance(); },
	onSetPoiLayer:function(poi) {
		if (poi == 'null') {
			this.mode = 'geo';
			this.currentState = 3;
			if (this.actionDelayID != null) {
				clearTimeout(this.actionDelayID);
				this.actionDelayID = null;
			}
			if (this.adDelayID != null) {
				clearTimeout(this.adDelayID);
				this.adDelayID = null;
			}
			this.updateTargeting();
		} else {
			this.mode = 'vertical';
			this.verticalCurrent = false;
			this.advance();
		}
	},
	onPlotArbitraryLayer:function() { this.advance(); },
	/******************************************************************************************************************/
	
	// Manager method for the state machine
	/******************************************************************************************************************/
	advance:function() {
		if (this.mode == 'geo') {
			switch(this.currentState) {
				case 0: // adDelay
					if (this.adDelayID == null) {
						this.currentState++;
						this.broadcastMessage('onStateChange', wxtools.MapAdController_states[this.currentState]);
					}
					break;
				case 1: // waiting
					this.currentState++;
					this.broadcastMessage('onStateChange', wxtools.MapAdController_states[this.currentState]);
					this.setActionTimer();
					break;
				case 2: // actionDelay
					if (this.actionDelayID == null) {
						this.currentState++;
						this.broadcastMessage('onStateChange', wxtools.MapAdController_states[this.currentState]);
						this.updateTargeting();
					} else {
						this.refreshActionTimer();
					}
					break;
				case 3: // targetting
					if (this.targetsCurrent) {
						this.currentState++;
						this.broadcastMessage('onStateChange', wxtools.MapAdController_states[this.currentState]);
						this.loadAds();
					}
					break;
				case 4: // loading
					this.currentState = 0;
					this.broadcastMessage('onStateChange', wxtools.MapAdController_states[this.currentState]);
					this.setAdTimer();
					break;
			}
		} else {
			if (!this.verticalCurrent) {
				this.verticalCurrent = true;
				this.broadcastMessage('onStateChange', wxtools.MapAdController_states[this.currentState]);
				this.loadAds();
			}
		}
	},
	/******************************************************************************************************************/
	
	// state machine timer handle methods
	/******************************************************************************************************************/
	setActionTimer:function() {
		this.actionDelayID = setTimeout('wxtools.MapAdController_instances[\'' + this.id + '\'].clearActionTimer()',this.actionDelay);
	},
	refreshActionTimer:function() {
		clearTimeout(this.actionDelayID);
		this.setActionTimer();
	},
	clearActionTimer:function() {
		this.actionDelayID = null;
		this.advance();
	},
	setAdTimer:function() {
		this.adDelayID = setTimeout('wxtools.MapAdController_instances[\'' + this.id + '\'].clearAdTimer()',this.adDelay);
	},
	clearAdTimer:function() {
		this.adDelayID = null;
		this.advance();
	},
	/******************************************************************************************************************/
	
	// Geotargeting request/response logic
	/******************************************************************************************************************/
	updateTargeting:function() {
		if (!this.targetsCurrent) {
			var head = document.getElementsByTagName('head')[0];
			var script = document.getElementById(this.id + '_targetReq');
			if (script) {
				head.removeChild(script);
				delete script;
			}
			
			var center = this.map.getCenter();
			
			script = document.createElement('script');
			script.id = [this.id,'_targetReq'].join('');
			script.type = 'text/javascript';
			script.src = [wxtools.MapAdController_GeoServer,'lat=',center.latitude,'&long=',center.longitude,'&callback=wxtools.MapAdController_gotTargets&sourceID=',this.id].join('');
			head.appendChild(script);
		} else {
			this.advance();
		}
	},
	setTargets:function(targets) {
		var head = document.getElementsByTagName('head')[0];
		var script = document.getElementById(this.targetID + '_targetReq');
		if (script) {
			head.removeChild(script);
			delete script;
		}
		
		this.targets = targets;
		
		this.broadcastMessage('onNewTargets', this.targets);
		
		this.targetsCurrent = true;
		this.advance();
	},
	/******************************************************************************************************************/
	
	// Ad refresh logic
	/******************************************************************************************************************/
	//buildURL:function(info, token, target) {
	//	return [
	//		info.url,
	//		'adstream_mjx.ads/',
	//		info.host,
	//		info.spoof.replace(token, target),
	//		'/1',
	//		Math.floor(Math.random() * 99999999),
	//		'@%POS%?',
	//		info.query
	//	].join('');
	//},
	setPageVars:function(info, token, target) {
		OAS_spoof = info.spoof.replace(token, target);
		OAS_query = info.query;
	},
	loadAds:function() {
		addata.ord = Math.random()*10000000000000000;
		var geoTarget = '';
		var targetLevel;
		if (addata.geo) {
			addata.geo.cntry = this.targets["country"];
			addata.geo.province = this.targets["state"];
			addata.geo.market = this.targets["dma"];
			addata.geo.city = this.targets["city"];
			addata.geo.postcode = this.targets["zipcode"];
			
			constructOASAdVars();
			//geoTarget = OAS_spoof; // Not sure of this ...
		}
		
		//this.setPageVars(this.adinfo.geo, '\%GEO\%', geoTarget); // Probably this is not required.
		
		this.broadcastMessage('onRefreshAds');
		this.advance();
	}
	/******************************************************************************************************************/
};

var MapAdController = wxtools.MapAdController;

// The Ad Translation code is here!!
// This code converts the standard ad data block into the variables required by an OAS ad server

var OAS_MJX_on = true;
var OAS_url = addata.url;
var OAS_host = addata.site;
var OAS_listpos = addata.positions.join(',');

var OAS_query = [];
var OAS_spoof = [addata.page];
var OAS_sitepage = OAS_host + [addata.page];

constructOASAdVars();

function constructOASAdVars() {
	OAS_query = [];
	OAS_sitepage = OAS_host + [addata.page];
	
	if (addata.geo) {
	    OAS_query.push('?COUNTRY=',addata.geo.cntry);
	    OAS_query.push('&ST=',addata.geo.province);
	    OAS_query.push('&DEPT=',addata.geo.market);
	    OAS_query.push('&CITY=',addata.geo.city);
	    OAS_query.push('&PCODE=',addata.geo.postcode);
	}
	
	if (addata.interest) OAS_query.push('&interest=',addata.interest);
	if (addata.severe && (addata.severe == 'Y')) OAS_query.push('&severe=',addata.severe);
	if (addata.wx) {
	    if (addata.wx.temp) OAS_query.push('&temp=',addata.wx.temp);
	    if (addata.wx.dew) OAS_query.push('&dew=',addata.wx.dew);
	    if (addata.wx.temph) OAS_query.push('&temph1=',addata.wx.temph[0],'&temph2=',addata.wx.temph[1],'&temph3=',addata.wx.temph[2]);
	    if (addata.wx.templ) OAS_query.push('&templ1=',addata.wx.templ[0],'&templ2=',addata.wx.templ[1],'&templ3=',addata.wx.templ[2]);
	    if (addata.wx.cond) OAS_query.push('&cond=',addata.wx.cond);
	    if (addata.wx.fcond) OAS_query.push('&fcond1=',addata.wx.fcond[0],'&fcond2=',addata.wx.fcond[1],'&fcond3=',addata.wx.fcond[2]);
	    if (addata.wx.wind) OAS_query.push('&wind=',addata.wx.wind);
	    if (addata.wx.humid) OAS_query.push('&humid=',addata.wx.humid);
	    if (addata.wx.uv) OAS_query.push('&uv=',addata.wx.uv);
	    if (addata.wx.pollen) OAS_query.push('&pollen=',addata.wx.pollen);
	}
	OAS_query = OAS_query.join('').substr(1);
}

	var adinfo = {
		geo:{ url:OAS_url, host:OAS_host, spoof:OAS_sitepage, query:OAS_query },
		vertical:{ url:OAS_url, host:OAS_host, spoof:OAS_sitepage, query:OAS_query }
	};