/**
*
* PRELOADING BRIGHTCOVE PLAYER
* RENDITION SELECTION
* WEBTRENDS CALLS
* MESSAGE FOR GEO-BLOCKED CONTENT
* SET LINKBASEURL
*/

// How far in percent a rendition can be above the video screen height.
var FRAME_HEIGHT_TOLERANCE = 2.5;

// The percent amount the detected bandwidth is reduced when checking against encoding.
// Generally, you want a rendition to be encoded less than the available bandwidth in order to 
// ensure smooth playback.
var ENCODING_RATE_TOLERANCE = 5.0;


var _player;
var _experienceModule;
var _contentModule;
var _socialModule;
var _chromelessPlayer;
var _playlist;
var _swf_overlay;
var _adModule;
var _menuModule;

var videolayer=".videoLayer";
var closebtn=".lightbox_close";
var overlay=".lightbox_background"

var currentVideo;
var currentPlaylist;
var currentPlaylistLevel = 0;
var isVisible = false;
var isLive = false;
var p20 = false; var p40=false; var p60=false; var p80=false;

var keypressed=function(q){var p=q.which||q.keyCode||q.charCode;if(p===27){hidePlayer()}};

var showPlayer=function()
{
	isVisible = true;
	$("body").addClass("darkOverlay");
  	$(overlay).css("z-index",10050);
  	$(overlay).css("opacity","0");
  	$(overlay).css("display","block");
	$(overlay).animate({opacity:0.8})
	$(overlay).addClass("loading");
		
	// center and show videoplayer
  	var pos=($(window).height()-518)/2;
  	if (pos < 0) pos = 0;
  	else if (pos > 100) pos -= 100;
  	$(videolayer).css({top:pos+"px"});
	pos=($(window).width()-892)/2;
	$(videolayer).css({left:pos+"px"});
	$(videolayer).css("visibility", "visible");
	$(videolayer).css("z-index", 10100);
	$(".skyscraper").css("display","none");
	$(".navWrapper").css("z-index",40);
 	$(document).bind("keypress",keypressed);
 	$(overlay).removeClass("loading");
};

var hidePlayer=function()
{
	isVisible=false;
	if (_chromelessPlayer)
		_chromelessPlayer.stop();
	if (_menuModule && _menuModule.isMenuPageShowing())
		_menuModule.closeMenuPage();
	$(document).unbind("keypress",keypressed);
	$(".skyscraper").css("display","block");
	$(videolayer).css("visibility", "hidden");
	$(overlay).css("z-index",50);
	$(overlay).hide();
	$(".navWrapper").css("z-index",200)
 		
};



/** Event handler for when the player the player first loads. **/
function onTemplateLoaded(id) 
{
   if (id == "stv_brightcove" || id == "stv_livestream")
   {
    	_player 		= brightcove.getExperience(id);    
    	_experienceModule 	= _player.getModule(APIModules.EXPERIENCE);		// stage
    	_experienceModule.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
    	_chromelessPlayer = (_experienceModule.getElementsByType("ChromelessVideoPlayer"))[0];
    	_chromelessPlayer.addEventListener(BCMediaEvent.BEGIN, onMediaBegin);                        	
    	_chromelessPlayer.addEventListener(BCMediaEvent.COMPLETE, onMediaComplete);
	_chromelessPlayer.addEventListener(BCMediaEvent.PROGRESS, onMediaEvent);
    	_chromelessPlayer.setRenditionSelectionCallback(selectRendition);
    	_socialModule 		= _player.getModule(APIModules.SOCIAL);
    	_menuModule		= _player.getModule(APIModules.MENU);
    	if( id == "stv_livestream" || id == "embed-livestream") 
    		isLive = true;
   }   
   
};

/** Event handler for when the player the player first loads : call from stv embed code script BrightcoveExternals.js. **/
function onExtTemplateLoaded(id) 
{
   if (id == "stv_brightcove" || id == "stv_livestream")
   {
    	_player 		= brightcove.getExperience(id);    
    	_experienceModule 	= _player.getModule(APIModules.EXPERIENCE);		// stage
    	_experienceModule.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
    	_chromelessPlayer = (_experienceModule.getElementsByType("ChromelessVideoPlayer"))[0];
    	_chromelessPlayer.addEventListener(BCMediaEvent.BEGIN, onMediaBegin);                        	
    	_chromelessPlayer.addEventListener(BCMediaEvent.COMPLETE, onMediaComplete);
	_chromelessPlayer.addEventListener(BCMediaEvent.PROGRESS, onMediaEvent);
    	_chromelessPlayer.setRenditionSelectionCallback(selectRendition);
    	_socialModule 		= _player.getModule(APIModules.SOCIAL);
    	_menuModule		= _player.getModule(APIModules.MENU);

   }
};




