function inheritAll() {
	for (var i = 1; i < arguments.length; i++) {
		for (x in arguments[i].prototype) {
			arguments[0].prototype[x] = arguments[i].prototype[x];
		}
	}
}

// take '##x##' string, parse it into h & w
function parseDimensions(dimString) {
	var h = 324;
	var w = 576;

	ar = dimString.split('x');
	if (ar[1]) {
		w = ar[0];
		h = ar[1];
	}
	return {height: h, width:w};
}

function CNNPlaylistManager() {
	if (CNNPlaylistManager.caller != CNNPlaylistManager.getInstance) {
		if((navigator.userAgent.indexOf('Safari')==-1) && (navigator.userAgent.indexOf('Opera')==-1)) {
			throw new Error("There is no public constructor for CNNPlaylistManager.");
		}
	}
	this.jsonurls = null;
	this.noCookies = false;
	this.forceSensitive = false;
	this.dataObject = null;
	this.cnnIsIntl = (location.hostname.indexOf('edition.') > -1) ? true : false; 
	this.playerName = null;
	this.playlists = new Array();
	this.activePlaylist = null;
	this.playlistType = '';
	this.vidString = 'BVP';
	this.vidContext = 'BVP';
	this.slateSize = '576x324';
	this.onlyCallMeOnce = false;
	this.isVideoError = false;
	this.errorObject = null;

	//atlas integration
	this.atlasActive = false;
	this.atlasSlateSize = null;
	this.viewport = null;
	this.atlasURL = null;
	this.atlasClick = function() {
		window.open(this.atlasURL, "atlas");
	}
	this.killAtlas = function() {
		if (this.atlasActive) {
			try {
				if (document.getElementById('atlasLayer') != null) {
					this.viewport.removeChild(document.getElementById('atlasLayer'));
				}
			} catch(err) { }
			this.atlasActive = false;
		}
	}	

	this.playlist = function(jsonList,pointer) {
		this.jsonList = jsonList;
		this.pointer = pointer;
		this.playlistJsonObjs = null;
		this.activeJson = function() { return this.jsonList[this.pointer]; }
	}
	this.advanceTo = function(playlistName,val) {
		if (this.noCookies == false) {
			if (this.splashActive) {
				this.splashActive = false;
				document.getElementById('cnnVPFlashLargeContainer').style.backgroundImage = '';
				document.getElementById('cnnVPFlashLargeContainer').innerHTML = '';
			}
			if (this.activePlaylist != playlistName) {
				this.activePlaylist = playlistName;
				this.playlists[this.activePlaylist].pointer = val;
				if (this.onlyCallMeOnce == false) {
					this.onlyCallMeOnce = true;
					CNNPlayer.getActivePlayer().setPlayerContext(this.vidContext);
					CNNPlayer.getActivePlayer().createPlayListContext(this.vidString);
				}
				CNNPlayer.getInstance('','advanceTo1').loadContent(this.playlists[this.activePlaylist].jsonList,this.playlists[this.activePlaylist].activeJson());
			} else {
				this.playlists[this.activePlaylist].pointer = val;
				CNNPlayer.getInstance('','advanceTo2').setCurrentPlayListPosition(this.playlists[this.activePlaylist].activeJson());			
			}
			this.highlight();
		}
	}
	this.setPlaylist = function(playlistName,callBackFunc) {

		pt = this.playlists[playlistName];
		pt.playlistJsonObjs = [];
		this.getPlayer().serializerFactory = xmp.baseplayer.BasePlayer.createContentVideoMetaLoader(pt.jsonList,
			pt.playlistJsonObjs, CNNPlayer.playlistContentItemCB, callBackFunc, this);
		this.getPlayer().serializerFactory.load();


//		pt = this.playlists[playlistName];
//		this.getPlayer().serializerFactory = xmp.baseplayer.MetaFileLoaderFactory.getInstance().create('videoContentMeta');
//		pt.playlistJsonObjs = this.getPlayer().serializerFactory.setIds(pt.jsonList, (new xmp.util.Callback('contentItemCB', CNNPlayer.playlistContentItemCB, null)));	
//		this.getPlayer().serializerFactory.setAllLoadedCallback(new xmp.util.Callback('allContentItemsCB', callBackFunc, null));
//		this.getPlayer().serializerFactory.load();
	}
	this.getPlayer = function() {
		return CNNPlayer.getInstance('','getPlayer');
	}
	this.emailVideo = function() {
		this.emailThis(this.dataObject);
	}
	this.emailThis = function(obj) {
		clickTitle = this.dataObject.headline;
		clickURL = ((window.location.href.split("/"))[2])+'/video/?/'+this.dataObject.id.slice(1,this.dataObject.id.length);
		commonLoc="&fb=Y&url="+escape(getClickURL())+"&title="+escape(getClickTitle())+"&random="+Math.random()+"&partnerID="+partnerID+"&expire="+escape(getClickExpire());
		ET();
	}
	// use highlight function defined in config
	this.highlight = function() {
		var highlightFunction = CNNPlaylistManager.getInstance().SAConfiguration.highlight;
		if (typeof(highlightFunction) != 'undefined') {
			highlightFunction();
		}
	}
}

