/* extra JS functions for pro7, sat1, kabel1, 7Games
** mediacenter videoplayer20
** Omniture Tracking only 
** $Revision: 1257 $ from $Date: 2009-05-25 16:00:43 +0200 (Mo, 25 Mai 2009) $ 
*/

function VP20Tracker() {	
	// keep some values
	this.updatePosition = -1;
	this.updateAdPosition = -1;
	this.updateAdEvent = "";
	this.updateAdName = "";
	this.viewTime = 0;
	this.viewTimeDelta = 0; // prepare for zoomIn/Out
	this.str = document.location.host.toLowerCase();
	this.isAT = (this.str.indexOf('sat1.at', this.str.length - 'sat1.at'.length) !== -1);
	this.isCH = (this.str.indexOf('sat1.ch', this.str.length - 'sat1.ch'.length) !== -1);
	this.doTrackATCH =  this.isAT || this.isCH;
		
	/**
	* Overwrite the data of the s object and call s.t() or s.tl() for Omniture tracking
	*/
	
	this.trackIVW = function(evt, obj) {
	  var pixel = new Image();
	  var timestamp = new Date().getTime();
	  var path = "/" + obj.ivwpath + "/";
	  var agof = obj.agof;
	  if (this.isAT) {
	    pixel.src = "http://svpro7.oewabox.at/cgi-bin/ivw/CP/" + agof + "/sat1.at/;" + path + "?d=" + timestamp;
	    return;
	  };
	  if (this.isCH) {
	    pixel.src = "http://sat1.wemfbox.ch/cgi-bin/ivw/CP/" + agof + ";" + path + "?d=" + timestamp;
	    return;
	  };
	  pixel.src = "http://sat1.ivwbox.de/cgi-bin/ivw/CP/" + agof + ";" + path + "?d=" + timestamp;
	};
		
	/**
	* Overwrite the data of the s object and call s.t() or s.tl() for Omniture tracking
	*/
	this.track = function(evt, obj) {	
		// different video tracking for at|ch and de
		if (this.doTrackATCH) {
			
			// tracking for at, and ch according to Warner Bros
			SIMGoogleTracker.ATCH.trackVideo(evt, obj);
			//_trackVideo(evt, obj);
		
			// first time ? then include ga.js 
			/*if (typeof this.ga_first_time === 'undefined') {
				this.ga_first_time = 'done'; 
				(function() {
					var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
					ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
					var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
				})();
			}*/
			
			// omniture is disabled for at and ch
			
		} else {
			if (typeof(SIMWebtrekkTracker) != "undefined") {
				SIMWebtrekkTracker.trackVideoEvent(evt, obj);
			}
			
			var mVideoEventNameList = {
				/* 'loadplayer': 'event16',  'play': 'event25',  'pause': 'event26',  'setBytesPerSecond': 'videoBytesPerSecond', */
				'PageViews': 'event2', 'PageViewsVideo': 'event6',
				'prerollAd_start': 'event17,event28', 'prerollAd_completed': 'event18',
				'contentClip_start': 'event19,event29', 'contentClip_completed': 'event20,event66', 
				'midrollAd1_start': 'event30,event28', 'midrollAd1_completed': 'event31', 
				'midrollAd2_start': 'event32,event28', 'midrollAd2_completed': 'event33', 
				'midrollAd3_start': 'event34,event28', 'midrollAd3_completed': 'event35', 
				'midrollAd4_start': 'event36,event28', 'midrollAd4_completed': 'event37',
				'midrollAd5_start': 'event38,event28', 'midrollAd5_completed': 'event39',
				'updateAdPosition': 'event21',  'updatePosition': 'event22,event66',  
				'updateMidroll1Position': 'event40', 'updateMidroll2Position': 'event41', 'updateMidroll3Position': 'event42',
				'updateMidroll4Position': 'event43', 'updateMidroll5Position': 'event44',
				'adClicked': 'event27', 'fullscreenOn': 'event23', 'fullscreenOff': 'event24',
				'viewTimeXplus': 'event65', 'videoBytesPerSecond': 'event67'
			};
		
			// check if s is already created and s_code.js is loaded
			if(!window.s) return;
		
			// handle the s object
			s = s_gi(s_account);
		
			// reset some values
			s.eVar13 = 0; // videoBytesPerSecond
			s.eVar14 = 0; // viewTime
			s.eVar28 = 0; // old one; this.getEventValue('videoBytesPerSecond');
		
			//special handling for PageView event
			if(evt.evtname == "PageViews") {
			  evt.evtname = "PageViewsVideo";
			  this.trackIVW(evt, obj);
			}
		
			// overwrite or set the Omniture values on-the-fly before calling s.t() or s.tl()
			s.linkTrackVars = "events,eVar13,eVar14,eVar16,eVar17,products"; // what variables are send
			s.linkTrackEvents = (mVideoEventNameList[evt.evtname]) ? mVideoEventNameList[evt.evtname] : ""; // define the events to send
		
			s.pageName = "/" + obj.ivwpath + "/" + obj.title;
			s.prop1 = obj.title;
			s.prop2 = obj.ivw_content_type ? obj.ivw_content_type : "video"; // IVW content type, "video" for VP and "content" for MC
			s.prop3 = "/" + obj.ivwpath + "/";
			s.prop4 = obj.agof;
			s.prop6 = ""; // Search string
			s.prop7 = ""; // Search Result
			s.hier1 = obj.ivwpath + "/" +obj.title;
			s.hier2 = s.server + "/" + obj.ivwpath + "/" +obj.title;
		
			var linkURL_tmp = obj.link_url.split("/");
		
			s.channel = linkURL_tmp[0]; //obj.link_url.split("/") >> channel
			s.prop8 = (linkURL_tmp.length > 1) ? linkURL_tmp[1] : ""; // obj.link_url.split("/") >> format = hierarchie1
			s.prop9 = (obj.hierarchy2) ? obj.hierarchy2 : ""; // vplayer = hierarchie2
			s.prop10 = (obj.video_type) ? obj.video_type : ""; // full, short = hierarchie3
			s.prop22 = (obj.playback_duration) ? obj.playback_duration : 0; // =video length [sec]
			s.prop23 = (obj.id) ? obj.id : ""; // =videoID
			s.prop24 = (obj.playertype) ? obj.playertype : ""; // =videoPlayerType [pageplayer, mediaplayer]

			//s_browserInfo should be provided by tools.js
			if (typeof s_browserInfo != "undefined") {
				s.prop25 = s_browserInfo.getViewportWidth(); //viewport width
				s.prop26 = s_browserInfo.getViewportHeight(); //viewport height
				s.prop27 = s_browserInfo.getFlashVersion(); // flash version
			}

			s.eVar8 = obj.ivw_content_type; // IVW content type
			s.eVar16 = s.prop3 + obj.title; // VideoName
			s.eVar17 = evt.evtname; // EventName
		
			// GOOGLE ANALYTICS MOVIE TRACKING
			gac_mov_track(s.prop10, s.prop8, obj.title, obj.ivwpath, evt.evtname);
		
			/**
			* define the s.products and prepare for later accumulation, see Omniture doc p.115
			* multiple event values separated with pipes "|"
			* s.events="purchase,event1,event2"
			* s.products="Category;Product;Quantity;Price;eventN=X[|eventN=X][,Category;Product;Quantity;Price;eventN=X]"
			*/
			s.products = (evt.evtname=="PageViewsVideo") ? "" : ";;;;";
		
			// attach position to fullscreenOn and fullscreenOff event
			// if(evt.evtname == "fullscreenOn" || evt.evtname == "fullscreenOff") s.eVar17 += " " + Math.round(evt.param1); // evt.param1=position [sec]
		
			// add viewtime to contentClip_completed
			if(evt.evtname == "contentClip_completed") {
				s.products += "event66=" + this.viewTime + "|";
				s.eVar14 = "viewTime " + this.viewTime;
			}
		
			// attach the data to the videoBytesPerSecond event
			if(evt.evtname == "videoBytesPerSecond") {
				s.products += mVideoEventNameList[evt.evtname] + "=" + evt.param1 + "|";
				s.eVar13 = "videoBytesPerSecond " + evt.param1;
			}
			// set the event list
			s.events = (mVideoEventNameList[evt.evtname]) ? mVideoEventNameList[evt.evtname] : ""; // put the events here, such as event17, ..
			if(s.events == "") return; // exit if event is not known
			else if(s.events == "event2") s.events = ""; // event2 is always added in s_code.js, so avoid double naming
		
			// set and reset updatePosition on contentClip_start/completed
			if(evt.evtname == "contentClip_start") {
				this.updatePosition = 0;
				this.viewTime = 0;	
			}
			if(evt.evtname == "contentClip_completed") {
				this.updatePosition = -1;
				this.viewTime = 0;
			}
		
			// save update of AdPositions and abort tracking, as position updates are collected
			if(evt.evtname == "updateAdPosition" || evt.evtname == "updateMidroll1Position" || evt.evtname == "updateMidroll2Position" || evt.evtname == "updateMidroll3Position" || evt.evtname == "updateMidroll4Position" || evt.evtname == "updateMidroll5Position")
			{
				this.updateAdPosition = evt.param1;
				this.updateAdEvent = s.events; 
				this.updateAdName = evt.evtname;
				return;
			}
		
			// save update of VideoPositions and abort tracking, as position updates are collected
			if(evt.evtname == "updatePosition")
			{
				this.updatePosition = evt.param1;
				this.viewTime += 5; // sum up the 5 seconds
				return;
			}
		
			// set and reset updateAdPosition on AdClip_start/completed
			if(evt.evtname == "prerollAd_start" || evt.evtname == "midrollAd1_start" || evt.evtname == "midrollAd2_start" || evt.evtname == "midrollAd3_start" || evt.evtname == "midrollAd4_start" || evt.evtname == "midrollAd5_start")
			{
				this.updateAdPosition = 0;
				switch (evt.evtname) {
					case "prerollAd_start":
						this.updateAdName = "updateAdPosition";
						break;
					case "midrollAd1_start":
						this.updateAdName = "updateMidroll1Position";
						break;
					case "midrollAd2_start":
						this.updateAdName = "updateMidroll2Position";
						break;
					case "midrollAd3_start":
						this.updateAdName = "updateMidroll3Position";
						break;
					case "midrollAd4_start":
						this.updateAdName = "updateMidroll4Position";
						break;
					case "midrollAd5_start":
						this.updateAdName = "updateMidroll5Position";
						break;
					default: 
						this.updateAdName = "";
				}
			
				this.updateAdEvent = (mVideoEventNameList[this.updateAdName]) ? mVideoEventNameList[this.updateAdName] : "";; 
			}
			if(evt.evtname == "prerollAd_completed" || evt.evtname == "midrollAd1_completed" || evt.evtname == "midrollAd2_completed" || evt.evtname == "midrollAd3_completed" || evt.evtname == "midrollAd4_completed" || evt.evtname == "midrollAd5_completed")
			{
				this.updateAdPosition = -1;
				this.updateAdEvent = "";
				this.updateAdName = "";
			}
		
			/*
			* invoke a complete new path set for the "PageViews" event with s.t()
			* for all other events just do the smaller s.tl()
			*/
			if(evt.evtname == "PageViewsVideo") s.t(); // s.t() just as IVW and updateAds()
			else s.tl(this, 'o', obj.title); // s.tl(this, 'o', s_eVar16);
		}
	}
	
	/**
	* Call this method when user aborts the playing of a clip to send the viewTime, updatePosition and updateAdPosition data
	*/
	this.sendFinal = function() {
		// tracking for at, and ch according to Warner Bros
		if (this.doTrackATCH) {	_trackCancelEvent(); }		
		
		// check if s is already created and s_code.js is loaded
		if(!window.s) return;
		
		try {
			// s.products="Category;Product;Quantity;Price;eventN=X[|eventN=X][,Category;Product;Quantity;Price;eventN=X]"
			s.products = ";;;;";
		
			if(this.updatePosition != -1) {
				// create the updatePos event here
				s.linkTrackEvents = "event22,event66" + ",";
				s.events = "event22,event66" + ",";
				s.products += "event22=" + this.updatePosition + "|" + "event66=" + this.viewTime + "|"; // TODO recheck with reports, p.115 documentation
				s.eVar17= "updatePosition " + this.updatePosition;
				s.eVar14 = "viewTime " + this.viewTime; // add viewtime to updatePosition
				// fire the event
				s.tl(this, 'o', s.prop1);
				// reset the saved data
				this.viewTime = 0;
				this.updatePosition = -1;
			}
			
			if(this.updateAdPosition != -1) {
				// create the updateAdPos event  here
				s.linkTrackEvents += this.updateAdEvent;
				s.events += this.updateAdEvent;
				s.products += "" + this.updateAdEvent + "=" + this.updateAdPosition;
				s.eVar17= this.updateAdName + " " + this.updateAdPosition;
				// fire the event
				s.tl(this, 'o', s.prop1);
				// reset the saved data
				this.updateAdPosition = -1;
				this.updateAdEvent = "";
				this.updateAdName = "";
			}
		}
		catch(e) {
			void(0);
		}
	}
	
	/**
	* attach sendFinal to unload event to send 
	* last updatePos and updateAdPos to Omniture
	*/
	this.setUnloader = function(fn) {
		if(window.addEventListener) window.addEventListener("unload", fn, false);
		else if(window.attachEvent) window.attachEvent("onunload", fn);
	}
}

