/**
 * BCJS 0.2.0 (9 APRIL 2009)
 * A Brightcove JavaScript Library
 *
 * AUTHOR:
 *       Matthew Congrove, Professional Services Engineer, Brightcove
 *       Brian Franklin, Professional Services Engineer, Brightcove
 *       Jesse Streb, Professional Services Engineer, Brightcove
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE. YOU AGREE TO RETAIN IN THE SOFTWARE AND ANY MODIFICATIONS TO THE
 * SOFTWARE THE REFERENCE URL INFORMATION, AUTHOR ATTRIBUTION AND CONTRIBUTOR
 * ATTRIBUTION PROVIDED HEREIN.
 *
 * BCJS incorporates the following libraries:
 *
 *       Kudos-JS - Brightcove Javascript SDK
 *       Copyright (C) 2009 Brian Franklin, Matthew Congrove
 *       http://www.kudos-js.com
 *
 * BCJS requires the following libraries:
 *
 *       NWMatcher - http://javascript.nwbox.com/NWMatcher
 */

var BCJS = function() {
	this.init = function() {
		this.DOM = new BCJS.DOM();
		this.DOM.init();
		this.EXP = new BCJS.EXP();
		this.EXP.init();
		this.UI = new BCJS.UI();
		this.UI.init();
		/*
			this.API = new BCJS.API();
			this.API.init();
		*/

		this.$ = this.DOM.select;
		this.$$ = this.DOM.hasMatch;

		this.browser = this.browser();
		this.isSafari = false;
		this.isFirefox = false;
		this.isIE = false;
		this.isIE6 = false;
		this.isIE7 = false;

		if(this.browser[1] == "firefox") {
			this.isFirefox = true;
		} else if(this.browser[1] == "safari") {
			this.isSafari = true;
		} else if(this.browser[1] == "explorer") {
			this.isIE = true;

			if(this.browser[2] < 7) {
				this.isIE6 = true;
			} else if(this.browser[2] < 8) {
				this.isIE7 = true;
			}
		}
	};

	this.ajax = function(pSrc, pCallback, pPost, pParams) {
		if(window.XMLHttpRequest) {
			httpRequest = new XMLHttpRequest();
			if(httpRequest.overrideMimeType) {
				httpRequest.overrideMimeType("text/xml");
			}
		} else if(window.ActiveXObject) {
			try {
				httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch(e1) {
				try {
					httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
				}
			catch(e2) {}
			}
		}

		if(!httpRequest) {
			return false;
		}

		httpRequest.onreadystatechange = function() {
			if(httpRequest.readyState == 4) {
				if(httpRequest.status == 200) {
					if(!pCallback) {
						return httpRequest.responseText;
					} else {
						pCallback(httpRequest.responseText);
					}
				}
			}
		};

		if(!pPost) {
			if(!pCallback) {
				httpRequest.open("GET", pSrc, false);
			} else {
				httpRequest.open("GET", pSrc, true);
			}

			httpRequest.send("");
		} else {
			httpRequest.open("POST", pSrc, true);
			httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			httpRequest.setRequestHeader("Content-length", pParams.length);

			httpRequest.send(pParams);
		}
	};

	this.browser = function() {
		var type;
		var os;
		var version;

		var browser = new Array(
			{string: navigator.userAgent, subString: "Chrome", identity: "Chrome"},
			{string: navigator.userAgent, subString: "OmniWeb", versionSearch: "OmniWeb/", identity: "OmniWeb"},
			{string: navigator.vendor, subString: "Apple", identity: "Safari", versionSearch: "version"},
			{prop: window.opera, identity: "Opera"},
			{string: navigator.vendor, subString: "iCab", identity: "iCab"},
			{string: navigator.vendor, subString: "KDE", identity: "Konqueror"},
			{string: navigator.userAgent, subString: "Firefox", identity: "Firefox"},
			{string: navigator.vendor, subString: "Camino", identity: "Camino"},
			{string: navigator.userAgent, subString: "Netscape", identity: "Netscape"},
			{string: navigator.userAgent, subString: "MSIE", identity: "Explorer", versionSearch: "MSIE"},
			{string: navigator.userAgent, subString: "Gecko", identity: "Mozilla", versionSearch: "rv"},
			{string: navigator.userAgent, subString: "Mozilla", identity: "Netscape", versionSearch: "Mozilla"}
		);

		var system = new Array(
			{string: navigator.platform, subString: "Win", identity: "windows"},
			{string: navigator.platform, subString: "Mac", identity: "mac"},
			{string: navigator.platform, subString: "Linux", identity: "linux"}
		);

		var g = function(d) {
			for(var i = 0; i < d.length; i++) {
				var s = d[i].string;
				var p = d[i].prop;

				type = d[i].versionSearch || d[i].identity;

				if(s) {
					if(s.indexOf(d[i].subString) != -1) {
						return d[i].identity;
					}
				} else if(p) {
					return d[i].identity;
				}
			}
		};

		var h = function(s, t) {
			var i = s.indexOf(t);

			if(i == -1) {
				return;
			}

			return parseFloat(s.substring(i + t.length + 1));
		};

		browser = g(browser) || "unknown";
		version = h(navigator.userAgent, type) || h(navigator.appVersion, type) || "unknown";
		browser = browser.toLowerCase();
		os = g(system) || "unknown";

		return new Array(os, browser, version);
	};

	this.dimensions = function() {
		var win_width;
		var win_height;
		var scroll_width;
		var scroll_height;

		if(typeof window.innerWidth != "undefined") {
			win_width = window.innerWidth;
			win_height = window.innerHeight;
		} else if(typeof document.documentElement != "undefined" && typeof document.documentElement.clientWidth != "undefined" && document.documentElement.clientWidth != 0) {
			win_width = document.documentElement.clientWidth;
			win_height = document.documentElement.clientHeight;
		} else {
			win_width = document.getElementsByTagName("body")[0].clientWidth;
			win_height = document.getElementsByTagName("body")[0].clientHeight;
		}

		if(typeof(window.pageYOffset) == "number") {
			scroll_width = window.pageXOffset;
			scroll_height = window.pageYOffset;
		} else if(document.body && (document.body.scrollLeft || document.body.scrollTop)) {
			scroll_width = document.body.scrollLeft;
			scroll_height = document.body.scrollTop;
		} else if(document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
			scroll_width = document.documentElement.scrollLeft;
			scroll_height = document.documentElement.scrollTop;
		}

		if(typeof(win_width) == "undefined") { win_width = 0; }
		if(typeof(win_height) == "undefined") { win_height = 0; }
		if(typeof(scroll_width) == "undefined") { scroll_width = 0; }
		if(typeof(scroll_height) == "undefined") { scroll_height = 0; }

		return new Array(win_width, win_height, scroll_width, scroll_height);
	};

	this.getNum = function(pNum) {
		var ret = "";
		var bool = false;

		if(pNum.indexOf("px") > -1) {
			bool = true;
			ret = parseInt(pNum.substring(0, pNum.indexOf("px")));
		} else {
			ret = parseInt(pNum);
		}

		return new Array(ret, bool);
	};

	this.time = function(pNum) {
		pNum = new Number(pNum / 1000);
		var h = Math.floor(pNum / 3600);
		var m = Math.floor(pNum % 3600 / 60);
		var s = Math.floor(pNum % 3600 % 60);
		return ((h > 0 ? h + ":" : "") + (m > 0 ? (h > 0 && m < 10 ? "0" : "") + m + ":" : "0:") + (s < 10 ? "0" : "") + s);
	};

	this.getCookie = function(pName) {
		var start = document.cookie.indexOf(pName + "=");
		var len = start + pName.length + 1;

		if((!start) && (pName != document.cookie.substring(0, pName.length))) {
			return null;
		}

		if(start == -1) {
			return null;
		}

		var end = document.cookie.indexOf(";", len);

		if(end == -1) {
			end = document.cookie.length;
		}

		return unescape(document.cookie.substring(len, end));
	};

	this.setCookie = function(pName, pValue, pExpires, pOptions) {
		if(pOptions === undefined) {
			pOptions = {};
		}

		if(pExpires) {
			var expires_date = new Date();
			expires_date.setDate(expires_date.getDate() + pExpires)
		}

		document.cookie = pName + "=" + escape(pValue) +
			((pExpires) ? ";expires="+expires_date.toGMTString() : "") +
			((pOptions.path) ? ";path=" + pOptions.path : "") +
			((pOptions.domain) ? ";domain=" + pOptions.domain : "") +
			((pOptions.secure) ? ";secure" : "");
	};

	this.deleteCookie = function(pName, pPath, pDomain) {
		if(BCJS.getCookie(pName)) {
			document.cookie = pName + "=" +
			((pPath) ? ";path=" + pPath : "") +
			((pDomain) ? ";domain=" + pDomain : "") +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
		}
	};

	this.base64 = function(pType, pString) {
		var key = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
		var keyRe = new RegExp("[^" + key + "=]", "g");

		if(pType == "encode") {
			var i = 0;
			var output = "";
			var len = pString.length;
			var padding = 3 - (len % 3);

			while(i < len) {
				var byte1 = pString.charCodeAt(i++);
				var byte2 = pString.charCodeAt(i++) || 0;
				var byte3 = pString.charCodeAt(i++) || 0;
				var index1 = byte1 >> 2;
				var index2 = (byte1 & 3) << 4 | byte2 >> 4;
				var index3 = (byte2 & 15) << 2 | byte3 >> 6;
				var index4 = byte3 & 63;

				output += key.charAt(index1) + key.charAt(index2) + key.charAt(index3) + key.charAt(index4);
			}

			if(padding) {
				output = output.slice(0, output.length - padding) + (padding == 1 ? "=" : "==");
			}

			return output;
		} else {
			pString = pString.replace(keyRe, "");

			var i = 0;
			var output = "";
			var len = pString.length;
			var padding = len - pString.indexOf("=");

			while(i < len) {
				var byte1 = key.indexOf(pString.substr(i++, 1));
				var byte2 = key.indexOf(pString.substr(i++, 1));
				var byte3 = key.indexOf(pString.substr(i++, 1));
				var byte4 = key.indexOf(pString.substr(i++, 1));
				var char1 = byte1 << 2 | byte2 >> 4;
				var char2 = ((byte2 & 15) << 4) | (byte3 >> 2);
				var char3 = ((byte3 & 3) << 6) | byte4 & 63;

				output += String.fromCharCode(char1) + String.fromCharCode(char2) + String.fromCharCode(char3);
			}

			if(padding) {
				output = output.substr(0, output.length - padding);
			}

			return output;
		}
	};

	this.param = function(pName) {
		pName = pName.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");

		var regexS = "[\\?&]" + pName + "=([^&#]*)";
		var regex = new RegExp(regexS);
		var results = regex.exec(window.location.href);

		if(results == null) {
			return "";
		} else {
			return results[1];
		}
	};

	this.UI = function() {
		this.init = function() {
			this.isFading = false;
		};

		this.tween = function(pEl, pType, pNewValue, pTime, pCallback) {
			if(typeof(pEl) == "string") {
				pEl = BCJS.DOM.select(pEl)[0];
			}

			if(pType == "opacity") {
				if(BCJS.isIE) {
					pType = "filter";
				}
			}

			if(pTime == 0 || typeof(pTime) != "number") {
				pTime = 1;
			}

			var pStartValue = BCJS.getNum(pEl.style[pType])[0];
			var pValueDistance = pNewValue - pStartValue;
			var pTimeStart = new Date().getTime();
			var pTimeEnd = pTimeStart + pTime;

			BCJS.UI.tweenExecute(pEl, pType, pStartValue, pValueDistance, pTime, pTimeEnd, pCallback);
		};

		this.tweenExecute = function(pEl, pType, pStartValue, pValueDistance, pTime, pTimeEnd, pCallback) {
			var pCurrentTime = new Date().getTime();
			var pTimeRemaining = Math.max(0, pTimeEnd - pCurrentTime);
			var pCurrentMove;

			if(pType == "top" || pType == "right" || pType == "bottom" || pType == "left") {
				pCurrentMove = Math.round((pValueDistance - (Math.pow(pTimeRemaining, 3) / Math.pow(pTime, 3)) * pValueDistance) * 10) / 10;
			} else {
				pCurrentMove = Math.round((pValueDistance - (pTimeRemaining / pTime) * pValueDistance) * 10) / 10;
			}

			if(pTimeRemaining <= 0 || pValueDistance > 10) {
				pCurrentMove = parseInt(pCurrentMove);
			}

			if(pType != "filter") {
				var isPx = BCJS.getNum(pEl.style[pType])[1];
			}

			if(isPx) {
				pEl.style[pType] = (pStartValue + pCurrentMove) + "px";
			} else {
				if(pType == "filter") {
					pEl.style[pType] = "alpha(opacity=" + ((pStartValue + pCurrentMove) * 100) + ")";
				} else {
					pEl.style[pType] = (pStartValue + pCurrentMove);
				}
			}

			if(pTimeRemaining > 0) {
				setTimeout(
					function() {
						BCJS.UI.tweenExecute(pEl, pType, pStartValue, pValueDistance, pTime, pTimeEnd, pCallback);
					},
					10
				);
			} else {
				if(typeof(pCallback) == "function") {
					pCallback();
				}
			}
		};

		this.hide = function(pEl) {
			if(typeof(pEl) == "string") {
				pEl = BCJS.DOM.select(pEl)[0];
			}

			if(pEl.style["display"] != "none" && pEl.style["display"] != "hidden") {
				pEl.style["display"] = "none";
			}
		};

		this.show = function(pEl) {
			if(typeof(pEl) == "string") {
				pEl = BCJS.DOM.select(pEl)[0];
			}

			if(pEl.style["display"] == "none" || pEl.style["display"] == "hidden") {
				pEl.style["display"] = "block";
			}
		};

		this.toggle = function(pEl) {
			if(typeof(pEl) == "string") {
				pEl = BCJS.DOM.select(pEl)[0];
			}

			if(pEl.style["display"] == "none" || pEl.style["display"] == "hidden") {
				pEl.style["display"] = "block";
			} else {
				pEl.style["display"] = "none";
			}
		};

		this.center = function(pEl) {
			if(typeof(pEl) == "string") {
				pEl = BCJS.DOM.select(pEl)[0];
			}

			var elWidth;
			var elHeight;

			if(pEl.offsetWidth) {
				elWidth = pEl.offsetWidth;
			} else {
				elWidth = BCJS.getNum(pEl.style["width"])[0];
			}

			if(pEl.offsetHeight) {
				elHeight = pEl.offsetHeight;
			} else {
				elHeight = BCJS.getNum(pEl.style["height"])[0];
			}

			var win = BCJS.dimensions();

			var newX = ((win[0] / 2) - (elWidth / 2) + win[2]);
			var newY = ((win[1] / 2) - (elHeight / 2) + win[3]);

			pEl.style["left"] = newX + "px";
			pEl.style["top"] = newY + "px";
		};
	};

	this.DOM = function() {
		this.init = function() {

		};

		this.match = function(pEl, pAttr) {
			return NW.Dom.match(pEl, pAttr);
		};

		this.select = function(pEl) {
			return NW.Dom.select(pEl);
		};

		this.hasMatch = function(pEl, pAttr) {
			if(typeof(pEl) == "string") {
				pEl = this.select(pEl)[0];
			}

			if(this.match(pEl, pAttr)) {
				return true;
			} else {
				return false;
			}
		};

		this.addClass = function(pEl, pClass) {
			if(typeof(pEl) == "string") {
				pEl = this.select(pEl)[0];
			}

			if(!this.match(pEl, "." + pClass)) {
				pEl.className = pEl.className + " " + pClass;
			}
		};

		this.removeClass = function(pEl, pClass) {
			if(typeof(pEl) == "string") {
				pEl = this.select(pEl)[0];
			}

			if(this.match(pEl, "." + pClass)) {
				var reg = new RegExp("(\\s|^)" + pClass + "(\\s|$)");
				pEl.className = pEl.className.replace(reg, " ");
			}
		};

		this.toggleClass = function(pEl, pClass) {
			if(typeof(pEl) == "string") {
				pEl = this.select(pEl)[0];
			}

			if(!this.match(pEl, "." + pClass)) {
				this.addClass(pEl, pClass);
			} else {
				this.removeClass(pEl, pClass);
			}
		};
	};

	this.EXP = function() {
		this.init = function() {
			this.player = null;
			this.experience = null;
			this.ad = null;
			this.video = null;
			this.social = null;
		};

		this.onTemplateLoaded = function(pId) {
			BCJS.EXP.player = brightcove.getExperience(pId);
			BCJS.EXP.experience = BCJS.EXP.player.getModule(APIModules.EXPERIENCE);
			BCJS.EXP.ad = BCJS.EXP.player.getModule(APIModules.ADVERTISING);
			BCJS.EXP.video = BCJS.EXP.player.getModule(APIModules.VIDEO_PLAYER);
			BCJS.EXP.social = BCJS.EXP.player.getModule(APIModules.SOCIAL)

			BCJS.EXP.experience.addEventListener(BCExperienceEvent.TEMPLATE_READY, BCJS.EXP.onTemplateReady);
			BCJS.EXP.experience.addEventListener(BCExperienceEvent.CONTENT_LOAD, BCJS.EXP.onContentLoaded);

			if(typeof BCJS.EXP.templateLoaded == "function") {
				this.templateLoaded();
			}
		};

		this.onContentLoaded = function() {
			if(typeof BCJS.EXP.contentLoaded == "function") {
				BCJS.EXP.contentLoaded();
			}
		};

		this.onTemplateReady = function() {
			BCJS.EXP.video.addEventListener(BCMediaEvent.COMPLETE, BCJS.EXP.onMediaComplete);

			if(typeof BCJS.EXP.templateReady == "function") {
				BCJS.EXP.templateReady();
			}
		};

		this.onExternalAd = function(pXML) {
			if(typeof BCJS.EXP.externalAd == "function") {
				BCJS.EXP.externalAd();
			}
		};

		this.onMediaComplete = function() {
			if(typeof BCJS.EXP.mediaComplete == "function") {
				BCJS.EXP.mediaComplete();
			}
		};
	};

	/*
	this.API = function() {
		this.init = function() {
			this.token = "";
			this.callback = "BCJS.API.flush";
			this.url = "http://api.brightcove.com/services/library";
			this.calls = [
				{ "method":"find_all_videos", "default":false },
				{ "method":"find_playlists_for_player_id", "default":"player_id" },
				{ "method":"find_all_playlists", "default":false },
				{ "method":"find_playlist_by_id", "default":"playlist_id" },
				{ "method":"find_related_videos", "default":"video_id" },
				{ "method":"find_video_by_id", "default":"video_id" },
				{ "method":"find_videos_by_ids", "default":"video_ids" },
				{ "method":"find_videos_by_tags", "default":"or_tags" },
				{ "method":"find_video_by_reference_id", "default":"reference_id" },
				{ "method":"find_video_by_reference_ids", "default":"reference_ids" },
				{ "method":"find_videos_by_user_id", "default":"user_id" },
				{ "method":"find_videos_by_campaign_id", "default":"campaign_id" },
				{ "method":"find_videos_by_text", "default":"text" },
				{ "method":"find_modified_videos", "default":"from_date" },
				{ "method":"find_playlists_by_ids", "default":"playlist_ids" },
				{ "method":"find_playlist_by_reference_id", "default":"reference_id" },
				{ "method":"find_playlists_by_reference_ids", "default":"reference_ids" }
			];
		};

		this.inject = function(pParams) {
			var pEl = document.createElement("script");

			pEl.setAttribute("src", BCJS.API.url + "?" + pParams);
			pEl.setAttribute("type", "text/javascript");

			document.getElementsByTagName("head")[0].appendChild(pEl);

			return true;
		};

		this.find = function(pMethod, pParams) {
			var pDefault = null;
			var pQuery = "";

			pParams = pParams || null;
			pMethod = pMethod.toLowerCase().replace(/(find_)|(_)|(get_)/g, "");

			for(var method in BCJS.API.calls) {
				if(pMethod == BCJS.API.calls[method].method.toLowerCase().replace(/(find_)|(_)|(get_)/g, "")) {
					pMethod = BCJS.API.calls[method].method;
					pDefault = BCJS.API.calls[method].default;
				}
			}

			pQuery = "command=" + pMethod;

			if((typeof pParams == "object") && pParams) {
				for(var pValue in pParams) {
					if(pValue == "selector") {
						pQuery += "&" + pDefault + "=" + pParams[pValue];
					} else {
						pQuery += "&" + pValue + "=" + pParams[pValue];
					}
				}

				if(typeof pParams.callback != "string") {
					pQuery += "&callback=" + this.callback;
				}

				if(typeof pParams.token != "string") {
					pQuery += "&token=" + this.token;
				}
			} else if(pParams) {
				pQuery += "&" + pDefault + "=" + pParams + "&callback=" + this.callback;
				pQuery += "&token=" + this.token;
			} else {
				pQuery += "&token=" + this.token;
				pQuery += "&callback=" + this.callback;
			}

			BCJS.API.inject(pQuery);

			return true;
		};

		this.flush = function(pData) {
			return true;
		};
	};
	*/
};

function onTemplateLoaded(pId) {
	BCJS.EXP.onTemplateLoaded(pId);
}

BCJS = new BCJS();
BCJS.init();