CNNPlaylistManager.__instance__ = null; 

CNNPlaylistManager.getInstance = function (playerName) {
	if (this.__instance__ == null) {
		inheritAll(CNNPlaylistManager,SAPlaylistManager);
		this.__instance__ = new CNNPlaylistManager();
		this.__instance__.playerName = playerName;
		currentPlayer = playerName;
	}
	return this.__instance__;
}
CNNPlaylistManager.isBootStrapped = null;
CNNPlaylistManager.endOfVideoContent = function() {
	ppp = CNNPlaylistManager.getInstance().playlists[CNNPlaylistManager.getInstance().activePlaylist];
	if (ppp.playlistJsonObjs.length - 1 != ppp.pointer) {
		ppp.pointer++;
		CNNPlaylistManager.getInstance().highlight();
		CNNPlaylistManager.getInstance().runNextUpSlate = true;
	}
	CNNPlayer.getInstance('','endOfVideoContent').advance();
}
CNNPlaylistManager.findImageSize = function(imageSizeArray, id) {
	var ct = imageSizeArray.length;
	var default_size = this.getInstance().SAConfiguration.defaultStreamSize[0] + 'x' + this.getInstance().SAConfiguration.defaultStreamSize[1];

	for (var i = 0; i < ct; i++) {
		if (imageSizeArray[i].id == id) {
			return imageSizeArray[i].resource;
		}
		if (imageSizeArray[i].id == default_size) {
			var default_image = imageSizeArray[i].resource;
		}
	}

	if (typeof(default_image) != 'undefined') {
		return default_image;
	} else {
		return ("http://i.cdn.turner.com/cnn/.element/img/2.0/global/misc/"+id+".no.photo.gif");
	}
}

function SAPlaylistManager() {}
SAPlaylistManager.prototype.SAConfiguration = null;
SAPlaylistManager.prototype.SALoadVideo = function(configuration) {
		this.SAConfiguration = configuration;
		this.jsonurls = this.SAConfiguration.videoArray;
		this.vidContext = this.SAConfiguration.vidContext;
		this.vidString = this.SAConfiguration.vidString;
		this.slateSize = this.SAConfiguration.slateSize[0]+"x"+this.SAConfiguration.slateSize[1];
		CNNPlaylistManager.isBootStrapped = SAIsBootStrapped;
		CNNPlayer.create();

}
SAPlaylistManager.prototype.SABootStrapCallback = function(success) {
	if (success) {
		this.playlists['saplaylist'] = new this.playlist(this.jsonurls,this.SAConfiguration.startPoint);
		this.setPlaylist('saplaylist',SAPlaylistUICallback);
	} else {
		if (this.errorObject != null) {
			this.SAConfiguration.bootErrorHandler(this.errorObject._code);
		} else {
			this.SAConfiguration.bootErrorHandler("General Error");
		}
	}
}
SAPlaylistManager.prototype.SAWriteSplash = function() {
	this.playlistType = 'sa';
	this.playStartSlate = true;
	this.dataObject = this.playlists['saplaylist'].playlistJsonObjs[this.SAConfiguration.startPoint].getDataObject();
	this.SAConfiguration.initHandler();
	CNNPlaylistManager.getInstance().advanceTo('saplaylist',this.SAConfiguration.startPoint);
}
SAPlaylistManager.prototype.SANoFlashTimer = function() {
	this.SAConfiguration.bootErrorHandler('No Flash');
}

SAPlaylistUICallback = function() { 
	CNNPlaylistManager.getInstance().SAWriteSplash();
}


SAIsBootStrapped = function(success) {
	if (success) {
		CNNPlaylistManager.getInstance().SABootStrapCallback(success);
	} else {
		var e = CNNPlaylistManager.getInstance().errorObject;
		if ((e.name === "InvalidPlugInVersionError") && (e.message.indexOf("Flash PlugIn/ActiveX Player") != -1)) {
			var dim = parseDimensions(CNNPlaylistManager.getInstance().slateSize);
			var ex = new SWFObject('/.element/js/2.0/video/xmp/expressinstall.swf', 'expressinstall', dim['width'], dim['height'], '6', '#CCCCCC');
			ex.write(CNNPlaylistManager.getInstance().SAConfiguration.videoDivId);
		} else if (e.message.indexOf('PlugInNotFoundError') > -1) {
			document.getElementById(CNNPlaylistManager.getInstance().SAConfiguration.videoDivId).innerHTML = "<div class=\"cnnNoFlashContainer\"><div class=\"cnnNoFlash\"><p class=\"cnnTopGraf\">This CNN.com feature is optimized for Adobe Flash Player version 9 or higher.<\/p><a href=\"http://www.adobe.com/go/getflashplayer\" target=\"blank\"><img src=\"http://i.cdn.turner.com/cnn/.element/img/2.0/global/noflash/install_btn.gif\" class=\"cnnGetBtn\" width=\"155\" height=\"31\" alt=\"Get Flash Player\" border=\"0\"><\/a><\/div><\/div>";
		} else {
			CNNPlaylistManager.getInstance().errorSlate();
		}
	}
}

