if (!this.videostrip) { var videostrip = {}; }

/**
 * AdMatcher client functions for both publisher and advertisters (who use conversion tracking)
 */
videostrip.admatcher = {

	/**
	 * Different banner size defitions.
	 */
	bannerSizes: {
		'fullsize': { 'width': 468, 'height': 60 },
		'skyradio': { 'width': 320, 'height': 60 },
		'skyradiosmall': { 'width': 160, 'height': 30 },
		'halfsize': { 'width': 234, 'height': 60 },
		'rectangle': { 'width': 300, 'height': 250 },
		'button': { 'width': 120, 'height': 60 },
		'leaderboard': { 'width': 728, 'height': 90 },
		'largerectangle': { 'width': 336, 'height': 280 },
		'skyscraper': { 'width': 120, 'height': 600 }
	},

	/**
	 * This function is called form the AdMatcherClient (be it the JWPlayer plugin
	 * or another instance of a client) and passes in a banner ad domain object.
	 * This function tries to display the banner inside the pubsliher's page, but
	 * only if a div tag with a correct ID is present in the DOM.
	 * 
	 * @param {Object} bannerAd BannerAd domain object
	 */
	showBanner: function(bannerAd) {
		
//		if (console && console.log) {
//			console.log(bannerAd);
//		}
		
		if (typeof bannerAd.vast20Events == "string") {
			
			bannerAd.vast20Events = eval("(" + bannerAd.vast20Events + ")");
			
		} else {
			
			bannerAd.vast20Events = [ ];
		}
		
		var bannerName = bannerAd.type.toLowerCase();
		var prefixes = ['banner_', 'vs_a2s_tag_'];
		var bannerElement;
		for (var i in prefixes) {
			bannerElement = document.getElementById(prefixes[i] + bannerName);
			if (bannerElement != null) { break; }
		}
		if (bannerElement == null) { return false; }

		var divElement = document.createElement('div');
		divElement.style.position = 'absolute';
		divElement.style.width = this.bannerSizes[bannerName].width + 'px';
		divElement.style.height = this.bannerSizes[bannerName].height + 'px';
		divElement.style.backgroundColor = '#ffffff';
		divElement.style.filter = 'alpha(opacity=0)';
		divElement.style.opacity = 0;
		divElement.style.mozOpacity = 0;
		divElement.style.cursor = 'pointer';
		bannerElement.innerHTML = '';
		bannerElement.appendChild(divElement);

		var clickHandler = function() {
			if (typeof bannerAd.clickUrl != "undefined" && bannerAd.targetUrl != "undefined") {
				this.sendVast20Event(bannerAd.vast20Events, 'click');
				window.open(bannerAd.clickUrl + '&url=' + escape(bannerAd.targetUrl));
			}
		};

		if (document.addEventListener) {
			divElement.addEventListener('click', videostrip.admatcher.bind(this, clickHandler), true);
		} else if (document.attachEvent) {
			divElement.attachEvent('onclick', videostrip.admatcher.bind(this, clickHandler));
		} else {
			divElement.onclick = videostrip.admatcher.bind(this, clickHandler);
		}

		var iframeElement = document.createElement('iframe');
		iframeElement.setAttribute('frameBorder', 0);
		iframeElement.setAttribute('scrolling', 'no');
		iframeElement.setAttribute('allowTransparency', true);
		iframeElement.setAttribute('width', this.bannerSizes[bannerName].width);
		iframeElement.setAttribute('height', this.bannerSizes[bannerName].height);
		bannerElement.appendChild(iframeElement);

		var html = '';
		html += '<html>';
		html += '<head><style type="text/css">* { margin:0; padding:0; } body { background-color:transparent; }</style></head>';
		if (typeof bannerAd.sourceTag != "undefined") {
			
			html += '<body>' + bannerAd.sourceTag + '</body>';
			
		} else  if (typeof bannerAd.tag != "undefined") {
			
			html += '<body>' + bannerAd.tag + '</body>';
		}
		html += '</html>';

		iframeElement.contentWindow.document.open('text/html', 'replace');
		iframeElement.contentWindow.document.write(html);
		setTimeout(function() { iframeElement.contentWindow.document.close(); }, 2000);

		this.sendVast20Event(bannerAd.vast20Events, 'creativeView');
	},
	
	sendVast20Event: function(aVast20Events, event) {
		
		if (typeof aVast20Events == "array" || typeof aVast20Events == "object") {
				
			if (typeof aVast20Events[event] == "array" || typeof aVast20Events[event] == "object") {
				
				for	(var p in aVast20Events[event]) {
						
					var url = aVast20Events[event][p];
					if (typeof url == "string") {
						
						url = url + "&javaScript=1";
						var tracker = document.createElement("script");
						tracker.src = url;
						document.getElementsByTagName('head')[0].appendChild(tracker);
					}
				}
			}
		}
	},

	// dummy: to be removed
	setupConversion: function(domain) {},

	/**
	 * This function tries to register the conversion at Videostrip's EventTracker,
	 * with the optionalData.
	 */
	registerConversion: function(optionalData) {
		DomReady.ready(function() {

			var url = 'http://eventtracker.videostrip.com/?event=conversion&pixel=1&data=' +
				encodeURIComponent(optionalData);

			var imgElement = document.createElement('img');
			imgElement.src = url;
			imgElement.width = 1;
			imgElement.height = 1;
			imgElement.alt = '';

			var bodyElm = document.getElementsByTagName('body')[0];
			bodyElm.appendChild(imgElement);

		});
	},
	
	bind: function (obj, fun, args) {
		return function() {
	    	if (obj === true) {
				obj = this;
			}
			var f = typeof fun === "string" ? obj[fun] : fun;
	    	return f.apply(obj, Array.prototype.slice.call(args || []).concat(Array.prototype.slice.call(arguments)));
		};
	}
};