var vp20Tracker = new VP20Tracker();
vp20Tracker.setUnloader(doTrackerUnload);

function doTrackerUnload() {
	vp20Tracker.sendFinal();
}

function _trackCancelEvent() {
	_trackVideo( {evtname : 'contentClip_canceled'});	
}

// Parameter obj  is delivered from Videoplayer
function _trackVideo( event, obj) {
	var result = true;
	switch (event.evtname) {
	case "contentClip_start":

		// Start timer for video and save type
		this.ga_view_time = 0;
		this.ga_video_duration = Math.round(event.duration);

		var pathObj = obj.ivwpath.split('/');
	    this.ga_channel = pathObj[0];
		this.ga_subchannel1 = pathObj[1];
		this.ga_title = obj.title;
		this.ga_video_type = (obj.video_type == 'full') ? 'ganze-folge' : type='clip';

		_gaq.push(["_setCustomVar", 1, "tvBrand", "Sat1", 3]);
		_gaq.push(["_setCustomVar", 2, "channel", this.ga_channel, 3]);
		_gaq.push(["_setCustomVar", 3, "subchannel1", this.ga_subchannel1, 3]);
		
		_gaq.push([ '_trackEvent', this.ga_video_type, this.ga_subchannel1, this.ga_title ]);
		
		break;
	case "updatePosition":
		// Increment timer
		this.ga_view_time += 5;
		break;

	case "viewTimeXplus":

		_gaq.push(["_setCustomVar", 1, "tvBrand", "Sat1", 3]);
		_gaq.push(["_setCustomVar", 2, "channel", this.ga_channel, 3]);
		_gaq.push(["_setCustomVar", 3, "subchannel1", this.ga_subchannel1, 3]);
		_gaq.push([ '_trackEvent', this.ga_video_type + "-3min", this.ga_subchannel1, this.ga_title ]);

		break;

	case "contentClip_completed":
	case "contentClip_canceled":
		// Record total duration viewed and reset

		_gaq.push(["_setCustomVar", 1, "tvBrand", "Sat1", 3]);
		_gaq.push(["_setCustomVar", 2, "channel", this.ga_channel, 3]);
		_gaq.push(["_setCustomVar", 3, "subchannel1", this.ga_subchannel1, 3]);
		_gaq.push([ '_trackEvent', this.ga_video_type + "-viewtime", this.ga_subchannel1, this.ga_title, this.ga_view_time ]);
		this.ga_view_time = 0;

		break;

	default:
		// Ignore
		result = false;
	}
	return result;
};


