// Default auf False zur Unterdrueckung von Werbung in Videos. Wird auf true gesetzt, wenn Werbung erlaubt ist.
// RL, HF 28.08.2009
var bCMSForceVPlayerAds = false;

var flashClass     = { video: 'VideoContainer', audio: 'AudioContainer' };
var tempInnerHTML  = { video: [], audio: [] };
var playersStarted = { video: 0, audio: 0 };

var tempTargetDivId = "";

var adcalls = new Object();

function saveHTML( type ) {
	$('.' + flashClass[type]).each( function(i) {
		tempInnerHTML[type][i] = $(this).html();
	});
}

function pausePlayers( type ) {
	if (playersStarted[type] == 0) return; // FemFix sb 23.01.08  Sonst erschien undefined in der VideoBox auf der mysite bei geloeschten caches.
	try{
		$('.' + flashClass[type]).each( function(i) {
			$(this).html(tempInnerHTML[type][i]);
		});
	} catch(e) {}
}

/** Function writeFLV
 *		@param: videoXML = Url zum XML
 *		@param: playerWidth = Breite des Players 290|610|940
 *		@param: magnifierLink = URL zum Seite mit großem Player
 *		@param: targetDivId = DivId es VideoContainer	
 *		@param: isAudio = 'isaudio' oder ''
 *		@param: tagIt = true | false  (erzeuge eine ivw-Tag)
 *		@param: sci= '<id-des-videos>'
 *		@param: stle='<titel-des-videos>'
 *		@param: smark:'gema' ist fest mit dem Wert gema hinterlegt, sonst leer wenn keine Gema Meta-Daten vorliegen
 *		@param: ivideoId = Url zum Video, wenn es zu diesem Video ein MP4 Video gibt (für iPhone|ipad..)
 */