$(document).ready(function () 
{
  if ($("a.brightcove").length > 0 && $("#stv_brightcove").length <= 0)
  {
	$.getScript('http://admin.brightcove.com/js/BrightcoveExperiences_all.js', function() 
	{
	    $.ajax({
		url: "/cs/Satellite?pagename=ServusTV/Common/BrightcovePlayer",
		cache: false,
		success: function(html){
		    $("body").append(html);
		}
	    });
	});
  }		
  
  $("#liveplayerlink a").live("click", function(event)
  {
  	event.preventDefault();
  	var livebc 		= brightcove.getExperience("embed-livestream");    
	if (livebc)
	{
		var liveexp	= livebc.getModule(APIModules.EXPERIENCE);		
	       	var liveplayer = (liveexp.getElementsByType("ChromelessVideoPlayer"))[0];
    	
  		if (liveplayer)	liveplayer.play();
  		$(this).parent().remove();
  	}
  });
  

  $('a.brightcove').live('click', function(event) 
  {
	event.preventDefault();
	showPlayer();  	

	var videolist = new Array();
	var video;
	var array = $(this).children('input[name="videoList.format"]');
	if (array.length > 0)
		videolist[0] = array[0].value;
	array = $(this).children('input[name="videoList.subcategory"]');
	if (array.length > 0)
		videolist[1] = array[0].value;
	array = $(this).children('input[name="videoList.category"]');
	if (array.length > 0)
		videolist[2] = array[0].value; 	
	array = $(this).children('input[name="videoList.featured"]');
	if (array.length > 0)
		video = array[0].value;
	playVideo(event, video, videolist);
  });
  
  
  $(closebtn).live("click", function(event)
  {
  	event.preventDefault();
  	hidePlayer();
  });


});


/** Event handler for when the player is ready for interaction. **/
function onTemplateReady(event) 
{
    _playlist 	 = _experienceModule.getElementByID("videoList");
    _swf_overlay = _experienceModule.getElementByID('themedOverlay');

    _experienceModule.removeEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
    
    
    if (currentVideo && currentPlaylist)
    {
	playVideo (null, currentVideo, currentPlaylist);
	
    }
    else if (_chromelessPlayer && isLive == true) 
    {
    	var playlist = new Array()
    	playlist[0] = "latest";
	playVideo(null, 1368212533001, playlist);
    }
    
    _adModule = _player.getModule(APIModules.ADVERTISING);
    _adModule.addEventListener(BCAdvertisingEvent.AD_PROGRESS, onAdProgress);
    _adModule.addEventListener(BCAdvertisingEvent.AD_COMPLETE, onAdComplete);
    
}
function onAdProgress(event)
{ 
	if(_chromelessPlayer)
		_chromelessPlayer.showControls(true);
}
function onAdComplete(event)
{ 
	if(_chromelessPlayer)
		_chromelessPlayer.showControls(false);
}



/** start to play the indicated video from the indicated playlist in the Eer **/
function playVideo(event, video, playlist)
{
    currentVideo = video;
    currentPlaylist = playlist;
    currentPlaylistLevel = 0;
    
    if (_experienceModule)
    {
    	var collId = 0;
    	if (currentPlaylist[currentPlaylistLevel] && currentPlaylist[currentPlaylistLevel] != "null" && currentPlaylist[currentPlaylistLevel] != 0)
    	    collId = currentPlaylist[currentPlaylistLevel];
    	else if (currentPlaylist[++currentPlaylistLevel] && currentPlaylist[currentPlaylistLevel] != "null" && currentPlaylist[currentPlaylistLevel] != 0)
    	    collId = currentPlaylist[currentPlaylistLevel];
    	else if (currentPlaylist[++currentPlaylistLevel] && currentPlaylist[currentPlaylistLevel] != "null" && currentPlaylist[currentPlaylistLevel] != 0)
    	    collId = currentPlaylist[currentPlaylistLevel];
    	    
    	if (collId != 0)
    	{
    		_contentModule 	= _player.getModule(APIModules.CONTENT);		// content retrieval
		_contentModule.addEventListener(BCContentEvent.MEDIA_COLLECTION_LOAD, onMediaCollectionLoad);    
    		_contentModule.getMediaCollectionAsynch(collId, "referenceId");
    	}
    	if (currentVideo && isLive && _chromelessPlayer) 
    		_chromelessPlayer.loadVideo(currentVideo);
    	else if (currentVideo && isVisible && _chromelessPlayer) 
    		_chromelessPlayer.loadVideo(currentVideo, "referenceId");
    		
    }   
}


