/**
 *	DDC Video Player
 *	Copyright (c) 2008 Dealer.com.
 *
 *	Created: blah, James Vivian
 *	Modified: 07.Feb.2008, Randy Morey
 *	Modified: 02.Apr.2008, Jamie Addessi
 *	Modified: 12.May.2008, Randy Morey - (132) changed namespace of video player and video player methods
 *	Modified: 14.Oct.2008, James Vivian - (65) add optional override to generated videoId via playerId param
 *	Modified: 15.Oct.2008, Randy Morey - (all) refactored for DDC JS standards compliancy and JSLint validation
 *	Modified: 21.Oct.2009, Roger Kappe - (178) added ability to autplay video on .ddcPlayer-holder elements by setting an attribute 'autoplay' to 'true' or 'false', if attribute is missing, a default value of 'false' will be used
 *
 * @param Object params An object literal containing key/value pairs used by the embedVideoPlayer function.
 * @option number width Required height in pixels of video player
 * @option number height Required width in pixels of video player
 * @option boolean showPlayList If true, enables a YouTube-like listing of other videos listed in playlistXmlPath.
 * @option string swfPath Path to movie player.
 * @option string swfId Id to give the movie player html element. - deprecated
 * @option string playerId Id to override default generated id on movie player html element.
 * @option boolean allowFullScreen - deprecated, flash player will automatically show the full-screen button if supported
 * @option boolean autoPlay If true, autoplay movie.
 * @option string playlistXmlPath Path to XML file listing video assests for video player.
 * @option string videoUrl URL where video is located; only used if a playlistXmlPath is not provided.
 * @option string overlayPath Path to video overlays; if playlistXmlPath is located at "http://videos.dealer.com/vehicles/"
 *							  or "video/media/vehicles/", a overrideable default overlayPath will be provided
 * @option boolean backgroundLoad Preloads video data.
 * @option sting divName Id of target div to append video player.
 * @option function success Callback function executed on completion of script embedding script.
 */