function writeFLV(videoXML, playerWidth, magnifierLink, targetDivId, isAudio, tagIt, sci, stle, smark, ivideoId)
{
	pausePlayers( 'audio' );
	pausePlayers( 'video' );
	
	var playerHeight = "";
	var playerType = "medium";
	var playerCacheBuster = parseInt( Math.random() * 100000000 );

	// Player Setup
	switch( playerWidth )
    {
        case '290':
            playerHeight = '163';
            playerType = "small";
            break;
		case '600':
            playerHeight = '338';
            //playerType = "small";
            break;        
        case '610':
            playerHeight = '343';
            break;
        case '940':
            playerHeight = '529';
            break;
        case '100%':
            playerHeight = '100%';
            break;
        default:
            playerWidth = '100%';
            playerHeight = '100%';
            break;
    }

	$('#' + targetDivId).height( playerHeight );
	$('#' + targetDivId).width( playerWidth );

	// Check Device
	var isiDevice = /iPad|iPhone|iPod/i.test(navigator.userAgent);
	if (!(isiDevice && ivideoId)) 
	{
		ivideoId="";
	}
	if (!ivideoId)
	{
		if (!VideoFlashCheck(targetDivId)) return; // prüft wenn kein iphone etc ob Flash in mindestens Version 9 existiertm wenn nicht wird dies mit einem Bubble angezeigt
		
		/*** Kommentar: Prüfung wird beim Rendern des flowplayer durchgeführt... siehe function onFail ****/
	}
	//ivw-Tag erzeugen
	if (tagIt) try{new_tag();}catch(e){}
	
	var iqty = "lo";
	if (playerWidth > 290) {iqty = "hi";};
	if (isAudio == "isAudio") {
		iqty="au";
	};

	// Create Player
	if (isiDevice && ivideoId) 
	{
		//Render HTML5 VIDEO-TAG mit url aus ivideoId
		var iPlayer = '';
		if(isAudio == "isAudio")
		{
			iPlayer += '<audio id="iPlayer" title="' + stle + '" autoplay controls>';
			iPlayer += '	<source src="http://video.faz.net' + ivideoId + '" type=\'audio/mp3\' />';
			iPlayer += '	Your browser does not support the HTML5 Audio element. Please try activating Flash instead.';
			iPlayer += '</audio>';
		}
		else {
			iPlayer += '<video id="iPlayer" width="' + playerWidth + '" height="' + playerHeight + '" title="' + stle + '" autoplay controls>';
			iPlayer += '	<source src="http://video.faz.net' + ivideoId + '" type=\'video/mp4;codecs="avc1.42E01E, mp4a.40.2"\' />';
			iPlayer += '	Your browser does not support the HTML5 Video element. Please try activating Flash instead.';
			iPlayer += '</video>';
		}
		
		$('#' + targetDivId).html( iPlayer );
		
		// Tracking, einmalig mit 100% Fortschritt, npt = 1
		trackEvent('{"id":"13","ci":"' + sci + '","cn":"' + stle + '","npb":100,"sqty":"' + iqty + '","npt":1,"smark":"' + smark + '"}');
	}
	else {
		//Render FLOWPLAYER mit url aus videoXML
		//var playerFilePrefix = "/img/FAZNETPlayer-3.1.5";
		//Local:
		//var playerFilePrefix = "http://www.faz.net/img/FAZNETPlayer-3.1.5";
		//Neu local:
		var playerFilePrefix = "/swf/";
		var pluginFilePrefix = '/swf/plugins/';
		var PlayerSpeedDetectPrefix = 'http://video.faz.net/v/';

		var player_icon= pluginFilePrefix + 'play.swf?icon=play_290';
		if (playerWidth > 290) {player_icon=pluginFilePrefix + 'play.swf?icon=play'};
		if (isAudio == "isAudio") {
			player_icon=pluginFilePrefix + 'play.swf?icon=audio';
		};
		
		//var key = "['#@1951e7e7e34004d63a8', '#@96e12b53bb76fcfde9b', '#@6032db51bbb32890e94', '#@1b0591fa86c03770bb3']";
		
		// Ad Setup
		var bForceVPlayerAds = true;
		if( isAudio && isAudio != "" || playerType == "small")
		{
			bForceVPlayerAds = false; // Unterdruecken der Werbung bei Audio und kleinen Playern, unabhängig CMS
		}
		if (bCMSForceVPlayerAds && bForceVPlayerAds) 
		{
				// Generiert ToFo Ad-Calls
				try {
					var get_preroll = ads_gettag('preroll',467,385,100,'xml',0);
					//var get_midroll = ads_gettag('midroll',467,385,100,'xml',0);		// Im Moment hinfaellig (C.Sander E-Mail 04.06.2009)
					var get_midroll = '';
					var get_postroll = ads_gettag('postroll',467,385,100,'xml',0);
					var get_overlay = ads_gettag('videolayer',467,385,100,'xml',0);
				} catch (e) {
					var get_preroll = '';
					var get_midroll = '';
					var get_postroll = '';
					var get_overlay = '';
				}
		}
		else {
				var get_preroll = '';
				var get_midroll = '';
				var get_postroll = '';
				var get_overlay = '';
		}
		
		//* Live-Tags
		var preroll 	= get_preroll;
		var midroll 	= get_midroll;
		var postroll 	= get_postroll;
		var overlay 	= get_overlay;
		/* Test-Tags
		var preroll 	= escape('http://cdn1.eyewonder.com/200125/754851/1149206/1149206_tag.xml?ewbust=[timestamp]');
		var midroll 	= escape('http://cdn.eyewonder.com/100125/758003/1312737/1312737_tag.xml?ewbust=[timestamp]');
		var postroll 	= escape('http://cdn1.eyewonder.com/200125/754851/1149206/1149206_tag.xml?ewbust=[timestamp]');
		var overlay 	= escape('http://cdn.eyewonder.com/100125/758003/1312753/1312753_tag.xml?ewbust=[timestamp]');
		//*/
		
		// DoppelKlick Bug - targetDivId html leeren und dann Player einbetten  
		

		var active_player = $f();
		if ( active_player )
		{
			active_player.unload();
		}
		
		// Fullscreen Bug, Knopf wird nicht korrekt freigegeben, wenn mit false initialisiert
		var forceFullscreenBtn = false;
		if( playerType != "small" ) {
			forceFullscreenBtn = true;
		}

		$('#' + targetDivId).empty();
		
		// Flowplayer installation with Flashembed parameters
		flowplayer(targetDivId, {
				src: playerFilePrefix + "flowplayer.commercial.swf?" + playerCacheBuster,
				wmode: 'transparent',
				// we need at least this version
				version: [10, 1],

				// older versions will see a custom message
				onFail: function()  {
					$('#' + targetDivId).html(
						"You need the latest Flash version to view MP4 movies. " +
						"Your version is " + this.getVersion()
						);
				},

				width:  playerWidth,
				height: playerHeight
			}, {
				key: ['#@1951e7e7e34004d63a8', '#@96e12b53bb76fcfde9b', '#@6032db51bbb32890e94', '#@1b0591fa86c03770bb3'],

				//debug: true,
				//log: {level:'debug', trace:'true'},

				canvas: {
					backgroundColor: '0x111111',
					backgroundGradient: 'none'
				},

				screen:	{
					bottom: 0	// make the video take all the height
				},

				plugins: {
					controls: {
						url: pluginFilePrefix + 'faz.controls.swf?' + playerCacheBuster,
						fullscreen: forceFullscreenBtn,
						hd: false
					},

					audio: {
						url: pluginFilePrefix + 'flowplayer.audio-3.2.7.swf?' + playerCacheBuster
					},

					FAZ: {
						url: pluginFilePrefix + 'faz.swf?' + playerCacheBuster,
						detail_url:        magnifierLink,
						player_type:       playerType,
						bandwidth_file:    PlayerSpeedDetectPrefix + 'speeddetection.swf?' + playerCacheBuster,
						replay_button_url: pluginFilePrefix + 'play.swf?icon=replay'
					},

					uif: {
						url: pluginFilePrefix + 'uif.swf?' + playerCacheBuster,
						
						preroll:  preroll,
						midroll:  midroll,
						postroll:  postroll,
						overlay:  overlay,
						
						//ad_facade_url: './img/facade.jpg',
						//ad_facade_duration: '3',
						
						midroll_video_length: '10',
						overlay_delay: '5',
						
						ad_countdown: true,
						ad_countdown_position: 'top',
						ad_countdown_text: ' Die Anzeige endet in: [time] ',
						ad_countdown_text_color: '0xffffff',
						ad_countdown_color: '0x111111',
						ad_countdown_opacity: 0.6
					}
				},

				playlist: [ videoXML ],

				play: {
					url: player_icon,
					opacity: 0.99,
					fadeSpeed: 500,
					rotateSpeed: 50,
					replayLabel: '',
					label: null
				},

				clip: {
					autoPlay: true,
					scaling: 'fit',
					autoBuffering: false,
					urlResolvers: [ 'FAZ' ]
				}
			}
		);
		
		// Start Tracking muss hier stattfinden, da der Player ohne Anpassung des EyeWonder UIF-Plugin keinen 0% Status vor Preroll wirft
		trackEvent('{"id":"13","ci":"' + sci + '","cn":"' + stle + '","npb":"0","sqty":"' + iqty + '","smark":"' + smark + '"}');

	}

	tempTargetDivId = targetDivId;
	
	playersStarted[(isAudio == "isAudio"?'audio':'video')]++;
}

