
function CoAdBrowser(targetDiv,scrolling) {
	
	//private vars
	var inited = false;
	var iframeBrowser;
	var target;
	var currentSrc;
	
	this.updateWindow = function (src,width,height) {

		try {

			if(!inited)
				init();
				
			iframeBrowser.style.cssText = 	'width:' + width + 'px;height:' + height + 'px;';	
		}catch(e) {}
		
		setSrc(src);
	}

	this.destroyWindow = function() {
		try{
			iframeBrowser.contentWindow.location.replace("about:blank");
		}catch(e){}
		target.removeChild(iframeBrowser);	
	}
	
	// private methods
	var init = function() {

		try {
		
			var scrolling = scrolling && scrolling != "null" ? scrolling : "no";
			if(navigator.appName=="Microsoft Internet Explorer"){
				iframeBrowser = document.createElement('<iframe sr' + 'c="" allowtransparency="true" scrolling="' + scrolling + '" frameborder="0"></iframe>');
			}else{
				iframeBrowser = document.createElement('iframe');
				iframeBrowser.setAttribute("frameborder", 0);
				iframeBrowser.setAttribute("scrolling", scrolling);
				iframeBrowser.setAttribute("allowtransparency", "true"); 	
				iframeBrowser.setAttribute("background-color", "transparent"); 	
			}
			iframeBrowser.style.display = 'none';
			
			target = document.getElementById(targetDiv);
			
			target.appendChild(iframeBrowser);
			
			inited = true;
			
		}catch(e) {}
	}
	
	var setSrc = function(src) {
		//if(src && currentSrc!=src){
		if(src){
			try{

				if(iframeBrowser.contentWindow)
					iframeBrowser.contentWindow.location.replace(src);
				else
					iframeBrowser.src = src;	
				
				currentSrc = src;
			}catch(e){
			
				iframeBrowser.src = src;
				currentSrc = src;
			} 
		}
	}

};


function CoAdPNG(targetDiv) {
	
	//private vars
	var initialized = false;
	var target;
	var container;
	var currentSrc;
	
	this.update = function (src,width,height,clickTag) {		
		try {
			if(!initialized){
				init();
			}
			else if(currentSrc!=src) this.destroy();
			
			if(src && currentSrc!=src){
				container = document.createElement('div');
				container.style.width = width + "px";
				container.style.height = height + "px";
				container.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='image')";
				container.onclick = function(){ window.open(clickTag); }
	
				if(isIE==undefined){
					var img = document.createElement('img');
					img.src = src;
					currentSrc = src;
			
					container.appendChild(img);
				}
				
				target.appendChild(container);
			}				
		}
		catch(e) {}		
	}
	
	this.destroy = function() {
		target.removeChild(container);	
	}
	
	// private methods
	var init = function() {
		try {
			target = document.getElementById(targetDiv);
			initialized = true;
		}
		catch(e) {}
	}

};

function linkEvent(lnk,linkName,linkType,linkVars) {

      mtvn.btg.Controller.sendLinkEvent({
        linkName : linkName,
        linkType : linkType
      });
}

/* *************************************************** */

// global variables
var com_mtvi_mtv2flag;
var controller;
var coad = new CoAdBrowser("coadTarget");
var coadLogo = new CoAdBrowser("coadTarget2");
var coadPNG = new CoAdPNG("coadLogoTarget");