/**
 * The old way of placing companion banners
 */
videostrip.banner = {

	init: function(bannerAd) {
		videostrip.admatcher.showBanner(bannerAd);
	}
};

/**
 * Cookie functions implicit include to prevent seperate includes in client pages.
 */
videostrip.cookies = {

	/**
	 * Set a cookie. An argument defaults when it is assigned null as a
	 * placeholder. A null placeholder is not required for trailing omitted
	 * arguments.
	 * @param {Object} name Name of the cookie.
	 * @param {Object} value Value of the cookie.
	 * @param {Object} [lifetime] Time (in seconds) a cookie should exist.
	 * 					Defaults to end of current session.
	 * @param {Object} [path] Path for which the cookie is valid.
	 * 					Defaults to path of calling document.
	 * @param {Object} [domain] Domain for which the cookie is valid.
	 * 					Defaults to domain of calling document.
	 * @param {Object} [secure] Boolean value indicating if the cookie
	 * 					transmission requires a secure transmission.
	 */
	setCookie: function(name, value, lifetime, path, domain, secure) {
		if (lifetime) {
			var d = new Date();
			d.setTime(d.getTime() + lifetime * 1000);
			var expires = '; expires=' + d.toGMTString();
		} else {
			var expires = null;
		}
		document.cookie = name + '=' + escape(value) +
			(expires ? expires : '') +
			(path ? '; path=' + path : '') +
			(domain ? '; domain=' + domain : '') +
			(secure ? '; secure' : '');
	},

	/**
	 * Return string containing value of specified cookie or null
	 * if cookie does not exist
	 * @param {Object} name Name of the desired cookie.
	 */
	getCookie: function(name) {
		var dc = document.cookie, prefix = name + '=', begin = dc.indexOf('; ' + prefix);
		if (begin == -1) {
			begin = dc.indexOf(prefix); if (begin == -1) { return null; }
		} else {
			begin += 2;
		}
		var end = dc.indexOf(';', begin); if (end == -1) { end = dc.length; }
		return unescape(dc.substring(begin + prefix.length, end));
	},

	/**
	 * Delete a cookie. Path and domain are optional and default if assigned
	 * null or omitted if no explicit argument proceeds. Also path and domain
	 * must be same as used to create cookie.
	 * @param {Object} name
	 * @param {Object} [path]
	 * @param {Object} [domain]
	 */
	deleteCookie: function(name, path, domain) {
		videostrip.cookies.setCookie(name, '', -1, path, domain);
	}

};