/** Event handler for media collection load **/
function onMediaCollectionLoad(event) 
{
	if(_contentModule) 
	{
		if (event.mediaCollection)
		{
			var videoDTO = _contentModule.getMedia(currentVideo, "referenceId");
			var index = -1;
					
			// This means the mediaCollection is a playlist or group of videos
			var mediaDTOs = new Array();
			for(var i = 0; i < event.mediaCollection.mediaCount; i++) 
			{
				var video = event.mediaCollection.mediaIds[i];
				if (video)
				{
					mediaDTOs[i] = _contentModule.getMedia(event.mediaCollection.mediaIds[i]);
					if (videoDTO && video == videoDTO.id)
						index = i;					
				}
			}
			_playlist.setData(mediaDTOs);
			var pageindex = 0;
			if (index >= 0)
			{
			    pageindex = Math.floor(index/5);
			    if (pageindex != _playlist.getPageIndex())
				_playlist.showPage(pageindex);    
			    _playlist.setSelectedIndex(index);
			    setLogoOverlay(videoDTO);
			    if(_socialModule) _socialModule.setLink(videoDTO.linkURL);
		
			}
			_playlist.addEventListener('elementClick', onMediaChange);

		}
		else if (currentPlaylist[++currentPlaylistLevel])
			_contentModule.getMediaCollectionAsynch(currentPlaylist[currentPlaylistLevel], "referenceId");
	}
	
}

/** Event handler for media begin **/
function onMediaBegin(event) 
{
	if (!isVisible)
	{
		if (_chromelessPlayer)
			_chromelessPlayer.stop();
	}	
	else {
		p20 = false; p40=false; p60=false; p80=false;
		var video = event.media;
		if (video)
		{
			var playername = (typeof(ext) == 'undefined') ? _experienceModule.getPlayerName() : ext;
			var videotype = 'vod';
			if (video.referenceId && video.referenceId.toString().indexOf('trailer')>= 0)
				videotype = 'trailer';
			else if (video.tags)
			{
				for (var i = 0; i < video.tags.length; i++) {
			        	if (video.tags[i] == 'trailer') 
			        		videotype = 'trailer';
        			}
			}
			
			trackVideoProgress(video, 0);
			
			if (document.szmpixel)
			{
				// SZM according https://www.infonline.de/downloads/9-1356-493/INFOnline_Ajaxmessung.pdf
				var IVW= "http://servustv.ivwbox.de/cgi-bin/ivw/CP/videodetail";
				document.szmpixel.src = IVW+"?r="+escape(document.referrer)+"&d="+(Math.random()*100000);
			}
			if (document.oewapixel)
			{
				// OEWA VERSION="1.6" 
				var OEWA="http://servustv.oewabox.at/cgi-bin/ivw/CP/RedCont/Sonstiges/Sonstiges/servustv.com/";
				document.oewapixel.src = OEWA+"?r="+escape(document.referrer)+"&d="+(new Date()).getTime();
			}
		}
	}
	
}

/** Event handler for media complete **/
function onMediaComplete(event) 
{
	trackVideoProgress(event.media, 100);
}

/** Event handler for media progress **/
function onMediaEvent(event)
{
	duration = event.duration;
	position = event.position;
	progress = Math.floor((position / duration) * 100);
	if (p20 == false && progress >= 20) {
		trackVideoProgress(event.media, 20); p20 = true;
	}
	else if (p40 == false && progress >= 40)  {
		trackVideoProgress(event.media, 40); p40 = true;
	}
	else if (p60 == false && progress >= 60) { 
		trackVideoProgress(event.media, 60); p60 = true;
	} 	
	else if (p80 == false && progress >= 80) { 
		trackVideoProgress(event.media, 80); p80 = true;
	}
}

/** track video progess **/
function trackVideoProgress(video, percent)
{
	if (video)
	{
		var playername = (typeof(ext) == 'undefined') ? _experienceModule.getPlayerName() : ext;
		var videotype = 'vod';
		if (video.referenceId && video.referenceId.toString().indexOf('trailer')>= 0)
			videotype = 'trailer';
		var clip_ev = 'progress';
		var vp_start = '';
		if (percent == 100)
			clip_ev = 'complete';
		else if (percent == 0)
		{
			clip_ev = "start"
			vp_start = '1';
		}
		
		
		dcsMultiTrack(
			'WT.clip_ev',  clip_ev,
			'WT.ti', video.displayName,
			'WT.z_asset', 'video',
			'DCSext.aid', video.referenceId,
			'DCSext.videoplayer', playername,
			'DCSext.videotype', videotype,
			'DCSext.videoprogress', percent,
			'WT.clip_n', video.displayName,
			'WT.clip_t', 'Video',
			'DCS.vp_start', vp_start);
	}		
}


/** Event handler for media change **/
function onMediaChange(event) 
{
	var video;
	if (event.elementData)
	{
		video = event.elementData;
		_chromelessPlayer.loadVideo(video.id);
	}
		
	if (video)
	{
		setLogoOverlay(video);
		if(_socialModule) _socialModule.setLink(video.linkURL);
	
	}
	
}