//if ((window.location.search.indexOf("gvp=1") > -1) || (window.location.href.indexOf("/sechsterpack/video/") > -1)) {
if (window.location.search.indexOf("streamplayer=1") == -1) {
  SWFObject.prototype.write = function(elementId) {
    if(this.getAttribute('useExpressInstall')) {
    	// check to see if we need to do an express install
    	var expressInstallReqVer = new deconcept.PlayerVersion([6,0,65]);
    	if (this.installedVer.versionIsValid(expressInstallReqVer) && !this.installedVer.versionIsValid(this.getAttribute('version'))) {
    		this.setAttribute('doExpressInstall', true);
    		this.addVariable("MMredirectURL", escape(this.getAttribute('xiRedirectUrl')));
    		document.title = document.title.slice(0, 47) + " - Flash Player Installation";
    		this.addVariable("MMdoctitle", document.title);
    	}
    }
    if(this.skipDetect || this.getAttribute('doExpressInstall') || this.installedVer.versionIsValid(this.getAttribute('version'))){
    	var n = (typeof elementId == 'string') ? document.getElementById(elementId) : elementId;
    	n.innerHTML = this.getSWFHTML();
      document.getElementById("clip-info").innerHTML = "";
    	return true;
    }else{
    	if(this.getAttribute('redirectUrl') != "") {
    		document.location.replace(this.getAttribute('redirectUrl'));
    	}
    }
    return false;
  }
  
	SWFObject.prototype.addParam = function(name, value) {
		if (name == "wmode") {
			this.params["bgcolor"] = "000000";
			value = "opaque";
		}
		this.params[name] = value;
	};
	SWFObject.prototype.addVariable = function(name, vvalue) {
		var originalvalue = vvalue;
		if (name == "json") {
			try {
				vvalue = JSON.parse(unescape(vvalue));
			} catch (err) {
				vvalue = eval( "(" + unescape(vvalue) + ")");
			}
			window.getConfig = function() {
				return window.mingConfig;
			}
			var value=vvalue;
			var jsonPart = {
				display_info: {
					brand_logo: value.brand_logo == "1" ? true : false,
					product_placement: value.product_placement == "1" ? true : false
				}, 
				home_url: value.categoryList[0].metadata.link_url,
				theme_url: value.categoryList[0].metadata.tracking_path,
				taxonomy_marketing: value.categoryList[0].metadata.taxonomy_marketing, // JSON
				taxonomy_index: value.categoryList[0].metadata.taxonomy_index, // JSON
				segments: []
			}
			
			for (var j=0;j<value.categoryList[0].clipList[0].segments.length;j++) {
				jsonPart.segments[j] = {
					type: value.categoryList[0].clipList[0].segments[j].segment_type,
					title: value.categoryList[0].clipList[0].segments[j].title,
					startOffset: value.categoryList[0].clipList[0].segments[j].offset
				}
				if (typeof(value.categoryList[0].clipList[0].segments[j+1]) != "undefined") {
					jsonPart.segments[j].endOffset = value.categoryList[0].clipList[0].segments[j+1].offset;
				} else {
					jsonPart.segments[j].endOffset = value.categoryList[0].clipList[0].stop; 
				}
			}
				
			if (window.mingConfig==undefined) {
				window.mingConfig = {
					playlist: {
						videos: [{}]
					}
				}
			}
			for (var i in jsonPart) {
				window.mingConfig.playlist.videos[0][i] = jsonPart[i];
			}
		}
		
		
		if (name == "qvt") {
			try {
				vvalue = JSON.parse(unescape(vvalue));
			} catch (err) {
				vvalue = eval( "(" + unescape(vvalue) + ")")
			}
			window.getConfig = function() {
				return window.mingConfig;
			}
			
			var value=vvalue;
			var qvtPart = {
				tracker_info: {
					foo: "bar",
					myvar: 1
				},
				ad_info: {
					ad_exclude_all: value.ad_exclude_all == "1" ? true : false,
					ad_exclude_preroll: value.ad_exclude_preroll == "1" ? true : false,
					ad_exclude_postroll: value.ad_exclude_postroll == "1" ? true : false,
					ad_exclude_midroll: value.ad_exclude_midroll == "1" ? true : false,
					ad_exclude_overlay: value.ad_exclude_overlay == "1" ? true : false,
					ad_exclude_sponsor: value.ad_exclude_sponsor == "1" ? true : false,
					ad_exclude_pauseroll: value.ad_exclude_pauseroll == "1" ? true : false
				},
				// display_info: {}, // JSON
				broadcast_date: value.broadcast_date || "1970-01-01",
				broadcast_time: value.broadcast_time || "00:00:00",
				clip_id: value.id || "000000",
				copyright: value.copyright || "",
				filename: value.downloadFilename || "",
				description: value. desc || "",
				duration: value.playback_duration || "0",
				endOffset: value.stop,
				format: value.show_artist || "",
				fsk: value.fsk || "",
				geoblocking: value.geoblocking || "de",
				opener_id: value.opener_id || "",
				// home_url: "", // JSON
				// theme_url: "", // JSON
				startOffset: value.start || "0",
				// taxonomy_marketing: "", // JSON
				// taxonomy_index: "", // JSON
				title: value.title || "",
				type: value.video_type || "short",
				visible_start: value.visibility.visible_start || "",
				visible_stop: value.visibility.visible_stop || "",
				thumbnail: [{
					width: 180,
					height: 120,
					quality: "normal",
					url: value.thumbnail.url
				}]
				// segments: [{}] // segments iterieren
			}
				
			if (window.mingConfig==undefined) {
				window.mingConfig = {
					playlist: {
						videos: [{}]
					}
				}
			}
			for (var i in qvtPart) {
				window.mingConfig.playlist.videos[0][i] = qvtPart[i];
			}
			
			if (typeof(value.flashdrm_url) == "undefined") {
				var version = "1.0.0-SNAPSHOT-sat1";
				var basepath = "http://archive.sat1.de/imperia/gvp";
				var playerpath = basepath + "/player/bootstrap/"+version+"/MingBootstrap.swf";
				this.variables["loaderUrl"] = basepath + "/MingLoader.swf";
				this.variables["playerRepositoryUrl"] = basepath;
				this.variables["site"] = "sat1";
				this.variables["configVersion"] = version;
				this.variables["loaderVersion"] = version;
				this.variables["autoplay"] = true;
				this.attributes.swf = playerpath;
				this.attributes.version = new deconcept.PlayerVersion("10.1".split("."));
			}
		}
		
		this.variables[name] = originalvalue;
	}
};