(function(){

    var DomReady = window.DomReady = {};

	// Everything that has to do with properly supporting our document ready event. Brought over from the most awesome jQuery. 

    var userAgent = navigator.userAgent.toLowerCase();

    // Figure out what browser is being used
    var browser = {
    	version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
    	safari: /webkit/.test(userAgent),
    	opera: /opera/.test(userAgent),
    	msie: (/msie/.test(userAgent)) && (!/opera/.test( userAgent )),
    	mozilla: (/mozilla/.test(userAgent)) && (!/(compatible|webkit)/.test(userAgent))
    };    

	var readyBound = false;	
	var isReady = false;
	var readyList = [];

	// Handle when the DOM is ready
	function domReady() {
		// Make sure that the DOM is not already loaded
		if(!isReady) {
			// Remember that the DOM is ready
			isReady = true;
        
	        if(readyList) {
	            for(var fn = 0; fn < readyList.length; fn++) {
	                readyList[fn].call(window, []);
	            }
            
	            readyList = [];
	        }
		}
	};

	// From Simon Willison. A safe way to fire onload w/o screwing up everyone else.
	function addLoadEvent(func) {
	  var oldonload = window.onload;
	  if (typeof window.onload != 'function') {
	    window.onload = func;
	  } else {
	    window.onload = function() {
	      if (oldonload) {
	        oldonload();
	      }
	      func();
	    }
	  }
	};

	// does the heavy work of working through the browsers idiosyncracies (let's call them that) to hook onload.
	function bindReady() {
		if(readyBound) {
		    return;
	    }
	
		readyBound = true;

		// Mozilla, Opera (see further below for it) and webkit nightlies currently support this event
		if (document.addEventListener && !browser.opera) {
			// Use the handy event callback
			document.addEventListener("DOMContentLoaded", domReady, false);
		}

		// If IE is used and is not in a frame
		// Continually check to see if the document is ready
		if (browser.msie && window == top) (function(){
			if (isReady) return;
			try {
				// If IE is used, use the trick by Diego Perini
				// http://javascript.nwbox.com/IEContentLoaded/
				document.documentElement.doScroll("left");
			} catch(error) {
				setTimeout(arguments.callee, 0);
				return;
			}
			// and execute any waiting functions
		    domReady();
		})();

		if(browser.opera) {
			document.addEventListener( "DOMContentLoaded", function () {
				if (isReady) return;
				for (var i = 0; i < document.styleSheets.length; i++)
					if (document.styleSheets[i].disabled) {
						setTimeout( arguments.callee, 0 );
						return;
					}
				// and execute any waiting functions
	            domReady();
			}, false);
		}

		if(browser.safari) {
		    var numStyles;
			(function(){
				if (isReady) return;
				if (document.readyState != "loaded" && document.readyState != "complete") {
					setTimeout( arguments.callee, 0 );
					return;
				}
				if (numStyles === undefined) {
	                var links = document.getElementsByTagName("link");
	                for (var i=0; i < links.length; i++) {
	                	if(links[i].getAttribute('rel') == 'stylesheet') {
	                	    numStyles++;
	                	}
	                }
	                var styles = document.getElementsByTagName("style");
	                numStyles += styles.length;
				}
				if (document.styleSheets.length != numStyles) {
					setTimeout( arguments.callee, 0 );
					return;
				}
			
				// and execute any waiting functions
				domReady();
			})();
		}

		// A fallback to window.onload, that will always work
	    addLoadEvent(domReady);
	};

	// This is the public function that people can use to hook up ready.
	DomReady.ready = function(fn, args) {
		// Attach the listeners
		bindReady();
    
		// If the DOM is already ready
		if (isReady) {
			// Execute the function immediately
			fn.call(window, []);
	    } else {
			// Add the function to the wait list
	        readyList.push( function() { return fn.call(window, []); } );
	    }
	};
    
	bindReady();
	
})();