/** load the rbtv swf overlay if required **/
function setLogoOverlay(media)
{
	if (_swf_overlay)
	{
		var streamname = media.FLVFullLengthURL;
		if (streamname && streamname.match("mp4:RB")=="mp4:RB" && !streamname.match("TR_"))
		{
			_swf_overlay.setSource('http://www.servustv.com/cs/ServusTV/swf/stv_rb_overlay_03.swf');
			_swf_overlay.setVisible(true);
		}
		else
			_swf_overlay.setVisible(false);
	}
}





/** The callback for rendition changes */
function selectRendition(context) {
    var renditions = context.renditions.slice();
    var heightMatch;
    var currentRendition;
    var selectedRendition;
    var bandwidth = context.detectedBandwidth*1000;
    var height = context.screenHeight;
    for (var i = 0; i < renditions.length; i++) {
        currentRendition = renditions[i];
        if (isNaN(currentRendition.frameHeight)) continue;
        if (isNaN(currentRendition.encodingRate) && bandwidth > -1) continue;
        // bandwidth hasn't yet need detected, look at height
        if (bandwidth == -1) {
            // set the rendition that most closely matches screen height
            if (heightMatch == null
                || Math.abs(currentRendition.frameHeight-height) < Math.abs(heightMatch.frameHeight-height)
            ) {
                heightMatch = currentRendition;
            }
        // if bandwidth has been detected, look at encoding rate;
        // only look at renditions that have encoding rate and height that is less than
        // the current bandwidth and screen height, within a tolerance setting
        } else if (bandwidth > -1
                    && currentRendition.encodingRate <= bandwidth*ENCODING_RATE_TOLERANCE
                    && currentRendition.frameHeight <= height*FRAME_HEIGHT_TOLERANCE
        ) {
            // check whether current rendition being evaluated is closer match than last one assigned to selectedRendition
            if (selectedRendition != null) {
            	
                // if this rendition is closer than previous assigned, use it
                if ( currentRendition.frameHeight >  selectedRendition.frameHeight) {
                    selectedRendition = currentRendition;
                    break;
                } 
            } else {
                selectedRendition = currentRendition;
            }
        }
    }
    // if we couldn't find anything under the current bandwidth and size...
    if (selectedRendition == null) {
        // bandwidth has been detected, so find the closest encoding
        if (bandwidth > -1) {
            // sort renditions first by encoding, then by height
            renditions = sortRenditions(renditions);
            var bandwidthMatch;
            for (var i = 0; i < renditions.length; i++) {
                currentRendition = renditions[i];
                if (isNaN(currentRendition.encodingRate)) continue;
                if (bandwidthMatch == null) {
                    bandwidthMatch = currentRendition;
                // if this rendition is closer in desired encoding than the previous, use it
                } else if (Math.abs(currentRendition.encodingRate-bandwidth*ENCODING_RATE_TOLERANCE) < Math.abs(bandwidthMatch.encodingRate-bandwidth*ENCODING_RATE_TOLERANCE)) {
                    bandwidthMatch = currentRendition;
                }
            }
            selectedRendition = bandwidthMatch;
        } else if (heightMatch != null) {
            // just grab the closest in height since we have no bandwidth data
            selectedRendition = heightMatch;
        }
    }
    // find the index in the initial list
    var renditionIndex = 0;    
    for (var i = 0; i < context.renditions.length; i++) {
	if (selectedRendition == context.renditions[i]) {
	    renditionIndex = i;
	    break;
	}
    }
    return renditionIndex;
}

/** Sorts renditions first by bandwidth, then by frame height */
function sortRenditions(renditions) {
    // first, sort by encoding
    renditions.sort(sortByEncoding);
    // run through sorted list and place same encodings into their own arrays
    var encodingRenditions = {};
    for (var i = 0; i < renditions.length; i++) {
        if (encodingRenditions[renditions[i].encodingRate] == null) {
            encodingRenditions[renditions[i].encodingRate] = [];
        }
        encodingRenditions[renditions[i].encodingRate].push(renditions[i]);
    }
    // now sort all nested arrays and put them back into single array
    var sortedRenditions = [];
    for (var i in encodingRenditions) {
        encodingRenditions[i].sort(sortByFrameHeight);
        sortedRenditions = sortedRenditions.concat(encodingRenditions[i]);
    }
    return sortedRenditions;
}

/** Sorts two renditions by encoding rate value. **/
function sortByEncoding(a, b) {
    var x = a.encodingRate;
    var y = b.encodingRate;
    return ((x < y) ? 1 : ((x > y) ? -1 : 0));
}

/** Sorts two renditions by frame height value. **/
function sortByFrameHeight(a, b) {
    var x = a.frameHeight;
    var y = b.frameHeight;
    return ((x < y) ? 1 : ((x > y) ? -1 : 0));
}