// Wird vom HQ-Button im flowplayer aufgerufen
function toggleHQmode() 
{
	var containerID = tempTargetDivId;
	var currentW = $('.VideoContainer').width();
	
	if(currentW == '600'){ return; } 
	
	// Untersch. Auszeichnung in Templates auslesen
	if( $('.TeaserMultimedia h1').length != 0 ) {
		var str_vdo_head = $('.TeaserMultimedia h1').html();
		var vdo_head_inner = '<h1>'+str_vdo_head+'</h1>';
	}
	else {
		var str_vdo_head_1 = $('.TeaserMultimedia p.Stichwort').html();
		var str_vdo_head_2 = $('.TeaserMultimedia p.Headline').html();
		var vdo_head_inner = '<p class="Stichwort">'+str_vdo_head_1+'</p><p class="Headline">'+str_vdo_head_2+'</p>';
	}
	
	// Stichwort-Headline (wird unter Video ausgegeben) 
	var vdo_header = '<div class="TeaserMultimedia" style="width: 100%;">'+vdo_head_inner+'</div>';
	var str_close = '<a class="BtnExitHQ" onclick="toggleHQmode(\''+containerID+'\')" title="Schlie&szlig;en">Schlie&szlig;en X</a>';
	
	// Maße hier anpassen
	if(currentW == '610') {
		var newW = '940';
		var newH = '540';
		var newPad = '20px 10px 10px 10px';
		var newOuterH = '545';		
		$('.ArtikelAbbinder.Video').before(vdo_header);
		$('.VideoContainer object').before(str_close);
	}
	else {
		var newW = '610';
		var newH = '343';
		var newPad = '20px 10px 10px 20px';		
		var newOuterH = 'auto';		
		$('.VideoBoxInnerLeft .TeaserMultimedia').remove();
		$('.VideoContainer a.BtnExitHQ').remove();
	}
	
	$('.VideoBoxInnerLeft').css({ width: newW, padding: newPad });
	$('.VideoContainer').css({ width: newW, height: newOuterH });		
	$('.ArtikelAbbinder.Video').css('width',newW);	 
	$('#'+containerID).css({ width: newW, height: newH });	
	$('#'+containerID+'_api').css({ width: newW, height: newH });
	
	$('.VideoBoxInnerRight').toggle();

}

function trackEvent(arg) 
{
	//alert ("Tracking"+ arg);
	//var tmpArg = JSON.parse(arg);
	var tmpArg = $.parseJSON(arg);
	try{console.log(tmpArg);}catch(e){} // Test
	try{__GETS.etag(tmpArg);}catch(e){} // Live
}

$(document).ready(function()
{
    saveHTML( 'audio' );
	saveHTML( 'video' );
});

