if (!Array.prototype.filter) {
	Array.prototype.filter = function(fun /* , thisp */) {
		var len = this.length >>> 0;
		if (typeof fun != "function")
			throw new TypeError();

		var res = [];
		var thisp = arguments[1];
		for ( var i = 0; i < len; i++) {
			if (i in this) {
				var val = this[i]; // in case fun mutates this
				if (fun.call(thisp, val, i, this))
					res.push(val);
			}
		}

		return res;
	};
}

if (!Array.prototype.forEach) {
	Array.prototype.forEach = function(fun /* , thisp */) {
		var len = this.length >>> 0;
		if (typeof fun != "function")
			throw new TypeError();

		var thisp = arguments[1];
		for (var i = 0; i < len; i++) {
			if (i in this)
				fun.call(thisp, this[i], i, this);
		}
	};
}

if (!Array.prototype.map) {
	Array.prototype.map = function(fun /*, thisp*/) {
		var len = this.length >>> 0;
		if (typeof fun != "function")
			throw new TypeError();

		var res = new Array(len);
		var thisp = arguments[1];
		for (var i = 0; i < len; i++) {
			if (i in this)
				res[i] = fun.call(thisp, this[i], i, this);
		}
		return res;
	};
}

function URL(text) {
	if (!text)
		return {};
	this.href = text; // store complete value
	// figure out hash ref:
	var t = text.lsplit('#',2);
	this.hash = (t.length > 1) ? '#' + t.pop() : '';
	text = t[0]; // store URI parts preceding the hash ref for more processing
	// figure out search query:
	t = text.lsplit('?',2);
	this.search = (t.length > 1) ? '?' + t.pop() : '';
	text = t[0]; // store URI parts preceding the search query for more processing
	// figure out protocol:
	t = text.lsplit('://',2);
	this.protocol = (t.length > 1) ? t.shift() + ':' : '';
	text = t[0]; // store URI parts succeeding the protocol for more processing
	// figure out pathname:
	t = text.lsplit('/',2);
	this.pathname = (t.length > 1) ? '/' + t.pop() : '/';
	text = t[0]; // store URI parts preceding the pathname for more processing
	// figure out auth:
	t = text.lsplit('@',2);
	this.auth = (t.length > 1) ? t.shift() : '';
	text = t[0]; // store URI parts succeeding the auth for more processing
	// I can split auth into username:password, but its not in the RFC so I don't care
	// figure out port:
	t = text.lsplit(':',2);
	this.port = (t.length > 1) ? parseInt(t.pop()) : null;
	// figure out hostname:
	this.host = t[0];
	// all done

	this.toString = function() {
		return this.protocol + '//' +
			(this.auth ? this.auth + '@' : '') +
			this.host +
			(this.port ? ':' + this.port : '') +
			this.pathname +
			this.search +
			this.hash;
	}

	return this;
};

if (!String.prototype.toURL) {
	String.prototype.toURL = function() {
		return new URL(this);
	};
}

String.prototype.lsplit = function(delimiter, limit) {
	var t = this.split(delimiter);
	return t.slice(0,limit-1).concat(t.length >= limit ? t.slice(limit-1).join(delimiter) : []);
}