(function () {
	var window = this,
		$ = window.jQuery,
		DDC = (window.DDC = (window.DDC || {})),
		reqMajVer = 9,		// Major version of Flash required
		reqMinVer = 0,		// Minor version of Flash required
		reqRev = 0,			// Minor version of Flash required
		alt = 'This content requires the Adobe Flash Player Version ' +
			reqMajVer,
		// version of the video player, increment to force an update to users
		swfVersion = '1.8.4',
		videoStarted = function (swfId, playlistIndex, videoUrl) {
			var i;
			
			for (i = 0; i < DDC.embedVideoPlayer.videos.length; i++) {
				try {
					// when a video is started, stop all videos on the page
					// except the one calling
					if (DDC.embedVideoPlayer.videos[i] !== swfId) {
						document.getElementById(DDC.embedVideoPlayer.videos[i])
							.stopMe();
					}
				} catch (e) {
					// do nothing
				}
			}
		},
		embedVideoPlayer = function (paramObj) {
			// Version check based upon the values entered above
			var ver = window.deconcept.SWFObjectUtil.getPlayerVersion(),
				width = !paramObj.width ? '100%' : paramObj.width,
				height = !paramObj.height ? '100%' : paramObj.height,
				alternateContent,
				so,
				swfName,
				swfPath,
				swfId,
				xmlPath;
			
			if ((+ver.major >= +reqMajVer) && (+ver.minor >= +reqMinVer)) {
				// version meets the requirements for playback
				swfName = 'ddcVideoPlayer_np.swf';
				
				if (paramObj.showPlaylist) {
					swfName = 'ddcVideoPlayer.swf';
				}
				
				swfPath = paramObj.swfPath ? paramObj.swfPath :
					'http://static.dealer.com/apps/video/player/';
				swfId = paramObj.playerId ? paramObj.playerId :
					paramObj.divName + '_flashobj';
				
				so = new window.SWFObject(swfPath + swfName + '?ver=' + swfVersion,
					swfId, width, height, reqMajVer.toString(), '');
				
				so.addParam('allowScriptAccess', 'always');
				
				so.addParam('wmode', 'transparent');
				so.addParam('allowFullScreen', 'true');

				so.addVariable('autoplay', paramObj.autoPlay);
				so.addVariable('embedWidth', width);
				so.addVariable('embedHeight', height);
				so.addVariable('swfId', swfId);
				
				if (paramObj.prerollXmlPath) {
					so.addVariable('prerollXmlPath', paramObj.prerollXmlPath);
				}
				if (paramObj.postrollXmlPath) {
					so.addVariable('postrollXmlPath', paramObj.postrollXmlPath);
				}
				if (paramObj.callToActionPath) {
					so.addVariable('callToActionPath',
						paramObj.callToActionPath);
				}

				if (paramObj.locale) {
					so.addVariable('locale', paramObj.locale);
				}
			
				if (paramObj.playlistXmlPath) {
					xmlPath = paramObj.playlistXmlPath;
					xmlPath = xmlPath.replace(/&/g, '%26');
					xmlPath = xmlPath.replace('_high.flv', '.xml');
					so.addVariable('playlistUrl', xmlPath);
				} else {
					so.addVariable('videoUrl', paramObj.videoUrl);
				}
				
				if (!paramObj.overlayPath) {
					// if overlay is not specified, add it automatically when
					// applicable - JMA
					if (paramObj.playlistXmlPath  && (paramObj.playlistXmlPath.indexOf('video/media/vehicles/') > 0)) {
						so.addVariable('overlayPath',
							'http://static.dealer.com/apps/video/player/overlays/vehicleFooter.swf%3F' + swfVersion);
					}
					if (paramObj.playlistXmlPath && (paramObj.playlistXmlPath.indexOf('http://videos.dealer.com/vehicles/') >= 0)) {
						so.addVariable('overlayPath',
							'http://static.dealer.com/apps/video/player/overlays/vehicleFooter.swf%3F' + swfVersion);
					}
				} else {
					so.addVariable('overlayPath', paramObj.overlayPath);
				}
				
				so.addVariable('playlistVisible', !!paramObj.showPlaylist);
				so.addVariable('backgroundLoad', !!paramObj.backgroundLoad);
				
				// test for the existence of the ID, otherwise so may fail
				if (document.getElementById(paramObj.divName)) {
					DDC.embedVideoPlayer.videos.push(swfId);
					so.write(paramObj.divName);
					if (typeof paramObj.success === 'function') {
						paramObj.success();
					}
				}
			} else {
				// flash is too old or we can't detect the plugin
				alternateContent = [
					'<div style="position: absolute; top: 40%; left: 30%;',
					'width: 300px; text-align: center; padding: 2px;',
					'padding-left: 25px; font-size: 11px;',
					'border: 1px solid #990000; color: #454545;',
					'background: #FFD8D3 url(/assets/icons/small/stop.png) ',
					'no-repeat; background-position: 5px 50%">',
					alt,
					'<br />',
					'<a href="http://www.adobe.com/go/getflash/" ',
					'target="_blank">',
					'Download Flash Player</a>',
					'</div>'
				].join('');
				document.getElementById(paramObj.divName).innerHTML =
					alternateContent;
			}
		},
		loadVideoContent = function () {
			/* DDC Video Player Embed Code in Dealer editable areas,.
				- Finds divs in the content with the image information available
				- as an attribute
				- (called in Assembler.init() method of composer to give time
				- for page to load in frame)
				- todo move this to external file / include
			*/
			$('.ddcPlayer-holder').each(function () {
				// ddcPlayerInfo="<src>-<width>-<height>"
				var attr = $(this).attr('ddcplayerinfo'),
					divId,
					accountId,
					infoArray,
					src,
					autoPlay,
					width,
					height;
				
				if (attr) {
					divId = this.id;
					// if hyphenatedAccountId is set on the ph image,. that
					// means we need to do some manipulation to get our parse
					// to work
					accountId = $(this).attr('hyphenatedaccountId');
					if (accountId) {
						attr = attr.replace(accountId, "<siteId>");
					}

					infoArray = attr.split('-');
					src = infoArray[0];

					// replace the siteId variable with the actual accountId
					if (accountId) {
						src = src.replace("<siteId>", accountId);
					}

					autoPlay = $(this).attr('autoplay') ?
						($(this).attr('autoplay') === 'true') : false;
					width = this.style.width || infoArray[1];
					height = this.style.height || infoArray[2];
					
					DDC.embedVideoPlayer({
						divName: divId,
						height: parseInt(height, 10),
						width: parseInt(width, 10),
						autoPlay: autoPlay,
						showPlaylist: false,
						allowFullScreen: false,
						playlistXmlPath: src,
						swfId: divId + '-player',
						swfPath: 'http://static.dealer.com/apps/video/player/'
					});
				}
			});
		};
	
	// export video player
	// TODO:  package the video player (i.e. DDC.Video.embedPlayer())
	// functions don't belong in the global DDC namespace
	window.DDC = window.DDC || {};
	if (!DDC.embedVideoPlayer) {
		DDC.embedVideoPlayer = embedVideoPlayer;
		DDC.embedVideoPlayer.videoStarted = videoStarted;
		DDC.embedVideoPlayer.videos = [];
		DDC.embedVideoPlayer.loadVideoContent = loadVideoContent;
	}
}());
