/**
		mediaplayer.js
		The Hot Hits Mediaplayer

		Created by Victor Nguyen
		Copyright 2009 mts. All rights reserved.
		
		Stores mediaplayer settings and functions specific to the The Hot Hits website.
		Integrates with movideo tools to parse media info formats the movideo player will recogniiize. Warren G.
		Dependencies: http://apps.v2.movideo.com/player/js/player.js , swfobject.js
*/

var mediaplayer = {
	
	Version: '3.0', // new movideo player
	Syndicated: false, // set to true by mediaplayer.syndicated.settings.js
	
	MediaPlayer: {
		ID: 'mediaPlayer',
		CONTAINER_ID: 'mpWrap', // wrapper div around entire mediaplayer
		Active: false,
		width: 630,
		height: 470,
		embed: function () {
			this.Active = true;
			return movideoplayer.embedPlayer(this.ID, mediaplayer.Vars.alias, mediaplayer.Vars.apiKey, this.width, this.height, mediaplayer.Vars); 
		}
	},
	
	ArtistPanel: {
		ID: 'artistPanel',
		SWF_URL: '/flash/mediaplayer/information_panel.swf',
		width: 630,
		height: 156,
		embed: function (movideoPlayerId) {
			return swfobject.embedSWF(this.SWF_URL, this.ID, this.width, this.height, mediaplayer.CommonFlashSettings.min_flash_ver, mediaplayer.CommonFlashSettings.expressinstall_url, { playerId:movideoPlayerId }, mediaplayer.Params, null);
		}
	},
	
	PlaylistPanel: {
		ID: 'playlistPanel',
		SWF_URL: '/flash/mediaplayer/playlist_panel.swf',
		width: 310,
		height: 366,
		embed: function (movideoPlayerId) {
			return swfobject.embedSWF(this.SWF_URL, this.ID, this.width, this.height, mediaplayer.CommonFlashSettings.min_flash_ver, mediaplayer.CommonFlashSettings.expressinstall_url, { playerId:movideoPlayerId }, mediaplayer.Params, null);
		}
	},
	
	Vars: {
		apiKey: 'movideoTheHotHits',
		// alias: null,
		// mediaId: null,
		// playlistId: null,
		// playlistIndex: null,
		// channelId: null,
		// Search tag must be a String, not an Array since ',' characters in the 'searchTags'
		// property will be split to form an array. 'searchTag' suffers no such fate
		searchTag: ''
	},
	
	Params: {
		menu: 'false',
		allowScriptAccess: 'always',
		allowFullScreen: 'true',
		bgcolor: '#000000',
		wmode: 'opaque',
		quality: 'high'
	},
	
	CommonFlashSettings: {
		min_flash_ver: '9.0.0',
		expressinstall_url: '/flash/mediaplayer/expressInstall.swf',
		bgcolor: '#000000'
	},
	
	Popup: {
		PATH: '/pop-media-player',
		width: 970,
		height: 646,
		x: 40,
		y: 40
	},
	
	Ads: {
		initial_src: '/flash/syn_island_start.html',
		
		Island: {
			ID: 'mediaAd',
			CONTAINER_ID: 'mpIsland',
			PATH: '/action/mediaplayer/island?zone=media_player',
			width: 300,
			height: 250
		},
		
		Leaderboard: {
			ID: 'mediaAdLeaderboard',
			CONTAINER_ID: 'leaderboard',
			PATH: '/action/mediaplayer/leaderboard?zone=media_player',
			width: 728,
			height: 90
		},
		
		setup: function (id, container_id, width, height) {
			var iframe = '<iframe src="' + this.initial_src + '" width="' + width + '" height="' + height + '" marginheight="0" marginwidth="0" frameborder="0" scrolling="no" name="' + id + '" id="' + id + '" style="background-color:' + mediaplayer.CommonFlashSettings.bgcolor + '"></iframe>';
			var container = document.getElementById(container_id);
			if (container) { container.innerHTML = iframe; }
		}
	},
	
	
	
	
	/**
		@ INITIALISE MEDIAPLAYER
			Tests if media_player.jsp is rendered on page (which means the user has played media via a link), then sets up vars and embeds
	*/
	init: function () {
		if (document.getElementById(mediaplayer.MediaPlayer.CONTAINER_ID)) {
			this.setupVarsFromPage();
			this.embed();
		}
	},
	
	
	/**
		@ EMBED MEDIAPLAYER
			Performs swfobject embeds of each Flash component and ad containers
	*/
	embed: function () {
		this.setupAliases();
		
		document.getElementById(this.MediaPlayer.CONTAINER_ID).style.visibility = 'visible';
		
		// mediaplayer panels
		var playerId = this.MediaPlayer.embed().playerId; // embeds mediaplayer component and assigns its playerId to var
		this.MediaPlayer.ID = playerId;
		this.PlaylistPanel.embed(playerId);
		this.ArtistPanel.embed(playerId);

		// ad containers
		this.Ads.setup(this.Ads.Island.ID, this.Ads.Island.CONTAINER_ID, this.Ads.Island.width, this.Ads.Island.height);
		this.Ads.setup(this.Ads.Leaderboard.ID, this.Ads.Leaderboard.CONTAINER_ID, this.Ads.Leaderboard.width, this.Ads.Leaderboard.height);
		
		window.addEvents({ 'beforeunload': function () { mediaplayer.cleanUp(); } });
	},
	
	
	/**
		@ SETUP VARS FROM PAGE
			Processes and applies vars in param string
			Previously using mediaplayerVariables var in media_player.jsp, now using param string has this only needs to be set if player is loaded with a page load (i.e. not inline)
	*/
	setupVarsFromPage: function () {
		// parsing mediaplayer url vars
		var query = window.location.search.substring(1); // Get query string
		var pairs = query.split("&");
		var numberoneYear, numberoneMonth, numberoneDay;
		
		for (var i=0;i<pairs.length;i++) {
			var pair = pairs[i].split("="); 
			switch (pair[0]) {
				case 'movideo_m':
				case 't':
					if ((typeof mediaId == 'undefined') || (!mediaId) || (mediaId == '')) {
						this.Vars.mediaId = pair[1].split('.')[0];
					} else {
						this.Vars.mediaId = mediaId;
					}
					break;
				case 'movideo_pi':
					this.Vars.playlistIndex = pair[1];
					break;
				case 'p':
					this.Vars.playlistIndex = pair[1].split('.')[1];
				case 'movideo_p':
					if ((typeof playlistId == 'undefined') || (!playlistId) || (playlistId == '')) {
						this.Vars.playlistId = pair[1].split('.')[0];
					} else {
						this.Vars.playlistId = playlistId;
					}
					break;
				case 'i':
					this.Vars.playlistId = pair[1].split('.')[0];
					this.Vars.playlistIndex = pair[1].split('.')[1];
					break;
				case 'a':
					this.Vars.searchTag = 'mcm:artistid='+pair[1].split('.')[0];
					break;
				case 'clientid':
					// we don't. they will be setup as diff players in the admin
					// clientid needs to be converted to key+alias
					break;
				case 'n':
					this.Vars.mediaId = pair[1].split('.')[1];
					break;
				case 'year':
					numberoneYear = pair[1];
					this.Vars.searchTag = 'mcm:numberone_week=' + pair[1] + ',*';
					break;
				case 'searchYear':
					numberoneYear = pair[1];
					this.Vars.searchTag = 'mcm:numberone_week=' + pair[1] + ',*';
					break;
				case 'month':
					numberoneMonth = pair[1];
					break;
				case 'day':
					numberoneDay = pair[1];
					break;
			}
		}
		
		// apply numberone week
		if (numberoneYear && numberoneMonth && numberoneDay) {
			_extendDateObj();
			this.Vars.searchTag = 'mcm:numberone_week='+_getNumberOnesWeek(numberoneYear, numberoneMonth, numberoneDay);
		}
		
		// get number ones week value
		function _getNumberOnesWeek (year, month, day) {
			var n1Date = new Date(year, month, day);
			return n1Date.getWeek(1);
		}

		function _extendDateObj () {
			Date.prototype.getWeek = function (dowOffset) {
				/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.meanfreepath.com */
				dowOffset = typeof(dowOffset) == 'int' ? dowOffset : 0; //default dowOffset to zero
				var newYear = new Date(this.getFullYear(),0,1);
				var day = newYear.getDay() - dowOffset; //the day of week the year begins on
				day = (day >= 0 ? day : day + 7);
				var daynum = Math.floor((this.getTime() - newYear.getTime() - (this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
				var weeknum;
				//if the year starts before the middle of a week
				if (day < 4) {
					weeknum = Math.floor((daynum+day-1)/7) + 1;
					if (weeknum > 52) {
						nYear = new Date(this.getFullYear() + 1,0,1);
						nday = nYear.getDay() - dowOffset;
						nday = nday >= 0 ? nday : nday + 7;
						/*if the next year starts before the middle of
						the week, it is week #1 of that year*/
						weeknum = nday < 4 ? 1 : 53;
					}
				} else {
					weeknum = Math.floor((daynum+day-1)/7);
				}
				return weeknum;
			};
		}
		
	},
	
	
	/**
		@ SETUP ALIASES
			Sets up and applies aliases based on mcm media site zones
	*/
	setupAliases: function () {
		if (this.Syndicated == true) {
			this.Vars.alias = 'syndicated-player';
			this.Vars.apiKey = 'movideo' + _getSyndicatedClient();
		} else {
			this.Vars.alias = _getPlayerAlias(TrackingVars.zone);
		}
		
		/**
			@ GET SYNDICATED PLAYER CLIENT ALIAS
				Returns the client alias from the syndicated player URL
				e.g.
					www.take40.com/player/news
					will return 'News'
		*/
		function _getSyndicatedClient () {
			var url = window.location.href;
			
			// getting yahoo in player/yahoo
			var pairs = url.split('/');
			var alias = pairs[pairs.length-1];
			
			// getting yahoo in player/yahoo?t=1231.3
			var pairs = alias.split('?');
			var alias = pairs[0];
			
			alias = alias.substring(0,1).toUpperCase() + alias.substring(1);
			return alias;
		}
		
		/**
			@ GET PLAYER ALIAS FROM PAGE
			@ zone [String] page zone according to take40/hothits. These zones are defined in tiles.xml and stored on a global TrackingVars var in main_layout.jsp
				Converts page zone to player alias setup in movideo platform
		*/
		function _getPlayerAlias (zone) {
			var alias;
			switch (zone) {
				case 'home':
					alias = 'homepage';
					break;
				case 'music_library':
					alias = 'music-library';
					break;
				case 'hothitschart':
					alias = 'chart';
					break;
				case 'music_charts':
					alias = 'chart';
					break;
				case 'new_music':
					alias = 'newmusic';
					break;
				case 'playlists':
					alias = 'playlists';
					break;
				case 'pop-out-default':
					alias = 'pop-out-default';
					break;
				case 'pop-out-chart':
					alias = 'pop-out-chart';
					break;
				default:
					alias = 'music-library';
			}
			return alias;
		}
		
		// interviews - no interviews zone? change zone? does this affect analytics?
	},
	
	
	
	/**
		@ REFRESH ADS
		@ infostring [String] param string generated from Flash to pass to ad request
			e.g. 'genreName0=Pop;artistid=3667;mediaid=86419;label=Universal;mediatype=video;propertyid=28784;clientid=0;'
			Refreshes the island and leaderboard iframe srcs with ad request paths
	*/
	refreshIslandBanner: function (infostring) {
 		var ord = Math.floor((Math.random()*13756)*345);
		
		var island = document.getElementById(mediaplayer.Ads.Island.ID);
	 	if (island) { island.src = mediaplayer.Ads.Island.PATH + '&ord=' + ord + '&keyvalues=' + infostring; }
	
		var leaderboard = document.getElementById(mediaplayer.Ads.Leaderboard.ID);
		if (leaderboard) { leaderboard.src = mediaplayer.Ads.Leaderboard.PATH + '&ord=' + ord + '&keyvalues=' + infostring; }
	},
	
	
	
	/**
		@ OPEN POPUP PLAYER
		@ propertyid [String] media param passed as string e.g. 't=12345.3'
			Run when user clicks 'Pop-out player' from inside the mediaplayer
	*/
	popMediaPlayerFlash: function (propertyid) {
		var url = this.Popup.PATH + '?' + propertyid;
		var specs = 'toolbar=0,menubar=0,resizable=0,titlebar=0,status=no,scrollbars=0,location=0,left=' + this.Popup.x + ',top=' + this.Popup.y + ',width=' + this.Popup.width + ',height=' + this.Popup.height;
		popup = window.open(url, 'mediaPlayer', specs);
		popup.focus();
	},
	
	
	
	/**
		@ CLEAN UP
			Removes Flash elements and cleans up the mediaplayer area as the user leaves the page.
			This function solves the 'mootools (1.11) + EI on mediaplayer + IE7' problem.
			Fires on 'beforeunload' -- just before the browser leaves the window (via refresh or link).

			We do this to prevent problems caused by conflicts with mootools' garbage collector, Flash's
			unloading of externalinterface callbacks from the mediaplayer and IE7. Yes, all three
			conditions need to be met.
			
			Here are some URLs that help explain this phenomenon:
				http://bugs.adobe.com/jira/browse/FP-529
				http://flowplayer.org/forum/8/10632
				http://www.fusioncharts.com/forum/Topic1785-23-1.aspx
				http://swfupload.org/forum/generaldiscussion/809		
	*/
	cleanUp: function () {
		// remove flash <object>'s
		var els = document.getElementsByTagName('object');
		if (els && els.length) {
			for (var i=els.length-1; 0<=i; i--) {
				var parent = els[i].parentNode;
				parent.removeChild(els[i]);
			}
		}
		
		// remove wrapper, and set styles to parent to prevent visual jumble
		var wrapper = document.getElementById(this.MediaPlayer.CONTAINER_ID);
		if (wrapper) {
			var parent = wrapper.parentNode;
			parent.style.height = '626px';
			parent.style.background = '#000000';
			parent.removeChild(wrapper);
		}
	}
	
};



window.addEvents({ 'domready': function () { mediaplayer.init(); } });