/* DOM readiness */
window.wpjwDOM = new (function() {
	// Capability based browser detection
	var is_opera = window.opera ? true : false;
	var is_ie = document.attachEvent && !is_opera ? true : false;
	var is_ie7 = is_ie && window.XMLHttpRequest;
	// Safari, Konqueror and Nokia S60 3rd Ed.
	var is_khtml = document.all && document.addEventListener ? true : false;
	var is_safari = document.childNodes && !document.all && !navigator.taintEnabled && !navigator.accentColorName;
	// DOM 1 capable
	var is_dom = document.getElementById ? true : false;
	// A Mozilla Gecko DOM implementation (there should be a better way to detect it)
	var is_gecko = !is_ie && !is_khtml && !is_safari && is_dom;

	var domReadyHandlers = []; // list of handlers waiting for DOM readiness
	var docReadyState = false; // whether the DOM was deemed ready
	var trc_timer_safari = null;
	var self = this;

	this.addReadyHandler = function(func, fake) {
		if (fake) {
			window.setTimeout(func, 10);
			return;
		}
		domReadyHandlers.push(func);
	};

	// event handler that fires as soon as the DOM is ready
	function domReady() {
		try {
			if (docReadyState)
				// fail fast - no point in being here if DOM was already readied.
				return;

			docReadyState = true;
			// remove ready state detection as its no longer needed
			if (is_gecko || is_opera) {
				document.removeEventListener("DOMContentLoaded", domReady, false);
			} else if (is_ie) {
				if (self.readystatechange)
					document.detachEvent('onreadystatechange', self.readystatechange);
			} else if (is_safari) {
				if (trc_timer_safari)
					clearInterval(trc_timer_safari);
			}
			// convert ready state handler registrar to a no-op that fires any late-to-register handler immediately
			self.addReadyHandler = function(func) {
				func(); // we are already ready.
			};
			// fire all DOM ready handlers
			for ( var i = 0; i < domReadyHandlers.length; i++)
				domReadyHandlers[i].call(document);
		} catch (e) {
		}
	}

	function initDomReady() { // X-platform register for the DOM ready event
		if (is_gecko || is_opera) // Geckos are easy
			document.addEventListener("DOMContentLoaded", domReady, false);
		else if (is_ie) { // Explorers are harder
			var pd = document.createElement('div');
			(function() {
				try {
					pd.doScroll('left');
				} catch (e) {
					pd.to = window.setTimeout(arguments.callee, 10);
					return;
				}
				domReady();
			})();
			document.attachEvent('onreadystatechange', self.readystatechange = function() {
				if (/loaded|complete/.test(document.readyState)) {
					window.clearTimeout(pd.to);
					domReady();
				}
			});
		} else if (is_safari) {
			trc_timer_safari = setInterval(function() {
				if (/loaded|complete/.test(document.readyState)) {
					domReady();
				}
			}, 10);
		}
		var oldHandler = window.onload;
		window.onload = function() {
			domReady();
			if (oldHandler)
				try {
					oldHandler();
				} catch (e) {
				}
		};
	}

	initDomReady();
	return this;
})();