MTVN.Player = new function(){
	this.feed = {};
	this.context = "page";
	this.instance;
	this.videoUri;
	this.episodeUri;
	this.vid;
	this.id;
	this.artist;
	this.artistType;
	this.movieId;
	this.personId;
	this.channelId;
	this.name;	
	this.category;
	this.sort;

	this.videoType;
	this.episodeType;
	this.gateway;
	this.albumID;
	this.contentTypeId;
	this.defaultPlaylistId;
	this.defaultArtistId;
	this.artists = new Array();
	this.freeWheelSSID;
    this.reloadableAds;

	this.episodeObj = {};
	this.seriesObj = {};
	this.channelObj = {};
	this.artistObj = {};
	this.tvSeriesObj = {};
	this.movieObj = {};
	this.personObj = {};
	this.recommendationsObj = {};

	// allow handling of local (site-specific) content
	this.localFeedHandler = function(){}
	this.localModulesHandler = function(){}

	var continuousPlayCookieName = "mtvnContinuousPlay";
	var multiGridViewCookie = "multiGridView";	
	var continuousPlayConfigValue;
	var suspendContinuousPlay;
	var channelOverride;
	var pageModulesLoaded = false;
	
	// synchronous feed variables
	var feedUrl = "/global/music/videos/json/feed.jhtml";
	var feedUrlParams = {};
	var doLoadFeed = false;
	
	// ads
	this.bannerAdRefreshTime = 120000;
	this.coAdRefreshTime = 90000;
	this.rectangleAdRefreshTime = 90000;
	
	var bannerInterval;
	var bannerAdObject = {};

	var coAdInterval;
	var coAdObject = {};
	
	var rectangleInterval;
	var rectangleAdObject = {};
	var useRectangleAd = false;
	
	this.init = function(){
		MTVN.Player.setContinuousPlayConfigValue(true);	
		
		if(MTVN.Player.context=="page" && $j("#embedContainer").is("*")){
			// set onclick events for controls
			if($j("#continuousPlay").is("*")){
				$j("#continuousPlay").bind("click", function(e){
					MTVN.Player.setContinuousPlayValue(this.checked);
				});
				MTVN.Player.updateContinuousPlayControl();
			}
			
			// update "get url" field with hash
			if ($j('#videoUrl').length > 0) {
				var videoUrlInput = $j("#videoUrl").get(0);
				videoUrlInput.value += window.location.hash;
			}
			
			// handle IE page title problem
			if(jQuery.browser.msie){
				setInterval("MTVN.resetPageTitle()", 1000);
			}
			try{          
		   	if (mtvn.btg.config.AdSettings.FreeWheel == null || !mtvn.btg.config.AdSettings.FreeWheel.enabled && MTVN.Player.reloadableAds!=false) MTVN.Player.initBannerAd();
			
			
			if (MTVN.Player.episodeType=="fullEpisode") {
                $j('#ad-300x250').remove();
                $j('.mdl-ad').css('display','none');
				// Dont resize if gigya module is included in the page.
				if (typeof(gigya_chat_conf) == 'undefined') MTVN.Player.resize(768,463);
			}
			else if (mtvn.btg.config.AdSettings.FreeWheel == null || !mtvn.btg.config.AdSettings.FreeWheel.enabled && MTVN.Player.reloadableAds!=false) MTVN.Player.initRectangleAd();
			}catch(e){ }
			MTVN.Player.initClipboardButtons();
			
			//if (typeof(gigya_chat_conf) == 'undefined')

				//setTimeout('MTVN.Player.initFacebookLike()',3000);

			if(MTVN.Player.feed.document != null && MTVN.Player.feed.document.chatModuleSkin!=null) {
			
				setTimeout('MTVN.Player.loadChatModule()',2500);

			}
		}
	}
	
	/* Continuous Play functions
	--------------- */
	this.onCommentsLoaded = function(){
		$j("div.fluxWidgetComments div.inputWrapper textarea").bind("focus", function(e){
			MTVN.Player.setSuspendContinuousPlay(true);
	    });
	}
	
	this.setSuspendContinuousPlay = function(val){
		suspendContinuousPlay = val;
	}
	this.getSuspendContinuousPlay = function(){
		return suspendContinuousPlay;
	}
	
	this.setContinuousPlayConfigValue = function(val){
		continuousPlayConfigValue = val;
	}
	this.getContinuousPlayConfigValue = function(){
		return continuousPlayConfigValue;
	}
	
	this.setContinuousPlayValue = function(val){
		MTVN.Utils.Cookies.create(continuousPlayCookieName, val, 365);
		MTVN.Player.updateContinuousPlayControl();
	}
	this.getContinuousPlayValue = function(){
		var cookieValue = MTVN.Utils.Cookies.read(continuousPlayCookieName);

		if(cookieValue!=null){
			var cookieBoolean = (cookieValue=="true") ? true : false;
			return cookieBoolean;
		}
		else{
			return MTVN.Player.getContinuousPlayConfigValue();
		}
	}
	
	this.updateContinuousPlayControl = function(){
		var controlValue = (MTVN.Player.getContinuousPlayValue()) ? true : false;
		$j("#continuousPlay").get(0).checked = controlValue;
		//MTVN.Player.output();
	}
	
	this.getContinuousPlayOverride = function(){
		if(suspendContinuousPlay != undefined ){
			return !suspendContinuousPlay;
		}
		else{
			return MTVN.Player.getContinuousPlayValue();
		}
	}
		
	/* load/parse/set metadata
	--------------- */	
	this.loadMetadata = function(){
		var hash = window.location.hash.substring(1);
		var vars = hash.split("&");
		for (var i=0; i < vars.length; i++) {
			var pair = vars[i].split("=");
			if (pair[0] == "name"){
				MTVN.Player.name = pair[1];
				feedUrlParams.name = MTVN.Player.name;
			}
			if (pair[0] == "id"){
				MTVN.Player.id = pair[1];
				feedUrlParams.id = MTVN.Player.id;
				doLoadFeed = true;
			}
			if (pair[0] == "artist"){
				MTVN.Player.artist = pair[1];
				feedUrlParams.artist = MTVN.Player.artist;
				doLoadFeed = true;
			}
			if (pair[0] == "artistType"){
				MTVN.Player.artistType = pair[1];
				feedUrlParams.artistType = MTVN.Player.artistType;
				doLoadFeed = true;
			}
			if (pair[0] == "movieId"){
				MTVN.Player.movieId = pair[1];
				feedUrlParams.movieId = MTVN.Player.movieId;
				doLoadFeed = true;
			}
			if (pair[0] == "personId"){
				MTVN.Player.personId = pair[1];
				feedUrlParams.personId = MTVN.Player.personId;
				doLoadFeed = true;
			}
			if (pair[0] == "category"){
				MTVN.Player.category = pair[1];
				feedUrlParams.category = MTVN.Player.category;
				doLoadFeed = true;
			}
			if (pair[0] == "sort"){
				MTVN.Player.sort = pair[1];
				feedUrlParams.sort = MTVN.Player.sort;
				doLoadFeed = true;
			}
			if (pair[0] == "clipsync"){
				MTVN.Player.clipSyncToggle = pair[1];
			}
		}

		if (!doLoadFeed && MTVN.Player.defaultPlaylistId != undefined){
			MTVN.Player.id = MTVN.Player.defaultPlaylistId;
			feedUrlParams.id = MTVN.Player.id;
			doLoadFeed = true;
		}

		if (!doLoadFeed && MTVN.Player.defaultArtistId != undefined){
			MTVN.Player.artist = MTVN.Player.defaultArtistId;
			feedUrlParams.artist = MTVN.Player.artist;
			doLoadFeed = true;
		}

		if(doLoadFeed){
			$j.ajax({
				url: feedUrl,
				data: feedUrlParams,
				dataType: "json",
				async: false,
				success: function(data){
					//console.log("success");
					MTVN.Player.parseMetadata(data);
				},
				complete: function(){
					//console.log("complete");
				}
			});
		}
	}
	
	this.parseMetadata = function(data){
		MTVN.Player.feed = data;

		if(MTVN.Player.feed.document != undefined){
			if(MTVN.Player.feed.document.episodeType!=undefined) MTVN.Player.episodeType = MTVN.Player.feed.document.episodeType;
			if(MTVN.Player.feed.document.channelOverride!=undefined) channelOverride = MTVN.Player.feed.document.channelOverride;
			if(MTVN.Player.feed.document.rollup!=undefined) MTVN.Ads.additionalValues += "rollup=" + MTVN.Player.feed.document.rollup + ";";
			if(MTVN.Player.feed.document.keyValues!=undefined) MTVN.Ads.additionalValues += MTVN.Player.feed.document.keyValues;
			if(MTVN.Player.feed.document.reporting!=undefined) MTVN.Reporting.dispatcherAttributes = MTVN.Player.feed.document.reporting;
			if(MTVN.Player.feed.document.navOverride!=undefined) MTVN.Player.internical = MTVN.Player.feed.document.navOverride;
			if(MTVN.Player.feed.document.navInclude!=undefined) MTVN.Player.internical = MTVN.Player.feed.document.navInclude;
			if(MTVN.Player.feed.document.tuneInPromo!=undefined) MTVN.Player.tuneInPromo = MTVN.Player.feed.document.tuneInPromo;
			if(MTVN.Player.feed.document.additionalSuite!=undefined && MTVN.Player.feed.document.additionalSuite.toLowerCase().indexOf("vma") > -1) com_mtvi_vmaflag = true;
			if(MTVN.Player.feed.document.additionalSuite!=undefined && MTVN.Player.feed.document.additionalSuite.toLowerCase().indexOf("unplugged") > -1) com_mtvi_unpluggedflag = true;
		}

		if (MTVN.Player.feed.document.pageKeyValues.browser != undefined) var pageKeyVals = MTVN.Player.feed.document.pageKeyValues.browser.document;
		if(pageKeyVals !=undefined){
			if(pageKeyVals.adPageVals!=undefined) MTVN.Ads.adPageVals = pageKeyVals.adPageVals;
			if(pageKeyVals.vidZone!=undefined) MTVN.Ads.sections = pageKeyVals.vidZone;
			if(pageKeyVals.additionalValues!=undefined) MTVN.Ads.additionalValues = pageKeyVals.additionalValues;			
			if(pageKeyVals.dartSiteOverride!=undefined) MTVN.Ads.dartSite = pageKeyVals.dartSiteOverride;
		}
		   						
		// handle <meta> nodes from feed
		if(MTVN.Player.feed.document.meta instanceof Array){
			for (var i=0; i < MTVN.Player.feed.document.meta.length; i++){
				MTVN.Player.setMetadata(MTVN.Player.feed.document.meta[i]);
			}
		}
		else{
			MTVN.Player.setMetadata(MTVN.Player.feed.document.meta);
		}

		// handle <document> nodes from feed
		if(MTVN.Player.feed.document.document != undefined){
			if(MTVN.Player.feed.document.document instanceof Array){
				for (var i=0; i < MTVN.Player.feed.document.document.length; i++){
					MTVN.Player.setMetadata(MTVN.Player.feed.document.document[i]);
				}
			}
			else{
				MTVN.Player.setMetadata(MTVN.Player.feed.document.document);
			}
		}
		
	 	if(MTVN.Player.feed.document.localFeedHandler != undefined)	var localFeedHandler = eval(MTVN.Player.feed.document.localFeedHandler+"()");
	}
	
	this.setMetadata = function(obj){
		// assign <meta> nodes from feed to client-side objects
		if(obj.type=="artist") MTVN.Player.artistObj = obj;
		else if(obj.type=="movie") MTVN.Player.movieObj = obj;
		else if(obj.type=="moviepersonality") MTVN.Player.personObj = obj;
		else if(obj.type=="episode"){
			MTVN.Player.episodeObj = obj;
			if(MTVN.Player.episodeObj.type=="series"){
				MTVN.Player.seriesObj = MTVN.Player.episodeObj;
				if(MTVN.Player.seriesObj.type=="channel") MTVN.Player.channelObj = MTVN.Player.seriesObj;
			}
		}

		// assign <document> nodes from feed to client-side objects
		if(obj.tvSeries!=undefined){
			MTVN.Player.tvSeriesObj = obj.tvSeries;
		}
	}
	
	this.loadChatModule = function(){
	
			MTVN.UI.InView.register($j(".group-c"), function() {
			
				var container = $j(".group-c");
		
				$j("<div/>").attr("class", "mdl mdl-clean chatMod").prependTo(".group-c");

				if (MTVN.Player.vid == "588319") $j("<iframe/>").attr({width: "300", height: "395", scrolling: "no", frameborder: "no", name: "chatFrame", marginwidth: "0", marginheight: "0", src: "/global/music/player/ajax/chatModuleHTML.jhtml?id=" + MTVN.Player.id}).prependTo(".chatMod");
				else $j("<iframe/>").attr({width: "300", height: "608", scrolling: "no", frameborder: "no", name: "chatFrame", marginwidth: "0", marginheight: "0", src: "/global/music/player/ajax/chatModuleHTML.jhtml?id=" + MTVN.Player.id}).prependTo(".chatMod");
			});
			
			
		
	}
	
	this.initFacebookLike = function() {
	
		var likeUrl = document.location.href;
	
		var hostname = window.location.hostname + '';
		var pathname = window.location.pathname + '';
		var search = window.location.search + '';
		var hash = window.location.hash + '';
	
		if (hostname.indexOf("mtvi") > -1) {
			hostname = hostname.replace(/-jd.mtvi.com/, ".com");
			hostname = hostname.replace(/-jq.mtvi.com/, ".com");
			hostname = hostname.replace(/-d.mtvi.com/, ".com");
			hostname = hostname.replace(/-q.mtvi.com/, ".com");
		}

		var newsearch = '';
		if(search.length > 1)
			newsearch = '&'+search.substring(1);

		var newURL = 'http:\/\/'+hostname+pathname+'?xrs=share_fblike'+newsearch+hash;

		var container = $j("#fblike");
		container.empty().append('<iframe src="http://www.facebook.com/plugins/like.php?href='+escape(newURL)+'&layout=standard&show_faces=false&width=280&action=like&font=arial&colorscheme=dark&height=80" scrolling="no" id="fbLikeFrame" frameborder="0" style="border:none; overflow:hidden; width:280px; height:80px;" allowTransparency="true"> </iframe>');
	}	


	/* Flash instantiation and player API calls
	--------------- */
	this.addPlayer = function(){
	MTVN.Player.setPlaylistHeader();
		
		// derive instance
		var instance = MTVN.Constants.playerChannelDomain;
		if(MTVN.Player.context == "popout") instance = "popout";
		else if(MTVN.Player.context == "moviemain") instance = "moviemain";
		else if(MTVN.Player.context == "fivedollarcover") instance = "fivedollarcover";
		else if(MTVN.Player.episodeUri != undefined) instance = "fullepisode";
		
		var flashObjectId = "embeddedPlayer";
		var flashVersion = "10.0.12.36";
		var configParams = "instance=" + instance;
		
		if(MTVN.Player.name != undefined) configParams += "&name=" + MTVN.Player.name;
		if(MTVN.Player.vid != undefined) configParams += "&vid=" + MTVN.Player.vid;
		if(MTVN.Player.id != undefined) configParams += "&id=" + MTVN.Player.id;
		if(MTVN.Player.artist != undefined) {
			configParams += "&artist=" + MTVN.Player.artist;
			if(MTVN.Player.artistType != undefined)
				configParams += "&artistType=" + MTVN.Player.artistType;
		}
		if(MTVN.Player.movieId != undefined) configParams += "&movieId=" + MTVN.Player.movieId;
		if(MTVN.Player.personId != undefined) configParams += "&personId=" + MTVN.Player.personId;
		if(MTVN.Player.category != undefined) configParams += "&category=" + MTVN.Player.category;
		if(MTVN.Player.sort != undefined) configParams += "&sort=" + MTVN.Player.sort;
		
		var src = MTVN.Constants.playerMediaHost + "/";
		if(MTVN.Player.episodeUri != undefined) src += MTVN.Player.episodeUri;
		else src += MTVN.Player.videoUri;

		/*var flashvars = {
			//configParams: encodeURIComponent(configParams)
			config: "config.xml"
		};*/
		var params = {
			allowFullScreen: "true",
			allowScriptAccess: "always",
			wmode: "transparent",
			swliveconnect: "true",
			bgcolor: "#000000"
		};
		var attributes = {
			id: flashObjectId,
			name: flashObjectId
		};
		
		//switch to check vid id so the immersive 360 player gets added to the correct pages
		//344910 is a test vid for now until i get the correct vid id's
		//make sure  the DOM is loaded before the functions are called so the related videos module shows up on the right
		
		switch(MTVN.Player.vid) {
			case 461146:
				$j(function(){
					var flashvars = {
						config: "config_461146.xml"
					};
					MTVN.Player.create360Vid(flashvars, params, attributes);
					MTVN.Player.getPlaylist();
					
					});
				break;
			
			case 461151:
				$j(function(){
					var flashvars = {
						config: "config_461151.xml"
					};
					MTVN.Player.create360Vid(flashvars, params, attributes);
					MTVN.Player.getPlaylist();
					
					});
				break;
			
			case 461159:
				$j(function(){
					var flashvars = {
						config: "config_461159.xml"
					};
					MTVN.Player.create360Vid(flashvars, params, attributes);
					MTVN.Player.getPlaylist();
					
					});
				break;
			
			case 461160:
				$j(function(){
					var flashvars = {
						config: "config_461160.xml"
					};
					MTVN.Player.create360Vid(flashvars, params, attributes);
					MTVN.Player.getPlaylist();
					
					});
				break;
			
			case 461161:
				$j(function(){
					var flashvars = {
						config: "config_461161.xml"
					};
					MTVN.Player.create360Vid(flashvars, params, attributes);
					MTVN.Player.getPlaylist();

					});
				break;
			
			case 461162:
				$j(function(){
					var flashvars = {
						config: "config_461162.xml"
					};
					MTVN.Player.create360Vid(flashvars, params, attributes);
					MTVN.Player.getPlaylist();
					
					});
				break;
			
			case 461163:
				$j(function(){
					var flashvars = {
						config: "config_461163.xml"
					};
					MTVN.Player.create360Vid(flashvars, params, attributes);
					MTVN.Player.getPlaylist();
					
					});
				break;
			
			case 461164:
				$j(function(){
					var flashvars = {
						config: "config_461164.xml"
					};
					MTVN.Player.create360Vid(flashvars, params, attributes);
					MTVN.Player.getPlaylist();
					
					});
				break;
			
			default:
				var hostname = window.location.hostname + '';
				// Load ClipSync Player
				if ((MTVN.Player.clipSync&&MTVN.Player.clipSyncToggle!="false")||MTVN.Player.clipSyncToggle=="true") {
					$j.getScript("http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php");
					$j.getScript("/global/apps/clipsync/clipsyncembed.jhtml");
				}
				// or Load MTVN Player
				else {
					var flashvars = {
						sid: MTVN.Player.freeWheelSSID,
						configParams: encodeURIComponent(configParams),
						autoPlay: "true"
					};

					//harry potter hack
					/*
			        if(MTVN.Player.vid == "596009") {
			            src = "http://media.mtvnservices.com/player/prime/?CONFIG_URL=http%3A%2F%2Fwww.mtv.com%2Fplayer%2Fembed%2FAS3%2Fharrypotter_live%2Fconfiguration.jhtml%3Fref%3Dwww.mtv.com&uri=mgid:uma:videolist:mtv.com:1651952";
						flashvars = {
                        	sid: MTVN.Player.freeWheelSSID,
							configParams: encodeURIComponent(configParams),
							autoPlay: "true",
							ref: "www.mtv.com"
						};
					}
                    */

					swfobject.embedSWF(src, flashObjectId, "100%", "100%", flashVersion, "/global/scripts/swfobject_2_1/expressInstall.swf", flashvars, params, attributes);
				}				
		}

		controller = new MTVNPlayerController(flashObjectId,"MTVN.Player.onPlayerLoaded");
	}
	
	
	this.create360Vid = function(flashvars, params, attributes){
		$j('#playerMdl').addClass('implayer');
		$j('#videoPlayer').addClass('implayer2');
		swfobject.embedSWF("/global/apps/music/apps/immersivemedia/IMPlayer.swf", "embeddedPlayer", "600", "550", "9", "/global/scripts/swfobject_2_1/expressInstall.swf", flashvars, params, attributes);
		
		
	}

	this.resize = function(w,h){
		if(w > 640) $j("#playerContainer").parent().removeClass("group-ab").addClass("group-abc"); 
		else $j("#playerContainer").parent().removeClass("group-abc").addClass("group-ab"); 
		
		$j("#videoPlayer").width(w);
		$j("#videoPlayer").height(h);
	}
	
	this.setCoad = function(adObject){
		// Ignore coad in ad package
/*		var src = adObject.url;
	    var w = adObject.width;
	    var h = adObject.height;
	  	var clickTag = adObject.clickUrl;
		
		//console.log(src + ", " + w + ", " + h);

		if(w == '300' && h == '250'){
			coad.updateWindow(src, w, h);
		} else if(w =='120' && h == '60'){
			coadLogo.updateWindow(src, w, h);
		} else if(w =='300' && h == '150'){
			coadPNG.update(src, w, h, clickTag);
		}*/
	}
	
	this.onPlayerLoaded = function(controller){
//		controller.player.addEventListener("NO_AD","MTVN.Player.onNoAd");
		controller.player.addEventListener("METADATA","MTVN.Player.onMetaData");
		controller.player.addEventListener("STATE_CHANGE","MTVN.Player.onStateChange");
		
//		if(MTVN.Player.episodeType!="fullEpisode" && MTVN.Player.episodeType!="afterShow")
//			coAdInterval = setInterval("MTVN.Player.refreshCoad()", MTVN.Player.coAdRefreshTime);

		//controller.player.addEventListener("METADATA","console.log('onMetaData')");
		//controller.player.addEventListener("READY","console.log('onReady')");
	}
	
	this.onMetaData = function(metadata){
		if(metadata.adUrl!=null && coAdObject.url==undefined){
			MTVN.Player.setCoAdObject(metadata.adUrl);
		}
	}
	
	this.onStateChange = function(state){
		if(MTVN.Player.context=="page" && state=="playing") {
			setTimeout('MTVN.Player.loadExtras()', 10);
		}
	}
	
	this.loadExtras = function (){
		if(!pageModulesLoaded) MTVN.Player.loadPageModules();
	}

	this.onNoAd = function (metadata){
		if(!useRectangleAd){
			MTVN.Player.setCoAdObject(metadata.adUrl);
			MTVN.Player.refreshCoad();
		}
	}
	
	this.setCoAdObject = function(adUrl){
		if (adUrl.indexOf("pfadx") != -1) {
			coAdObject.url = adUrl.replace(/pfadx/, "adi").replace(/640x480/, "300x250").replace(/text\/xml/, "text/html");
			coAdObject.width = "300";
			coAdObject.height = "250";
		}
	}
	
	this.refreshCoad = function(){
		if(coAdObject.url!=undefined){
			var newAdUrl = coAdObject.url;
			newAdUrl = newAdUrl.substring(0,newAdUrl.lastIndexOf("ord=")+4) + Math.round(Math.random()*Math.pow(10,7)).toString();
			coAdObject.url = newAdUrl;
			MTVN.Player.setCoad(coAdObject);
		}	
	}

	this.initBannerAd = function(){
		try {
			var adUrl;
			if($j("#ad-728x90").is("*")){
				adUrl = $j("#ad-728x90 script:eq(1)").get(0).src;
			}
			else if($j("#opa_and_ad_holder").is("*")){
				adUrl = $j("#opa_and_ad_holder script:eq(1)").get(0).src;
			}
			if(adUrl != ''){
				adUrl = adUrl.replace(/adj/, "adi");		
				bannerAdObject.url = adUrl;
				bannerInterval = setInterval("MTVN.Player.refreshBannerAd()", MTVN.Player.bannerAdRefreshTime);
			}
		} catch(e) {
			//alert('initBannerAd error:'+e.description);
		}
	}
	
	this.initRectangleAd = function(){
		if($j("#ad-300x250").is("*")){
        
			useRectangleAd = true;
			//var adUrl = $j("#ad-300x250 script:eq(1)").get(0).src;
			// Take banner ad params and use it for the 300x250.
			if($j("#ad-728x90").is("*")) var adUrl = $j("#ad-728x90 script:eq(1)").get(0).src;
			else var adUrl = $j("#opa_and_ad_holder script:eq(1)").get(0).src;
			adUrl = adUrl.replace(/adj/, "adi");
			adUrl = adUrl.replace(/728x90/g, "300x250");
			adUrl = adUrl.replace(/tile([-=])1/g, "tile$12");
			rectangleAdObject.url = adUrl;
			//var rectangle = new CoAdBrowser("ad-300x250");
			//rectangle.updateWindow(rectangleAdObject.url, 300, 250);
			rectangleInterval = setInterval("MTVN.Player.refreshRectangleAd()", MTVN.Player.rectangleAdRefreshTime);
		}
	}
	
	this.refreshBannerAd = function(){
		var newAdUrl = bannerAdObject.url;
		newAdUrl = newAdUrl.substring(0,newAdUrl.lastIndexOf("ord=")+4) + Math.round(Math.random()*Math.pow(10,7)).toString();
		bannerAdObject.url = newAdUrl;

		if($j("#ad-728x90").is("*")){
			$j("#ad-728x90").empty();
			var banner = new CoAdBrowser("ad-728x90");
		}
		else if($j("#opa_and_ad_holder").is("*")){
			$j("#opa_and_ad_holder").empty();
			var banner = new CoAdBrowser("opa_and_ad_holder");			
		}

		banner.updateWindow(bannerAdObject.url, 728, 90);
	}
	
	this.refreshRectangleAd = function(){
		var newAdUrl = rectangleAdObject.url;
		newAdUrl = newAdUrl.substring(0,newAdUrl.lastIndexOf("ord=")+4) + Math.round(Math.random()*Math.pow(10,7)).toString();
		rectangleAdObject.url = newAdUrl;
		
		$j("#ad-300x250").empty();
		var rectangle = new CoAdBrowser("ad-300x250");
		rectangle.updateWindow(rectangleAdObject.url, 300, 250);
	}
	
	/* Clipboard functions
	--------------- */
	this.initClipboardButtons = function(){
		var flashVersion = "9.0.115.0"; 
		var src ="/global/components/setClipboard.swf";

		var getUrlParams = {
			flashvars: { functionName: "MTVN.Player.setClipboardUrl" },
			params: {allowScriptAccess: "always", wmode: "transparent"},
			attributes: {}
		}
		
		var getEmbedParams = {
			flashvars: { functionName: "MTVN.Player.setClipboardEmbed" },
			params: {allowScriptAccess: "always", wmode: "transparent"},
			attributes: {}
		}

		swfobject.embedSWF(src, "getEmbedButton", "100%", "100%", flashVersion, "/global/scripts/swfobject_2_1/expressInstall.swf", getEmbedParams.flashvars, getEmbedParams.params, getEmbedParams.attributes);
	}
	
	
	this.setClipboardUrl = function(){
		return document.getElementById("videoUrl").value;
	}
	
	this.setClipboardEmbed = function(){
		return document.getElementById("embedTag").value;
	}
	
	/* Page modules	
	--------------- */
	this.loadPageModules = function(){
		
		pageModulesLoaded = true;
		MTVN.Player.getEmbedCode();

		if(MTVN.Player.episodeType=="fullEpisode"){
			this.initMultiGrid();
			var nowPlaying = "<span class='now-playing'>Now Playing</span>";
			if (MTVN.Player.channelId!='3') this.setVideoInfoHeader(nowPlaying);			
		}
		else if(MTVN.Player.episodeType=="afterShow"){
			MTVN.Player.getAfterShows();
			MTVN.Player.getFullEpisodes();
			MTVN.Player.getFranchiseLinks();
		}
		else if(MTVN.Player.episodeType=="webExclusive"){
			MTVN.Player.getPlaylist();
			MTVN.Player.getWebExclusives();
			MTVN.Player.getShowClips();			
			MTVN.Player.getFullEpisodes();
			MTVN.Player.getFranchiseLinks();			
		}
		else if(MTVN.Player.episodeType=="other"){
			MTVN.Player.getFranchiseLinks();			
		}
		else if (MTVN.Player.recommendationsObj.recsVideoType=="show"){
			MTVN.Player.getPlaylist();
			MTVN.Player.getWebExclusives();
			MTVN.Player.getShowClips();			
			MTVN.Player.getFullEpisodes();
			MTVN.Player.getFranchiseLinks();
		}		
		else {
			MTVN.Player.getPlaylist();
			MTVN.Player.getFranchiseLinks();			
			if(MTVN.Player.artist == undefined) MTVN.Player.getArtistVideos();

			if (MTVN.Player.videoType=="movies") {
				MTVN.Player.getTrailers();
				var nowPlaying = "Now Playing";
				this.setVideoInfoHeader(nowPlaying);
			}
		}
		if (MTVN.Player.feed.document!=undefined && MTVN.Player.feed.document.navInclude == "/sitewide/modules/header/geek/nav/index.jhtml") {}
		else if(MTVN.Player.internical!=undefined||MTVN.Player.videoType=="movies") MTVN.Player.getChannel();



		MTVN.Player.localModulesHandler();
	}
	
	this.setPlaylistHeader = function(){
		if(MTVN.Player.episodeObj.title != undefined || 
			MTVN.Player.artistObj.title != undefined ||
			MTVN.Player.movieObj.title != undefined ||
			MTVN.Player.personObj.title != undefined){
			
			var container = $j("#pageHeader");
			var header;
			var title;
			
			if(MTVN.Player.episodeObj.title != undefined) title = MTVN.Player.episodeObj.title;
			if(MTVN.Player.artistObj.title != undefined) title = MTVN.Player.artistObj.title;
			if(MTVN.Player.movieObj.title != undefined) title = MTVN.Player.movieObj.title;
			if(MTVN.Player.personObj.title != undefined) title = MTVN.Player.personObj.title;

			//title = title.replace(/ - /, " &#8250 ");
			if (this.getVideoInfoHeader()!=undefined) header = "<div>"+this.getVideoInfoHeader()+" > " + title + "</div>";
			else header = "<div>"+ title + "</div>";
			container.empty().append(header);
		}
	}

	this.getVideoInfoHeader = function(){
		var title;
        if(MTVN.Player.tvSeriesObj.franchise != undefined) title = MTVN.Player.tvSeriesObj.franchise + " ("+MTVN.Player.tvSeriesObj.season+")";
		else if(MTVN.Player.tvSeriesObj.title != undefined) title = MTVN.Player.tvSeriesObj.title;	
		if(MTVN.Player.tvSeriesObj.url != undefined) title = "<a href='"+MTVN.Player.tvSeriesObj.url+"'>"+title+"</a>";
		return title;
    }
	
	this.setVideoInfoHeader = function(nowPlayingText){    	
        var nowPlaying = "<div class='title-meta'><span>" + nowPlayingText + "</span></div>";
        if ($j("h1 .title-meta").length==1) $j("h1 .title-meta").remove();
        $j("h1").prepend(nowPlaying);
    }	

	this.getEmbedCode = function(){
		if(doLoadFeed && $j("#embedTag").is("*")){
			feedUrlParams.vid = MTVN.Player.vid;
			$j.ajax({
				url: "/global/music/videos/json/embedCode.jhtml",
				data: feedUrlParams,
				dataType: "json",
				success: function(data){
					var embedForm = $j("#embedTag");
					if ((typeof(data.embedCode) == "string") && (embedForm != null)) {
						embedForm.get(0).value = data.embedCode;
					} else {
						embedForm.get(0).value = "";
					}
				}
			});
		}
	}

	this.getFullEpisodes = function(target){
		if(target==undefined) target = "fullEpisodes";
		MTVN.Player.getFullEpisodeContent(target, "/global/music/videos/ajax/full_episodes.jhtml");
	}
	
	this.getAfterShows = function(target){
		if(target==undefined) target = "afterShows";
		MTVN.Player.getFullEpisodeContent(target, "/global/music/videos/ajax/after_shows.jhtml");
	}
	
	this.getWebExclusives = function(target){
		if(target==undefined) target = "webExclusives";
		MTVN.Player.getFullEpisodeContent(target, "/global/music/videos/ajax/web_exclusives.jhtml");
	}
	
	this.getShowClips = function(target){
		if(target==undefined) target = "showClips";
		MTVN.Player.getFullEpisodeContent(target, "/global/music/videos/ajax/show_clips.jhtml");
	}		

	this.initMultiGrid = function() {		
		var grid = MTVN.Utils.Cookies.read(multiGridViewCookie);
		if (grid=="false") MTVN.Player.toggleGrid(false);
		else MTVN.Player.toggleGrid(true);
		$j("#gridToggle").html('<span class="gridtoggle"><a href="#" onClick="javascript:MTVN.Player.toggleGrid(true); return false;">Grid</a></span> | <span class="listtoggle"><a href="#" onClick="javascript:MTVN.Player.toggleGrid(false); return false;">List</a></span><span id="Module2_AjaxLoader"></span>');
	}

	this.getMultiGridModule_fullEpisodeDetailPage = function(){
		
		var container = $j("#multiGridModule");
		var gridParams = {};
		$j("#Module2_AjaxLoader").css("display","block");
		if(MTVN.Player.tvSeriesObj.seriesId != undefined){			
			gridParams.seriesID = MTVN.Player.tvSeriesObj.seriesId;
			if(MTVN.Player.channelId != undefined) gridParams.channelID = MTVN.Player.channelId;  
			if(MTVN.Constants.playerBaseUrl != "") gridParams.playerBaseUrl = MTVN.Constants.playerBaseUrl;			
			
			$j.get("/global/music/videos/ajax/multiGridModule_fullEpisodeDetailPage.jhtml", gridParams, function(data){
				container.html(data);
				$j("#Module2_AjaxLoader").css("display","none");   
                $j("#dynaVidListingPopulate").css("display","none");				
			},"html");
		}
	}
    
    this.toggleGrid = function(grid) {	
		
    	var listcontainer = $j("#dynaVidListingPopulate");
    	var gridcontainer = $j("#multiGridModule");
    	if (!grid) {
			if (listcontainer.children().length==0) MTVN.Player.getVideoListModule_fullEpisodeDetailPage();
			else gridcontainer.css("display","none");
           	listcontainer.css("display","block");
			MTVN.Utils.Cookies.create(multiGridViewCookie, false, 365);
		}
        else {
			if (gridcontainer.children().length==0) MTVN.Player.getMultiGridModule_fullEpisodeDetailPage();
			else listcontainer.css("display","none");
			gridcontainer.css("display","block");
			MTVN.Utils.Cookies.create(multiGridViewCookie, true, 365);			
        }
    } 
    
	this.getVideoListModule_fullEpisodeDetailPage = function(){
		var container = $j("#dynaVidListingPopulate");
		var gridParams = {};        
		$j("#Module2_AjaxLoader").css("display","block");
		if(MTVN.Player.tvSeriesObj.seriesId != undefined){
			gridParams.seriesID = MTVN.Player.tvSeriesObj.seriesId;
			if(MTVN.Player.channelId != undefined) gridParams.channelID = MTVN.Player.channelId;
			//$j.get("/global/music/shows/ajax/videosByFranchiseHTML.jhtml", gridParams, function(data){
			$j.get("/global/music/modules/video/shows/", gridParams, function(data){
				container.html(data);
				$j("#Module2_AjaxLoader").css("display","none");   
                $j("#multiGridModule").css("display","none");
				MTVN.VidPopup.init(true);
			},"html");
		}
	}	
	
	this.getFullEpisodeContent = function(target, url){
		var container = $j("#"+target);
		if(container.is("*") && MTVN.Player.id != undefined){
			container.css("display","block");
					
			var fullEpParams = {};
			fullEpParams.id = MTVN.Player.id;
			if(MTVN.Constants.playerBaseUrl != "") fullEpParams.playerBaseUrl = MTVN.Constants.playerBaseUrl;
			$j.get(url, fullEpParams, function(data){
				container.html(data);
				if(target=="playlist"){
					MTVN.Player.handlePlaylistAutoScroll("#id"+MTVN.Player.id, false);
				}
				else{
					MTVN.UI.initScrollingModules();
				}
			});
		}
	}

    this.loadPlayerWidgets = function (){
		var container = $j("#widgetContainer");
		if(container.is("*") && MTVN.Player.videoUri != undefined){
			//container.css("display","block");

            if (typeof(gigya_chat_conf) == 'undefined') setTimeout('MTVN.Player.initFacebookLike()',3000);

			$j(".meta-list.usage").append('<div class="fluxWidget delay-load" id="wStatistics"><code class="hide"><!--{"widget": "Statistics", "args":{"containerId":"wStatistics", "contentUri": "' + MTVN.Player.videoUri + '", "ratings_title": "Video", "hide_titles": true}}--></code></div>');
			container.append('<ul class="meta-list rate"><li><div class="hard-corners"><div class="fluxWidget delay-load" id="wRate"><code class="hide"><!--{"widget": "Rate", "args":{"containerId":"wRate", "contentUri": "' + MTVN.Player.videoUri + '"}}--></code></div></div></li></ul>');

            container.parent().append('<div id="videoCtrls" class="group"><ul class="vid-ctrls"><li><a href="#" class="help" onclick="MTVN.Player.launchHelp(); return false;">Help With Video Player</a></li></ul></div>');
            $j("#more-info").before('<div id="more-info-bt"><a href="#" onClick="javascript\:document\.getElementById(\'more-info\')\.style\.display=\'block\'\; document\.getElementById(\'more-info-bt\')\.style\.display=\'none\'; return false\;">More Info &#187;</a></div>');
			$j("#more-info").append('<div id="hide-info-bt"><a href="#" onClick="javascript\:document\.getElementById(\'more-info\')\.style\.display=\'none\'\; document\.getElementById(\'more-info-bt\')\.style\.display=\'block\'\; return false\;">&#171; Less Info</a></div>');

			$j(".group-c").append('<div id="series"> </div><div id="customPromo"> </div><div id="rssPartner"> </div>');

            var params = {videoUri: MTVN.Player.videoUri};
			$j.get("/global/music/videos/lite/desktop/includes/shareWidget.jhtml", params, function(data){
				container.prepend(data);

            });

			//move esi comments into group ab from the base page
            $j("#esiCommentsWrap").appendTo($j(".group-ab.dynGroup"));

			//insert empty placeholder courousel divs
			$j(".group-ab.dynGroup").prepend('<div id="playlist"> </div> <div id="gridToggle"> </div> <div id="multiGridModule"> </div> <div id="dynaVidListingPopulate"> </div> <div id="fullEpisodes"> </div> <div id="vidRecs"> </div> <div id="afterShows"> </div>  <div id="webExclusives"> </div> <div id="showClips"> </div> <div id="artistVideos"> </div> <div id="relatedPlaylists"> </div> <div id="trailers"> </div> <div id="channel"> </div>');

			//insert flux comment widget markup
            $j(".group-ab.dynGroup").append('<div class="mdl comments-wrapper"><div class="h-wrap group"><h2 class="h-sub2 group"><span>Comments</span></h2></div><div class="fluxWidget delay-load" id="wComments"><code class="hide"><!--{"widget": "Comments", "args":{"containerId":"wComments", "contentUri": "' + MTVN.Player.videoUri + '"}}--></code></div>');

			MTVN.UI.InView.register($j("#rssPartner"), function() {
				var rsscontainer = $j("#rssPartner");
				if(rsscontainer.is("*")){
					$j.get("/global/music/modules/rssPartner/?rssModuleConfig=/content/rssPartner/videos/config.jhtml", {}, function(rssPartner){
						rsscontainer.append(rssPartner);
					});
				}
			});
		}
	}
	
	this.getPlaylist = function(){
		if(MTVN.Player.id != undefined || MTVN.Player.artist != undefined || MTVN.Player.movieId != undefined || MTVN.Player.personId != undefined || MTVN.Player.category != undefined) {
			$j("#playlist").css("display","block")
			MTVN.UI.InView.register($j("#playlist"), function() {
			
				var container = $j("#playlist");
				if(container.is("*")){
					var playlistParams = {};
						
						if(MTVN.Player.id != undefined) playlistParams.id = MTVN.Player.id;
						else if(MTVN.Player.artist != undefined) {
							playlistParams.artist = MTVN.Player.artist;
							if (MTVN.Player.artistType != undefined)
								playlistParams.artistType = MTVN.Player.artistType;
						}
						else if(MTVN.Player.movieId != undefined) playlistParams.movieId = MTVN.Player.movieId;
						else if(MTVN.Player.personId != undefined) playlistParams.personId = MTVN.Player.personId;
						else if(MTVN.Player.category != undefined) playlistParams.category = MTVN.Player.category;
						if(MTVN.Player.sort != undefined) playlistParams.sort = MTVN.Player.sort;				
						if(MTVN.Player.tvSeriesObj.seriesId != undefined) playlistParams.seriesID = MTVN.Player.tvSeriesObj.seriesId;
						if(MTVN.Player.channelId != undefined) playlistParams.channelID = MTVN.Player.channelId;				
						if(MTVN.Constants.playerBaseUrl != "") playlistParams.playerBaseUrl = MTVN.Constants.playerBaseUrl;

						$j.get("/global/music/videos/ajax/playlist.jhtml", playlistParams, function(data){
							container.empty().append(data);
							MTVN.Player.handlePlaylistAutoScroll("#vid" + MTVN.Player.vid, true);

                            //handle embeded script
                            var scriptStart = data.indexOf('<script type="text/javascript">');
                            if (scriptStart!=-1) {
								var scriptBody = data.indexOf(">", scriptStart);
								var scriptEnd = data.indexOf("<", scriptBody);
								var script = data.substring(scriptBody+1, scriptEnd);
								eval(script);
                            }
							MTVN.Player.getRecommendations();

							//Immersive 360 Player
							if(MTVN.Player.id == "1627391")
							{
							    obj = $j('#playlist ol li');
								obj.each(function(){
									$j('div a').click(function () {
										getFlashMovie("embeddedPlayer").closeStreams();
										});
								
								});	
							}
							//End 360 Player
						});
	
				}
			
			});
		}	
	}
	
	this.browseVideoViewAll = function(target){
		var container = $j("#"+target);
//		var mask_h = $j(".browsevideo_mask_h").height();
		container.attr("box_h", container.height());
		var mask_h = 240;
		var mask_h_css = mask_h+"px";
		if (mask_h<(container.height()+10)) {
			container.prepend('<a class="trigger" href="javascript:void(0)">Collapse</a>');
			var clickcontainer = $j("#"+target+" .trigger");
			clickcontainer.toggle(function(){
					var close_height = container.attr("box_h") + "px";

					container.animate({"height": mask_h_css}, {duration: "slow" });
					$j(this).text("View All");										   
				}, function () {
					var open_height = container.attr("box_h") + "px";
					container.animate({"height": open_height}, {duration: "slow" });
					$j(this).text("Collapse");					
			});
		}
	}
	
	this.handlePlaylistAutoScroll = function(activeId, showPosition){
		MTVN.UI.initScrollingModules();
		
		var activeSlat = $j(activeId);
		var parentSlat = activeSlat.parent();		
		var activePage = $j('#playlist ol').index(parentSlat);
		if(activeSlat.is("*")){
			var previousSlats = activeSlat.prevAll();
			var position = activePage*4 + previousSlats.length+1;				

			// Show Active Slat
			activeSlat.find("span.playlist-count").prepend("<span class='now-playing'>NOW<br/>PLAYING<br/></span>");
			activeSlat.find("span.playlist-count").css('width','130px');
			activeSlat.find("span.playlist-count").css('height','95px');
			activeSlat.addClass("active");
			
			// Goto Active Page
			var pagecoord = -1*(activePage*($j("#playlist div.pages").find('ol').width()+10));
			MTVN.UI.Paginate.page2($j('#playlist p.sm a'),null,activePage+1);
						
			var total = ($j("#playlist li").length)-($j("#playlist .pagination li").length); //subtract pagination LI count
			var nowPlayingText = "<span class='now-playing'>Now Playing</span>";
			if(showPosition) nowPlayingText += " Clip " + position + " of " + total;
			this.setVideoInfoHeader(nowPlayingText);
						
			var activeTop = 0;
			previousSlats.each(function(i){
				var li = $j(this);
				activeTop += li.outerHeight(true);
			});
		}
	}
	
	this.getArtistLinks = function(){
		MTVN.UI.InView.register($j("#artistLinks"), function() {
			var container = $j("#artistLinks");
			container.empty();
			for(var i=0; i < MTVN.Player.artists.length; i++){
				if(container.is("*")){
					$j.get("/global/music/videos/ajax/artist_links.jhtml", {artist: MTVN.Player.artists[i]}, function(data){
						container.append(data);
					});
				}
			}
		
		});
	}

    this.getArtistVideos = function(){
    	MTVN.UI.InView.register($j("#artistVideos"), function() {
			var container = $j("#artistVideos");
			container.empty();			
			var params = {vid: MTVN.Player.vid};
			if(MTVN.Constants.playerBaseUrl != "") params.playerBaseUrl = MTVN.Constants.playerBaseUrl;
			$j.get("/global/music/videos/ajax/artist_videos.jhtml", params, function(data){
				container.append(data);
			});				
   		});
	}
	
	this.getRelatedPlaylists = function(){
	
		MTVN.UI.InView.register($j("#relatedPlaylists"), function() {
			if(MTVN.Player.videoType=='music' || MTVN.Player.movieId != undefined){
				var container = $j("#relatedPlaylists");
				if(container.is("*")){
					var params = {vid: MTVN.Player.vid};
					if(MTVN.Player.movieId != undefined) params = {movieId: MTVN.Player.movieId};
					if(MTVN.Constants.playerBaseUrl != "") params.playerBaseUrl = MTVN.Constants.playerBaseUrl;
					$j.get("/global/music/videos/ajax/related_playlists.jhtml", params, function(data){
						container.append(data);
						MTVN.UI.initScrollingModules();
					});
				}
			}
		
		});
		
		
	}  
	
	this.getTrailers = function(){
		MTVN.UI.InView.register($j("#trailers"), function() {
			var container = $j("#trailers");
			if(container.is("*")){
				$j.get("/global/music/modules/trailers/index.jhtml", function(data){
					container.empty().append(data);
				});
				
				/* $j.get("/global/music/videos/ajax/trailers.jhtml", function(data){
					container.empty().append(data);
				});*/
			}					
		});
	}	


	
	this.getChannel = function(){
		MTVN.UI.InView.register($j("#channel"), function() {
			var container = $j("#channel");
			if(container.is("*")){
				var playerUrl = "name=shows";	
				if(channelOverride != undefined) playerUrl = "name=" + channelOverride;
				else if(MTVN.Player.channelObj.playerUrl != undefined) playerUrl = MTVN.Player.channelObj.playerUrl;
				else if(MTVN.Player.gateway != undefined) playerUrl = "name=" + MTVN.Player.gateway;
				
				if(MTVN.Constants.playerBaseUrl != "") playerUrl +=  "&playerBaseUrl=" + MTVN.Constants.playerBaseUrl;

				$j.get("/global/music/videos/ajax/channel.jhtml?"+playerUrl, function(data){
					container.empty().append(data);
				});
			}			
		
		});
	}
	
	this.getFranchiseLinks = function(){
		var container = $j("#franchiseLinks");
		if(container.is("*")){
			if(MTVN.Player.tvSeriesObj.seriesId != undefined){
				// get series links
				var params = {};
				
				if(MTVN.Player.tvSeriesObj.seriesId != undefined) params.seriesId = MTVN.Player.tvSeriesObj.seriesId;
				if(MTVN.Player.channelId != undefined) params.channelId = MTVN.Player.channelId;
				if(window.location.hash.length > 0 && window.location.hash.indexOf("id=") > -1) params.cid = window.location.hash.substring(1).split("=")[1];
				
				container = $j("#seriesLinks");
				$j.get("/global/music/videos/ajax/series_links.jhtml", params, function(data){
					container.empty().append(data);
				});
			}
		}
	}

	this.getRecommendations = function(){
		var container = $j("#vidRecs");
		if(container.is("*")){
			if((MTVN.Player.vid != undefined) && (MTVN.Player.contentTypeId == 1 || MTVN.Player.contentTypeId == 2 || MTVN.Player.contentTypeId == 3 || MTVN.Player.contentTypeId == 4 || MTVN.Player.contentTypeId == 6 || MTVN.Player.contentTypeId == 7 || MTVN.Player.contentTypeId == 8 || MTVN.Player.contentTypeId == 9 || MTVN.Player.contentTypeId == 10 || MTVN.Player.contentTypeId == 14 || MTVN.Player.contentTypeId == 18 || MTVN.Player.contentTypeId == 21 || MTVN.Player.contentTypeId == 31)){
			$j.getScript("/global/apps/recommendations/videos.jhtml");
            }
		}
	}

	this.launchPopout = function(id) {
		var url = "/global/music/videos/popout/?";
		var params = new Array();

		if(MTVN.Player.name!=undefined) params.push("name=" + MTVN.Player.name);
		if(MTVN.Player.id!=undefined) params.push("id=" + MTVN.Player.id);
		if(MTVN.Player.artist!=undefined) {
			params.push("artist=" + MTVN.Player.artist);
			if(MTVN.Player.artistType!=undefined)
				params.push("artistType=" + MTVN.Player.artistType);
		}
		if(MTVN.Player.movieId!=undefined) params.push("movieId=" + MTVN.Player.movieId);
		if(MTVN.Player.personId!=undefined) params.push("personId=" + MTVN.Player.personId);
		if(MTVN.Player.category!=undefined) params.push("category=" + MTVN.Player.category);
		if(MTVN.Player.sort!=undefined) params.push("sort=" + MTVN.Player.sort);
		if(MTVN.Player.vid!=undefined) params.push("vid=" + MTVN.Player.vid);
		//params.push("vid=" + MTVN.Player.vid);
		
		for(var i=0; i < params.length; i++){
			url += params[i];
			if(i < params.length-1) url += "&";
		}
				
		controller.player.pause();
		window.open(url,"popout","width=768,height=463,resizable=1");
	}
	
	this.launchHelp = function(){
		window.open("/overdrive/assets/includes/help.jhtml","help","width=640,height=860,resizable=1,scrollbars=1");
	}

	this.launchHD = function(url, w, h){
		linkEvent("", "HD_Download_overdrive", "o");
		controller.player.pause();

		var hdWindow = window.open("/global/music/videos/popout/hd.html?movUrl=" + escape(url) + "&width=" + w + "&height="+ h, "", "status=0,menubar=0,resizable=1,width=" + w + ",height=" + h);
		hdWindow.focus();
	}
	
	this.launchPlayerHD = function(vid){
		var screenW= screen.width;
		
		if (screenW >= 1280 && screenW < 1780){
		
			var videoWidth = 1280;
			var videoHeight = 720 + 31;
			
		} else if (screenW >= 1780 && screenW < 1920){
		
			var videoWidth = 1780;
			var videoHeight = 956 + 31;
			
		} else if (screenW >= 1920){
		
			var videoWidth = 1920;
			var videoHeight = 1080 + 31;
			
		} else {
		
			var videoWidth = screenW;
			var videoHeight = ((screenW/16)*9) + 31;
		}
		
		linkEvent("", "HD_Download_overdrive", "o");
		controller.player.pause();
		//document.write(unescape(videoWidth));
		var hdWindow = window.open("/global/music/videos/popout/"+vid, "", "status=0,menubar=0,resizable=1,width=" + videoWidth + ",height=" + videoHeight);
	
		hdWindow.focus();
	}

	
	this.vidlist_high = function(obj) {
		obj.className = 'vidlist_high';
	}
	
	this.vidlist_dehigh = function(obj){
		obj.className = 'vidlist_dehigh';
	}
	
	this.vidclick = function(url){
		document.location.href = url;
	}	
	
	/* debugging
	--------------- */
/*	this.output = function(){
		if($j("#output").is("*")){
			$j("#output").empty();
			$j("#output").append("getContinuousPlayValue = " + MTVN.Player.getContinuousPlayValue() + "<br/>");
			$j("#output").append("getSuspendContinuousPlay = " + MTVN.Player.getSuspendContinuousPlay() + "<br/>");
			$j("#output").append("------<br/>");
			$j("#output").append("getContinuousPlayOverride = " + MTVN.Player.getContinuousPlayOverride() + "<br/>");
		}
		else{
			$j("body").append('<div id="output" style="position:absolute;top:30px;left:0;background:#fff;"></div>');
			MTVN.Player.output();
		}
	}*/
}

MTVN.initArray.push(MTVN.Player.init);
//MTVN.initArray.push(MTVN.Utils.Clipboard.init);

// reassign functions
var resizePlayer = MTVN.Player.resize;
var mtvnSetCoad = MTVN.Player.setCoad;


