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

// constant values

wxtools.DynamicOAS_CallFrameURL = '/global/common/adstwo/OASCallFrame.html';
wxtools.DynamicOAS_AdFrameURL = '/global/common/adstwo/OASAdFrame.html';

// A handler class for the individual ad positions
//   this class takes care of all rendering and reloading of
//   individual ad position frames
wxtools.DynamicOAS_position = function(name, type) {
	with ({
		// private properties and methods
		
		_name:name,			// ad position name
		_static:false,		// render this ad only on the initial page load
		_dynamic:false,		// render this ad on subsequent refreshes
		_manual:false,		// render this ad only when explicitly requested
		_frame:null,		// cached reference to the iframe object
		_node:null,			// cached reference to the iframe DOM element
		
		// creates the iframe
		_write:function() {
			document.write([
				'<iframe ',
					'id="',this._name,'_frame" ',
					'name="',this._name,'_frame" ',
					'frameBorder="0" ',
					'scrolling="no" ',
					'allowtransparency="true" ',
					'background-color="transparent" ',
					'class="OASAdFrame" ',
					'></iframe>'].join(''));
		}
	}) {
		// BEGIN constructor
		switch (type) {
			case 'static':
				_static = true;
				break;
			case 'manual':
				_manual = true;
				break;
			case 'dynamic':
			default:
				_dynamic = true;
				break;
		}
		
		_write();
		
		_frame = top.frames[_name + '_frame'];
		_node = document.getElementById(_name + '_frame');
		
		if (!_manual) {
			_frame.location.replace([wxtools.DynamicOAS_AdFrameURL,'?position=',_name,'&cb=',Math.random()].join(''));
		}
		
		EventBroadcaster.initialize(this);
		// END constructor
		
		// public methods and properties
		
		// getter for the position name
		this.getName = function() { return _name; };
		
		// reloads the position
		this.reload = function() {
			if (!_static) {
				_frame.location.replace([wxtools.DynamicOAS_AdFrameURL,'?position=',_name,'&cb=',Math.random()].join(''));
			}
		};
		
		// broadcasts the new dimensions
		this.resize = function(width, height) {
			_node.style.height = height + 'px';
			_node.style.width = width + 'px';
			this.broadcastMessage('onResize', width, height);
		};
	}
}

// The Ads2 implementation class
//   This is a singleton class that abstracts all dynamic ad implementation details
//   It can be used with a standard OAS page implementation - just turn off the 
//    OAS ad call and include this JS.
wxtools.DynamicOAS = new function() {
	with ({
		// private properties and methods
		
		_url:null,				// current OAS request URL
		_frame:null,			// cached reference to the request iframe object
		_ready:false,			// flag to track when an ad call is in-progress
		_dynamicCall:false,		// flag to indicate whether the currect call is dynamic
		_names:[],				// the static position names
		_dynamicNames:[],		// the dynamic position names
		_manualNames:{},		// the manually rendered position names
		_positions:{},			// hash of the DynamicOAS_position objects
		
		// constructs and returns the current OAS request URL
		_getURL:function(names) {
			return [OAS_url,'adstream_mjx.ads/',OAS_host,OAS_spoof,'/1',(new String(Math.random())).substring(2,11),'@',names.join(','),'?',OAS_query].join('');
		},
		
		// iterates across the appropriate (static/dynamic) position list triggering
		//  content refreshes
		_reload:function() {
			var list = (this._dynamicCall?this._dynamicNames:this._names);
			for (var i = 0; i < list.length; i++) {
				if (this._positions[list[i]] !== null && !this._manualNames[list[i]]) {
					try {
						this._positions[list[i]].reload();
					} catch (e) {
						// the position is probably in a display:none container
					}
				}
			}
		}
	}) {
		// BEGIN constructor
		_names = OAS_listpos.split(',');
		_dynamicNames = OAS_listpos.split(',');
		
		_url = _getURL(_names);
		
		// creates the ad call frame
		document.write('<style>.OASAdFrame{margin:0px;padding:0px;top:0px;left:0px;width:100%;height:100%;border:none;overflow:hidden;}</style>');
		document.write(['<iframe id="OAS_frame" name="OAS_frame" src="',wxtools.DynamicOAS_CallFrameURL,'?cb=',Math.random(),'"class="OASAdFrame" style="position:absolute; width:0px; height:0px;"></iframe>'].join(''));
		// END constructor
		
		// public properties and methods
		
		// getter for current OAS request URL
		this.getTarget = function() { return _url; };
		
		// triggers an ad refresh
		this.reload = function() {
			_ready = false;
			_dynamicCall = true;
			_url = _getURL(_dynamicNames);
			_frame.location.replace([wxtools.DynamicOAS_CallFrameURL,'?cb=',Math.random()].join(''));
		};
		
		// creates and returns a new ad position object
		//  there are 3 types available:
		//    "dynamic" - the ad will be reloaded each time the ad target is changed
		//    "static" - the ad will only be loaded on the initial page load
		//    "manual" - the ad content will be refreshed each time the ad target is changed but the ad will only be rendered
		//               when explicitly requested (via the drawPosition method)
		//  "dynamic" is the default if no type is specified
		this.addPosition = function(name, type) {
			if (type == 'static') {
				for (var i = 0; i < _dynamicNames.length; i++) {
					if (_dynamicNames[i] == name) {
						_dynamicNames.splice(i, 1);
						break;
					}
				}
			} else if (type == 'manual') {
				_manualNames[name] = true;
			}
			
			_positions[name] = new wxtools.DynamicOAS_position(name, type);
			return _positions[name];
		};
		
		// renders a manual ad position
		this.drawPosition = function(name) {
			if (!_manualNames[name]) return;
			
			_positions[name].reload();
		};
		
		// The following methods are public but should NEVER be called.  They are used
		//  by the associated iframes to talk to DynamicOAS.  I've tried to explain briefly
		//  how each is used...
		
		// triggers a refresh of the ad positions
		//   this method is called by the ad call frame once its load is complete
		//   this method is also responsible for getting the cached reference
		//     to the iframe the first time it is called
		this.callFinished = function() {
			if (!_frame) _frame = top.frames.OAS_frame;
			_ready = true;
			_reload();
		};
		
		// tells an ad position that it has resized
		//   the various ad frames call this method because they don't have a reference
		//   to their associated ad position object
		this.resizeAd = function(name, width, height) { if(_ready) _positions[name].resize(width, height); };
		
		// executes the OAS_RICH method in an ad position frame
		//   this method is called by an ad frame to tell DynamicOAS that it
		//   is ready to have the ad rendered inside itself
		this.drawAd = function(position, doc) { if (_ready) _frame.drawAd(position, doc); };
	}
};

// global vanity alias
var DynamicOAS = wxtools.DynamicOAS;
OAS_MJX_on = false; // this must be set to false 
// override the OAS_RICH function - simplifies integration with existing pages
function OAS_RICH(position, type) {
	if (position == "PageCounter"){
		return wxtools.DynamicOAS.addPosition(position, 'static'); // as a rule of thumb PageCounter must be loaded only once
	}else{
		return wxtools.DynamicOAS.addPosition(position, type);
	}
}