(function() {
	if (typeof window.wpjwManager != "undefined") {
		window.wpjwManager.renderNext();
		return;
	}

	this.wpjwObjects = [];

	// Capability based browser detection
	var is_opera = window.opera ? true : false;
	var is_ie = document.attachEvent && !is_opera ? true : false;
	var is_ie7 = is_ie && window.XMLHttpRequest;
	// Safari, Konqueror and Nokia S60 3rd Ed.
	var is_khtml = document.all && document.addEventListener ? true : false;
	var is_safari = document.childNodes && !document.all && !navigator.taintEnabled && !navigator.accentColorName;
	// DOM 1 capable
	var is_dom = document.getElementById ? true : false;
	// A Mozilla Gecko DOM implementation (there should be a better way to detect it)
	var is_gecko = !is_ie && !is_khtml && !is_safari && is_dom;

	function init() {
		if (!window.wpjwSWFObjectLoaded && typeof SWFObject == "undefined") {
			window.wpjwSWFObjectLoaded = true;
			document.writeln('<script type="text/javascript" src="/wp/wp-content/plugins/swfobject.js"></script>');
		}
		if (!window.wpjwStylesheetLoaded) {
			var link = document.createElement('link');
			link.rel = "stylesheet";
			link.type = "text/css";
			link.href = "/wp/wp-content/plugins/jwplayer/jwplayer.css";
			document.head.appendChild(link);
			window.wpjwStylesheetLoaded = true;
		}
	}

	function findDir(elm) {
		if (!elm)
			return 'left';
		var dir = elm.dir || elm.style.direction;
		switch (dir) {
			case 'ltr':
				return 'left';
			case 'rtl':
				return 'right';
			default:
				return findDir(elm.parentNode);
		}
	}

	function Renderer(parent) {
		this.objectId = "wpjw-" + Math.floor(Math.random() * 1000);
		this.width = 500;
		this.height = 390;
		this.videoFile = null;
		this.publisherId = null;
		this.videoId = null;
		this.useRBox = true;
		this.useRPlayer = true;
		this.done = false;

		this.fixRBoxDimensions = function() {
			var rbox = document.getElementById('rbox-' + this.objectId);
			rbox.style.height = this.height + 'px';
			var rboxDiv = document.getElementById('rbox-blended');
			if (!rboxDiv || rboxDiv.childNodes.length < 1) {
				var self = this;
				window.setTimeout(function() {
					self.fixRBoxDimensions();
				}, 200);
				return;
			}

			rboxDiv.style.height = (this.height - 35) + 'px';
		};

		this.render = function() {
			if (this.done)
				return;
			var so = new SWFObject('/wp/wp-content/plugins/jwplayer/player.swf', 'single', this.width, this.height, '9');
			so.addParam('wmode', 'transparent');
			so.addParam('allowScriptAccess', 'always');
			so.addParam('allowfullscreen', 'true');
			so.addVariable('fullscreen', 'true');
			so.addVariable('width', this.width);
			so.addVariable('height', this.height);
			if (this.publisherId != null && this.videoId != null) {
				so.addVariable('plugins', '/wp/wp-content/plugins/jwplayer/rplayer/taboola.swf');
				so.addVariable('taboola.publisher', this.publisherId);
				so.addVariable('taboola.video_id', this.videoId);
			}
			so.addVariable('file', (escape(this.videoFile)));
			so.write(this.objectId);
			var cont = document.getElementById(this.objectId);
			var dir = findDir(cont);
			cont.style.cssFloat = dir;
			cont.style.styleFloat = dir;
			cont.style.cssFloat = dir;
			cont = document.getElementById('rbox-' + this.objectId);
			cont.style.cssFloat = dir;
			cont.style.styleFloat = dir;
			cont.style.cssFloat = dir;
			if (this.useRBox)
				this.drawRBox();
			this.done = true;
		};

		this.drawRBox = function() {
			if (this.done)
				return;
			var self = this;
			window.setTimeout(function() {
				if (typeof TRC == "undefined")
					self.drawRBox();
				else {
					TRC.drawRBox({container: 'rbox-' + this.objectId });
					this.done = true;
				}
			}, 200);
		}


		this.draw = function() {
			document.writeln('<div id="container-' + this.objectId + '" class="wpjw-container" style="width: '
					+ (this.width + 280) + 'px;">');
			document.writeln('<div id="' + this.objectId + '" name="' + this.objectId + '" style="width: ' + this.width
					+ 'px; height: ' + this.height + 'px; background: black;"></div>');
			var self = this;
			if (this.useRBox) {
				if (!parent.rboxLoaded) {
					parent.rboxLoaded = true;
					document.writeln('<script type="text/javascript" src="http://cdn.taboolasyndication.com/libtrc/'
						+ this.publisherId + '/rbox.js?video_id=' + escape(this.videoId) + '"></script>');
				}
				document.writeln('<div id="rbox-' + this.objectId + '" class="wpjw-rbox"></div>');
				(function(ev,call){
					if (is_ie) window.attachEvent('on'+ev,call);
					else window.addEventListener(ev,call,false);
					})('load', function() {
						self.fixRBoxDimensions();
					});
			}
			document.writeln('<div style="clear: both;"></div>');
			document.writeln('</div>');
			window.wpjwDOM.addReadyHandler(function() { self.render(); });
		};

		( // get a list of all scripts
			(function(list){
					if (is_ie) {
						var p = []; for (var i = 0; i < list.length; i++) p.push(list[i]); return p;
					}
					return Array.prototype.slice.call(list,0)
				})(document.getElementsByTagName('script'))
				// filter out only myself
				.filter(function(s){return s.src.search('jwplayer.js')>=0;})
				.shift() || {} // fallback in case I can't find myself
		).src.toURL() // get my URL
			.search.substring(1).split('&').map(function(p){ // and parse the query string
				return (function(k,v){ return { key:k, val:v }; }) // into key/value pairs
					.apply(null,p.lsplit('=',2).map(function(p){ return unescape(p); })); // after unescaping them
			}).forEach(function(q){ // now parse each supported value
				switch (q.key) {
					case 'w': case 'width':
						this.width = parseInt(q.val); break;
					case 'h': case 'height':
						this.height = parseInt(q.val); break;
					case 'p': case 'publisher':
						this.publisherId = q.val; break;
					case 'v': case 'video': case 'f': case 'file':
						this.videoFile = q.val; break;
					case 'i': case 'videoid': case 'video-id':
						this.videoId = q.val; break;
				}
			}, this);

		this.useRPlayer = this.publisherId != null && this.videoId != null;
		this.useRBox = this.useRPlayer && document.getElementById('content').className == 'widecolumn';

		if (typeof parent.wpjwObjects[this.videoFile] != "undefined")
			return parent.wpjwObjects[this.videoFile]; // misuse Javascript object system to avoid duplicates

		parent.wpjwObjects[this.videoFile] = this;
		parent.wpjwObjects.push(this);
			return this;
	}

	this.renderNext = function() {
		var wpjw = new Renderer(this);
		if (this.wpjwObjects.length > 1)
			wpjw.useRBox = false;
		wpjw.draw();
	}

	init();
	this.renderNext();
	return (window.wpjwManager = this);
})();
