// JavaScript Document

// Universal Player Javascript for Hammerhead
if (!window.UniversalPlayer) {

var UniversalPlayer = {};

UniversalPlayer.manager = {
	playerIds: [],
	players: [],

	getId: function() {
		return this.addPlayerId("player"+this.playerIds.length);
	},

	addPlayerId: function(id) {
		return this.playerIds[this.playerIds.push(id)-1];
	},

	addPlayer: function(obj) {
		return this.players[this.players.push(obj)-1];
	}
};

var loadUniversalPlayer = function(options) {
	if(document.location.search.contains('autoplay=true')){
		options = $merge((options || {}),{autoPlay: (document.location.search.contains('autoplay=true'))});
	}

	var setPlayer = function(options) {
		UniversalPlayer.manager.addPlayer(new UniversalPlayer.Player(options));
	};

	if (options.parentElement) {
		UniversalPlayer.manager.players.push(options.parentElement);
		if ($(options.parentElement)) {
			setPlayer(options);
		} else {
			window.addEvent('domready', setPlayer(options));
		}
	} else {
		options.parentElement = UniversalPlayer.manager.getId();
		document.write('<div id="'+options.parentElement+'"></div>');
		setPlayer(options);
	}

};


UniversalPlayer.Player = new Class({
	Implements: Options,

	options: {
		parentElement: '',
		//Basic Options
		playerType: 'Universal',
		playerTitle: 'Cnet Universal Player',
		autoPlay: false,
		externalPlayer: false,
		watchedVideoRotation: false,
		wrapperFloat: 'left',
		localTest: false,
		//Lumiere Options
		lumiereQueryType: 'orderBy',
		lumiereQueryValue: 'productionDate+desc',
		//Interface Options
		startVolume: 30,
		expandTabs: false,
		showVideoInfo: false,
		hideBkg: false,
		hideTabs: false,
		hideLeftTab: false,
		hideHeader: false,
		useCurrentPageUrl: false,
		userAutoplay: false,
		displayMuteBtn: false,
		reviewsVideoOnly: false,
		hideEmailBtn: false,
        playOverlayText: 'PLAY CNET VIDEO',
        //Ad Options
		adInterval: 2,
		preRollAd: false,
		firstVideoPostAd: true,
		contentPostRollAd: false,
		adTest: false,
		//Related Video Options
		relatedVideo: true,
		externalLinks: false,
		vendorVideo: false,
		//Page Variables
		siteId: PageVars.get('siteId'),//Defined in PageVars
		pageType: PageVars.get('pageType'),//Defined in PageVars
		nodeId: PageVars.get('nodeId'),//Defined in PageVars
		oid: PageVars.getOid(),//Built in this file
		editionId: PageVars.get('editionId'),//Defined in PageVars
		brandId: PageVars.get('brandId'),//Defined in PageVars
		userIP: PageVars.get('userIP'),//Defined in PageVars
		ncat: PageVars.get('breadcrumb'),//Defined in PageVars
		userAgent: escape(navigator.userAgent),//Developer should never have to enter this in
		channelId: PageVars.get('channelId'),//Defined in PageVars
		assetId: PageVars.get('assetId'),//Defined in PageVars
		guid: PageVars.get('guid'),//Defined in PageVars
		dvarMfg: '',
		//CPN Options
		ePartner: '',
		cpnModule: '',
		refDomain: '',

		//Reviews Product Page Video Info
		videoTitle: null,
		productionDate: null,
		lengthSecs: null,
		videoId: null,
		description: null,
		embedable: true, // Needs to be added into API
		primaryNodeId: null,
		primaryNodePath: PageVars.get('breadcrumb'), // Will need to be replaced with video API value
		externalItemId: null, // Missing this value, use Product ID temporarily
		externalVideoType: null,
		downloadable: null,
		isTranscriptAvailable: null,
		siteId: PageVars.get('siteId'),
		image53x40: null,
		image106x80: null,
		image320x240: null,
		/*** Don't have these Values yet***/
		relatedLinkUrls: null,
		relatedLinks: null,
		relatedLinkTexts: null,
		deliveryUrl: null,
		downloadUrl: null,

		/* Options for initialization actions - eg: load video player on click instead of on page load - defaults to page load */
		initObject: window,
		initAction: 'load'
	},

	initialize: function(options){
		this.setOptions(options);
		this.processPlayerData();
		this.setAutoPlayProperties();
		this.makeDiv();
	},

	processPlayerData: function(){
		//Set the copy URL to the current page URL if this.options.useCurrentPageUrl = true
		if(this.options.useCurrentPageUrl) this.options.useCurrentPageUrl = document.URL;

		//Parses the Reviews and Download video xml call and passes it into the player
		/*if(this.options.playerType=="Reviews" || this.options.playerType=="Download"){
			var reviewsUrl = this.options.lumiereQueryValue.split("-");
			var splitReviewsURL = reviewsUrl[2].split(".");
			this.options.lumiereQueryValue = splitReviewsURL[0];
		}*/
		if(Cookie.get('userVolume') != null) this.options.startVolume = Cookie.get('userVolume');
	},

	setAutoPlayProperties: function(){
		//Check for autoplay cookie
		if(Cookie.get("userAutoPlay")=="disabled") this.options.autoPlay = false;
	},

	makeDiv: function(){
		var loadImgSrc = (this.options.playerType=='Widget') ? 'http://i.i.com.com/cnwk.1d/i/vid/uPlayerWidgetLoader.gif' : 'http://i.i.com.com/cnwk.1d/i/vid/uPlayerLoader.gif';
		if(this.options.playerType == 'Widget'){
			var playerWidth = 300;
			var playerHeight = 250;
			//var background = 'http://i.i.com.com/cnwk.1d/i/vid/uPlayerWidget.gif';
			var swfName = 'universalWidget';
			var loadImgMargin = '0px';
		}else if(this.options.playerType == 'small'){
			var playerWidth = 364;
			var playerHeight = 280;
			//var background = 'http://i.i.com.com/cnwk.1d/i/vid/uPlayerWidget.gif';
			var swfName = 'universalSmall';
			var loadImgMargin = '0px';
		}else{
			if(this.options.hideTabs == true){
				var playerWidth = 460;
				var playerHeight = 322;
			}else{
				var playerWidth = 460;
				var playerHeight = 342;
			}
			var background = 'http://i.i.com.com/cnwk.1d/i/vid/uPlayerBG.gif';
			var loadImgMargin = '61px 0px 0px 8px';
			var swfName = 'universal';
		}

		var videoWrapper = new Element('div', {
			'id': 'universalVideoWrapper'+UniversalPlayer.manager.players.length,
			'class': 'float'+this.options.wrapperFloat,
			'styles': {
				'width': playerWidth,
				'height': playerHeight,
				'position': 'relative',
				'zIndex': '90',
				'float': this.options.wrapperFloat
			}
		});

		if(this.options.hideTabs == true){
			if(this.options.pageType == 4505){
				videoWrapper.setStyle('borderBottom', '#ffffff solid 2px');
			}else{
				videoWrapper.setStyle('borderBottom', '#cbcbcb solid 1px');
			}
		}

		videoWrapper.inject(this.options.parentElement);

		var loadImg = new Element('img', {'id': 'universalLoaderImg'+UniversalPlayer.manager.players.length, 'src': loadImgSrc, 'styles': {'position': 'absolute', 'zIndex': '100', 'margin': loadImgMargin}});
		//loadImg.inject(videoWrapper, 'top');

		this.checkFlashVersion(videoWrapper, playerWidth, playerHeight, swfName, loadImg, loadImgMargin);
	},

	checkFlashVersion: function(wrapperDiv, playerWidth, playerHeight, swfName, loaderImg, loadImgMargin){
		var MM_contentVersion = 8;

		var MM_FlashCanPlay = Swiff.getVersion() >= MM_contentVersion;


		if(!MM_FlashCanPlay){
			wrapperDiv.set('html', 'We&rsquo;ve detected that you need to upgrade or install Flash '+MM_contentVersion+' or later to view our library of thousands of tech videos. Installing Flash is fast, free, and easy! Simply follow the instructions from your browser, or <a href="http://www.adobe.com/go/getflashplayer" id="flashVidErrorLink">click here to install/upgrade the free Flash player</a>.<br />&nbsp;<br />Thanks,<br />The CNET TV Team');

			wrapperDiv.setStyles({
				font: 'normal 14px Arial, Helvetica, San Serif',
				lineHeight: '18px',
				color: '#000',
				margin: loadImgMargin,
				padding: '8px',
				width: playerWidth - 16,
				height: playerHeight - 16
			});
		}else{
			var thisObject = this;

			if(this.options.initAction == false){
				thisObject.makeSwf(wrapperDiv, playerWidth, playerHeight, swfName);
			}else{
				var initObject = $(this.options.initObject) || $$(this.options.initObject);
				initObject.addEvent(this.options.initAction, function(){
					 thisObject.makeSwf(wrapperDiv, playerWidth, playerHeight, swfName);
				});
			}
		}
	},

	makeSwf: function(videoWrapper, playerWidth, playerHeight, swfName){

		if(this.options.watchedVideoRotation == true){
			if(Cookie.get("cnetWatchedVideos") != false){
				var cnetWatchedVideos = Cookie.get("cnetWatchedVideos").split(",");
				for(r=0;r<cnetWatchedVideos.length;r++){
					if(cnetWatchedVideos.length > 5){
						cnetWatchedVideos.splice(0,1)
					}
				}

				var enteredVideos = this.options.lumiereQueryValue.split(",");

				for(var i=0;i<cnetWatchedVideos.length;i++){
					var videoCheck = cnetWatchedVideos[i];
					for(var c=0;c<enteredVideos.length;c++){
						if(videoCheck == enteredVideos[c]){
							enteredVideos.splice(c,1);
							enteredVideos.push(videoCheck);
							var videosWatched = true;
						}
					}
				}

				var queryValue = (videosWatched == true) ? enteredVideos : escape(this.options.lumiereQueryValue);
			}else{
				var queryValue = escape(this.options.lumiereQueryValue);
			}
		}else{
			var queryValue = escape(this.options.lumiereQueryValue);
		}

		//Check for live vs. stage ad environment
		var urlString = document.URL;

		if((urlString.contains(".com:") == true && urlString.contains("uat") == false) || urlString.contains("preview1.") == true || urlString.contains("dev-server-test.dev.sub.classes") == true){
			var liveAdEnv = false;
		}else{
			var liveAdEnv = true;
		}

		if(this.options.adTest==true){
			var swfPath = 'http://www.cnet.com/av/video/flv/universalPlayer/'+swfName+'.swf';
		}else if(urlString.contains("i.i.com.com/cnwk.1d") == true || urlString.contains("localhost") == true){
			var swfPath = 'http://www.cnet.com/av/video/flv/universalPlayer/'+swfName+'.swf';
		}else if(urlString.contains("ssadev") == true){
			var swfPath = 'http://publish.cnet.com:8100/av/video/flv/universalPlayer/'+swfName+'.swf';
		}else{
			var swfPath = '/av/video/flv/universalPlayer/'+swfName+'.swf'
		}

		if(this.options.localTest == true){
			var swfPath = 'http://publish.cnet.com:8100/av/video/flv/universalPlayer/tests/'+swfName+'.swf';
		}

	  	if(window.location.href.indexOf("playerVersion")>0){
		    var playerVersion = Browser.getQueryStringValues().playerVersion;
		    var swfPath = '/av/video/flv/universalPlayer/'+playerVersion+'/'+swfName+'.swf';
		}
		if(this.options.playerType=="Reviews"){
			if(this.options.image53x40.contains("http://www.download.com"))   this.options.image53x40 = this.options.image53x40.split("http://www.download.com")[1];
			if(this.options.image106x80.contains("http://www.download.com"))   this.options.image106x80 = this.options.image106x80.split("http://www.download.com")[1];
			if(this.options.image320x240.contains("http://www.download.com"))   this.options.image320x240 = this.options.image320x240.split("http://www.download.com")[1];
		}

		var playerIteration = videoWrapper.getProperty('id').split('universalVideoWrapper')[1];

		var parentElement = this.options.parentElement;

		var swfObj = new Swiff(swfPath, {
			id: 'universalPlayer'+playerIteration,
			width: playerWidth,
			height: playerHeight,
			container: videoWrapper,
			params: {
				wMode: 'transparent',
				bgcolor: '#EDEDED',
				scale: 'noscale',
				salign: 'lt',
				swLiveConnect: 'true',
				allowScriptAccess: 'always',
				allowFullScreen: 'true'
			},
			vars: {
				//Define Variables
				ddom: Browser.getHost(),
				parent: true,
				live: liveAdEnv,

				//Basic Options
				parentElement: parentElement,
				playerIteration: playerIteration,
				playerType: this.options.playerType,
				name: this.options.playerTitle,
				autoplay: this.options.autoPlay,
				externalPlayer: this.options.externalPlayer,
				//Lumiere Options
				type: this.options.lumiereQueryType,
				value: queryValue,
				//Interface Options
				startVolume: this.options.startVolume,
				expandTabs: this.options.expandTabs,
				showVideoInfo: this.options.showVideoInfo,
				hideLeftTab: this.options.hideLeftTab,
				hideHeader: this.options.hideHeader,
				copyUrl: this.options.useCurrentPageUrl,
				userAutoplay: this.options.userAutoplay,
				displayMuteBtn: this.options.displayMuteBtn,
				hideTabs: this.options.hideTabs,
				reviewsVideoOnly: this.options.reviewsVideoOnly,
				hideBkg: this.options.hideBkg,
				hideEmailBtn: this.options.hideEmailBtn,
                playOverlayText: this.options.playOverlayText,
                //Ad Options
				adInterval: this.options.adInterval,
				firstVideoPreRoll: this.options.preRollAd,
				firstVideoPostRoll: this.options.firstVideoPostAd,
				contentPostRoll: this.options.contentPostRollAd,
				adTest: this.options.adTest,
				//Related Video Options
				relatedVideo: this.options.relatedVideo,
				externalLinks: this.options.externalLinks,
				vendorVideo: this.options.vendorVideo,
				//Page Variables
				si: this.options.siteId,
				br: this.options.brandId,
				ip: this.options.userIP,
				ua: this.options.userAgent,
				cid: this.options.assetId,
				oid: this.options.oid,
				edid: this.options.editionId,
				nd: this.options.nodeId,
				pt: this.options.pageType,
				ncat: this.options.ncat,
				guid: this.options.guid,
				dvarMfg: this.options.dvarMfg,
				//CPN Options
				ePartner: this.options.ePartner,
				cpnModule: this.options.cpnModule,
				refDomain: this.options.refDomain,

				//Reviews Video Content
				videoTitle: this.options.videoTitle,
				productionDate: this.options.productionDate,
				lengthSecs: this.options.lengthSecs,
				videoId: this.options.videoId,
				description: this.options.description,
				embedable: this.options.embedable,
				primaryNodeId: this.options.primaryNodeId,
				primaryNodePath: this.options.primaryNodeId,
				externalItemId: this.options.externalItemId,
				externalVideoType: this.options.externalVideoType,
				downloadable: this.options.downloadable,
				isTranscriptAvailable: this.options.isTranscriptAvailable,
				siteId: this.options.siteId,
				image53x40: this.options.image53x40,
				image106x80: this.options.image106x80,
				image320x240: this.options.image320x240,
				relatedLinkUrls: this.options.relatedLinkUrls,
				relatedLinks: this.options.relatedLinks,
				relatedLinkTexts: this.options.relatedLinkTexts,
				deliveryUrl: this.options.deliveryUrl,
				downloadUrl: this.options.downloadUrl
			}
		});
	}
});


/* Tracking */
var trackEvent = function(cval) {
	//DW.redir({ ctype: 'event', cval: cval});
	cval = escape(cval);
	var dwUrl = "http://dw.com.com/redir?destUrl=" + escape("http://i.i.com.com/cnwk.1d/b.gif?" + Math.floor(Math.random()*1000));
	dwUrl += "&edid=" + this.options.edid;
	dwUrl += "&oid=" + this.options.oid;
	dwUrl += "&onid=" + this.options.nd;
	dwUrl += "&siteid=" + this.options.si;
	dwUrl += "&ptid=" + this.options.pt;
	dwUrl += "&ctype=event";
	dwUrl += "&cval="+ cval;

	var dwImg = new Image;
	dwImg.src = dwUrl;

	dbug.log("trackEvent: " + "&cval="+ cval );
}


var checkCookie = function(cookieName){
	return Number(new Cookie(cookieName).read().toString());
}

var setCookie = function(cookieName, cookieValue, cookieOptions){
	new Cookie(cookieName).write(cookieValue, cookieOptions);
}



/*
Script: Swiff.js
	Wrapper for embedding SWF movies. Supports (and fixes) External Interface Communication.

License:
	MIT-style license.

Credits:
	Flash detection & Internet Explorer + Flash Player 9 fix inspired by SWFObject.
*/

var Swiff = function(path, options){
	if (!Swiff.fixed) Swiff.fix();
	var instance = 'Swiff_' + Native.UID++;
	options = $merge({
		id: instance,
		height: 1,
		width: 1,
		container: null,
		properties: {},
		params: {
			quality: 'high',
			allowScriptAccess: 'always',
			wMode: 'transparent',
			swLiveConnect: true
		},
		events: {},
		vars: {}
	}, options);
	var params = options.params, vars = options.vars, id = options.id;
	var properties = $extend({height: options.height, width: options.width}, options.properties);
	Swiff.Events[instance] = {};
	for (var event in options.events){
		Swiff.Events[instance][event] = function(){
			options.events[event].call($(options.id));
		};
		vars[event] = 'Swiff.Events.' + instance + '.' + event;
	}
	params.flashVars = Hash.toQueryString(vars);
	if (Browser.Engine.trident){
		properties.classid = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000';
		params.movie = path;
	} else {
		properties.type = 'application/x-shockwave-flash';
		properties.data = path;
	}

	var build = '<object id="' + options.id + '"';
	for (var property in properties) build += ' ' + property + '="' + properties[property] + '"';
	build += '>';
	for (var param in params) build += '<param name="' + param + '" value="' + params[param] + '" />';
	build += '</object>';
	var holder = new Element('div').set('html', build).firstChild;
	if (options.container) $(options.container).adopt(holder);
	//return holder;
	//return ($(options.container) || new Element('div')).set('html', build).firstChild;
};

Swiff.extend({

	Events: {},

	remote: function(obj, fn){
		var rs = obj.CallFunction('<invoke name="' + fn + '" returntype="javascript">' + __flash__argumentsToXML(arguments, 2) + '</invoke>');
		return eval(rs);
	},

	getVersion: function(){
		if (!$defined(Swiff.pluginVersion)){
			var version;
			if (navigator.plugins && navigator.mimeTypes.length){
				version = navigator.plugins["Shockwave Flash"];
				if (version && version.description) version = version.description;
			} else if (Browser.Engine.trident){
				version = $try(function(){
					return new ActiveXObject("ShockwaveFlash.ShockwaveFlash").GetVariable("$version");
				});
			}
			Swiff.pluginVersion = (typeof version == 'string') ? parseInt(version.match(/\d+/)[0]) : 0;
		}
		return Swiff.pluginVersion;
	},

	fix: function(){
		Swiff.fixed = true;
		window.addEvent('beforeunload', function(){
			__flash_unloadHandler = __flash_savedUnloadHandler = $empty;
		});
		if (!Browser.Engine.trident) return;
		window.addEvent('unload', function(){
			Array.each(document.getElementsByTagName('object'), function(obj){
				obj.style.display = 'none';
				for (var p in obj){
					if (typeof obj[p] == 'function') obj[p] = $empty;
				}
			});
		});
	}

});
}