function flipBVPImage(imgName,srcName,onOff,ad) {
	if (ieVersion() == 0 || ieVersion() >= 7) {
		document.images[imgName+'Img'].src = 'http://i.cdn.turner.com/cnn/video/bvp/images/'+srcName+'_'+onOff+'.png';
	}
	else {
		if (ad == null) ad = '';
		document.getElementById(imgName+'_button'+ad).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://i.cdn.turner.com/cnn/video/bvp/images/"+srcName+"_"+onOff+".png')";
	}
}

function makeOn() { flipBVPImage('play','play','on'); }
function makeOff() { flipBVPImage('play','play','off'); }
function emailOn() { flipBVPImage('email','email','on'); }
function emailOff() { flipBVPImage('email','email','off'); }
function moveOn1() { flipBVPImage('replay','rply','on'); } 
function moveOut1() { flipBVPImage('replay','rply','off'); }

function ieVersion() {
	var ua = window.navigator.userAgent;
  var msie = ua.indexOf ( "MSIE " );
  if ( msie > 0 )      // If Internet Explorer, return version number
  	return parseInt (ua.substring (msie+5, ua.indexOf (".", msie )));
  else                 // If another browser, return 0
    return 0;
}

function cnnDetermineVideoFromPlaylist( filterName, videoArray ) {
		var numberOfVids = videoArray.length;
		var prevVideos = StorageManager.getInstance().getStorage().get('vid_prevPlayed_'+filterName);
		if(!prevVideos){ prevVideos = '';}
		var currentPrevVideos = '';
		var currentPosition = parseInt(Math.random()*numberOfVids);
		var returnVid = false;

		// start currentPosition towards the end
		while((currentPosition<numberOfVids) && returnVid== false)
		{
			var videoUrl = videoArray[currentPosition];
			if(prevVideos.indexOf( videoUrl )==-1)
			{
				returnVid = videoUrl;
			}
			currentPosition++;
		}

		// repeat but  start at bottom and go upwards
		currentPosition=0;
		while((currentPosition>0) && returnVid== false)
		{
			var videoUrl = videoArray[currentPosition];
			if(prevVideos.indexOf( videoUrl )==-1)
			{
				returnVid = videoUrl;
			}
		}
		if(returnVid==false)
		{
			// We haven't found a new video - so let's reset things
			returnVid = videoArray[0];
			prevVideos='';
		}
		if(returnVid)
		{
			prevVideos+= returnVid;

		}
		prevVideos[filterName] = currentPrevVideos;
		StorageManager.getInstance().getStorage().remove('vid_prevPlayed' );
		StorageManager.getInstance().getStorage().put('vid_prevPlayed_'+filterName, prevVideos );
		StorageManager.getInstance().getStorage().save();
		return returnVid;
	}


/* ****************************************************************
   Begin Adobe Client Side Flash Detection Script
   ****************************************************************
 */
 
// Flash Player Version Detection - Rev 1.6
// Detect Client Browser type
// Copyright(c) 2005-2006 Adobe Macromedia Software, LLC. All rights reserved.

var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

CNNPlaylistManager.prototype.ADOBEControlVersion = function() {
	var version;
	var axo;
	var e;
	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) { }
	if (!version) {
		try {
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			version = "WIN 6,0,21,0";
			axo.AllowScriptAccess = "always";
			version = axo.GetVariable("$version");
		} catch (e) { }
	}
	if (!version) {
		try {
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) { }
	}
	if (!version) {
		try {
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) { }
	}
	if (!version) {
		try {
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) { version = -1; }
	}
	return version;
}

CNNPlaylistManager.prototype.ADOBEGetSwfVer = function() {
	var flashVer = -1;
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = this.ADOBEControlVersion();
	}	
	return flashVer;
}

CNNPlaylistManager.prototype.ADOBEDetectFlashVer = function(reqMajorVer, reqMinorVer, reqRevision) {
	versionStr = this.ADOBEGetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

/* ********************
   End Adobe Client Side Flash Detection Script
   ********************
 */