// CSS Browser Selector   v0.2.5
// Documentation:         http://rafael.adm.br/css_browser_selector
// License:               http://creativecommons.org/licenses/by/2.5/
// Author:                Rafael Lima (http://rafael.adm.br)
// Contributors:          http://rafael.adm.br/css_browser_selector#contributors
var css_browser_selector = function() {
	var
		ua=navigator.userAgent.toLowerCase(),
		is=function(t){ return ua.indexOf(t) != -1; },
		h=document.getElementsByTagName('html')[0],
		b=(!(/opera|webtv/i.test(ua))&&/msie (\d)/.test(ua))?('ie ie'+RegExp.$1):is('gecko/')? 'gecko':is('opera/9')?'opera opera9':/opera (\d)/.test(ua)?'opera opera'+RegExp.$1:is('konqueror')?'konqueror':is('applewebkit/')?'webkit safari':is('mozilla/')?'gecko':'',
		os=(is('x11')||is('linux'))?' linux':is('mac')?' mac':is('win')?' win':'';
	var c=b+os+' js';
	h.className += h.className?' '+c:c;
}();

SecToObj = function(s){
    if (s < 0)
        s = 0;

    var h = Math.floor(s / 3600);
    s -= h * 3600;
    var m = Math.floor(s / 60);
    s -= m * 60;
    
    return {'hour':h, 'minute':m, 'second':s};
};

var qmp;
var scrubRate = 0;
var TIME_LIMIT = 120;
var URL_PREFIX = '';
var clipDuration;

function OnPlayerLoaded(player){
		if(player){
				qmp = player;
				//show the pageLoading DIV again, so the user knows something is happening
				$('pageLoading').style.display = 'block';

				//show the playerOverlay (contains error image) if it exists -- the user has installed the player, so it's safe
				if($('playerOverlay'))
						$('playerOverlay').style.display = 'block';


				MN.Event.Observe($('mn_pause'), 'click', Pause);
				MN.Event.Observe($('mn_play'), 'click', Play);
				MN.Event.Observe(qmp, 'PausedChanged', SwapPausePlay);
				MN.Event.Observe(qmp, 'PlayStateChanged', OnPlayStateChanged);
				MN.Event.Observe(qmp, 'ShowChanged', OnShowChanged);
				MN.Event.Observe(qmp, 'BitRateChanged', OnBitRateChanged);
				qmp.volumebar = new MN.PlayerUI.VolumeBar(qmp, 'mn_volume_bar');
				
				if(params.start && params.show && params.stop){
						params.stop = params.start + TIME_LIMIT;
						log('PAGE: have send-to-friend link,attempting to play: ', params.show, ' start: ', params.start, ' stop: ', params.stop);
						qmp.Play(URL_PREFIX + params.show, params.start, params.stop);
				}
				else{
						log('no s2f link,trying to play live content');
						qmp.Load(MN.TP.CONFIG.channels[0].url);
						MN.Event.Observe(qmp, 'TimelineLoaded', PlayLiveClip);
				}
				//clipDuration = SecToHMS(params.stop - params.start);
				//var setPos = setInterval('SetPosition()',250);
		}
}

function PlayLiveClip(qvt){
	MN.Event.StopObserving(qmp, 'TimelineLoaded', PlayLiveClip);
	params.start = (qvt.Duration() - 420 < 0) ? 0 : qvt.Duration() - 420;
	params.stop = params.start + TIME_LIMIT;
	qmp.Play(qvt.qvtURL, params.start, params.stop);
}

function Pause(){
    log('pause');
    qmp.Paused(true);
    SetStatusMsg('Pausa');
}

function Play(){
    log('play');
	if(qmp.scrubbing)
	{
		qmp.StopScrubbing();
		scrubRate = 0;
	}
	qmp.Paused(false);
	var br = qmp.CurrentBitRate();
	if(br > 0)
		SetStatusMsg('Conexi\u00f3n: ' + br + 'kbps');
  else
    SetStatusMsg('Conectado ');
}

function SwapPausePlay(paused){
	$('mn_pause').style.display = paused ? 'none' : 'block';
    $('mn_play').style.display = paused ? 'block' : 'none';
}

OnBitRateChanged = function(newBR){
    if(scrubRate == 0)
      SetStatusMsg('Conexi\u00f3n: ' + newBR + 'kbps');
};

function OnPlayStateChanged(oldPS, newPS){
		if(!qmp.scrubbing){
				//make sure the video player is visible
		    $('mn_player').style.visibility = (newPS == MN.QMP.PS.Error || newPS == MN.QMP.PS.MediaEnded) ? 'hidden' : 'visible';
						
				if(newPS == MN.QMP.PS.Playing){
					MN.Cookie.Set('esmastvdemo',1,365); //set the cookie once the user has actually seen some content
					SetStatusMsg('Conexi\u00f3n: ' + qmp.CurrentBitRate() + 'kbps');       
		      		//make sure the pause button is now showing because we are playing
					SwapPausePlay(false);
					//make the duration visible		
					$('mn_duration').style.textIndent = '0';
					//hide the pageLoading DIV
					if($('pageLoading').style.display == 'block')
						$('pageLoading').style.display = 'none';
		    }
		    else if(newPS == (MN.QMP.PS.Loading || MN.QMP.PS.Buffering))
						SetStatusMsg('Cargando');
				else if(newPS == MN.QMP.PS.Opening) 		SetStatusMsg('Abriendo');
				else if(newPS == MN.QMP.PS.Stopped)			SetStatusMsg('Parado');
				else if(newPS == MN.QMP.PS.Waiting)			SetStatusMsg('Esperando');
				else if(newPS == MN.QMP.PS.Stalled)			SetStatusMsg('Cargando');//Atascando
				else if(newPS == MN.QMP.PS.Init)				SetStatusMsg('Inicializando');
				else if(newPS == MN.QMP.PS.Authorizing)	SetStatusMsg('Autorizando');
				else if(newPS == MN.QMP.PS.MediaEnded){
						SetStatusMsg('Video Terminado');
						$('signupOverlay').style.left = '0px';
						$('errorOverlay').style.left = '-9000px';
				}
				else if(newPS == MN.QMP.PS.Error){
						SetStatusMsg('Error');
						$('errorOverlay').style.left = '0px';
						$('signupOverlay').style.left = '-9000px';
				}
				else
						SetStatusMsg(MN.QMP.PS[newPS]);
				
		}
}

function OnShowChanged(showNum, title){
	var qvt = qmp.CurrentQVT();
    //if the clip passes the length of the QVT (ie end of day) AND IS NOT TODAY'S QVT, only play to the end of the QVT
    if(params.stop > qmp.Duration() && !qmp.qvt.HaveAnyLive())
    		params.stop = qmp.Duration();
    else if(params.stop >= qmp.Duration() && qmp.qvt.HaveAnyLive()) {
				setTimeout('CheckPosition()',100000);
    }
    clipDuration = SecToHMS(params.stop - params.start);
		setInterval('SetPosition()',250);

	//sometimes the player throws an invalid show number.  This is a known, filed bug that
	//has not been fixed in the SDK yet
    if(showNum < 0 || showNum >= qvt.ShowCount()){
        showNum = qvt.ShowCount() - 1;
        title = qvt.Title(showNum);
    }

	if($('mn_show_title_center'))
    	$('mn_show_title_center').innerHTML = '<b>Est\u00e1s viendo:</b> ' + title;
}

function SetStatusMsg(msg){
	MN.SetInnerText($('mn_player_status'), msg);
}

function SecToHMS(sec){ //converts a number of seconds into h?:mm:ss format (from 00:00:00)
	var hmsFormat = SecToObj(sec);
	
	//pad seconds with a 0; if seconds = 60, increment minute & show correctly
	if(hmsFormat.second.toFixed(0) < 10)
		hmsFormat.second = '0' + hmsFormat.second.toFixed(0);
	else if(hmsFormat.second.toFixed(0) == 60){
		hmsFormat.second = '00';
		hmsFormat.minute ++;
	}
	else
		hmsFormat.second = hmsFormat.second.toFixed(0);
	
	//pad minutes with a 0; if minutes = 60, increment hour and show correctly
	if (hmsFormat.minute < 10)
			hmsFormat.minute = '0' + hmsFormat.minute;
	else if(hmsFormat.minute == 60) {
			hmsFormat.minute = '00';
			hmsFormat.hour++;
	}
	
	//return as h?:mm:ss
	if (hmsFormat.hour == 0)
			return (hmsFormat.minute + ':' + hmsFormat.second);
	else
			return (hmsFormat.hour + ':' + hmsFormat.minute + ':' + hmsFormat.second);
}

function SetPosition(){
	var curPos = SecToHMS(qmp.CurrentPosition() - params.start);
	MN.SetInnerText($('mn_duration'), curPos + ' / ' + clipDuration);
	return;
}
function CheckPosition() {
	if(qmp.CurrentPosition() >= params.stop){
		qmp.Stop();
		setTimeout('OnPlayStateChanged(MN.QMP.PS.Stopped,MN.QMP.PS.MediaEnded)',500);
	}
	else
		setTimeout('CheckPosition()',250);
}

var params;
function WindowLoaded(){
    // Even though there is nothing asynchronous in either of these two functions,
    // calling them without a timeout causes the second function to execute before
    // the first has had a chance to redirect to the geoserver and get a cookie.
	SetUpGeo();
	setTimeout(FinishPageSetup,750);
}
function SetUpGeo(){
    var p = MN.GetPageParams();
	if(p.videovalid)
		MN.Cookie.Set("videovalid", p.videovalid);
	
	//Geofilter -- restrict page viewing to users outside the US
    MN.Geo.Init('http://gksrv.tarabu.com/esmasgeo');
}
function FinishPageSetup(){
	if (!MN.Geo.IsUserAllowed('not [*|*|usa|*]'))	//false means user is in the US; redirect
		window.location = 'http://www.esmas.com/tv';
	
	//hide pageLoading DIV -- we'll re-open it after the player is loaded (don't keep displaying if they have to install)
	$('pageLoading').style.display = 'none';
	params = MN.GetPageParams();
	if(params.start)
		params.start = parseFloat(params.start);
	if(params.stop)
		params.stop = parseFloat(params.stop);
	if(params.debug)
		MN.Log.ShowPane(500);

	if(window.CustomWindowLoaded){
		CustomWindowLoaded();    
	}
	InitPopups();

	log('new new');
	log('PAGE: all good, call MN.QVT.CreatePlayer');
	MN.QVT.CreatePlayer('mn_player', OnPlayerLoaded, '100%', '100%');
}


//InitPopups-------------------------------------------------------------------------------//
//Parses the page and finds anchor tags with the classname "mn_popup" and modifies them so //
//that they open up a popup window instead of following the standard anchor tag behavior.  //
//-----------------------------------------------------------------------------------------//
InitPopups = function(){
		log('PAGE: Initializing popups from anchor tags');
		// var anchors = document.body.getElementsByTagName('a');
		var anchors = $('mn_container').getElementsByTagName('a');
		var curAnchor;
		for(var i = 0; i < anchors.length; i++){
		    curAnchor = anchors[i];
				if(curAnchor.className == 'mn_popup'){
						var func = MN.MakeBound(curAnchor, PopupWin);
						MN.Event.Observe(curAnchor, 'click', func);
						curAnchor.onclick = function(){return false;};
				}
		}
		log('PAGE: Done with popups');
};
//PopupWin--------------------------------------------------------------------------//
//This is called when a user clicks on an anchor that has been set as a "popup" via //
//InitPopups.  It opens a new window to the link.                                   //
//----------------------------------------------------------------------------------//
PopupWin = function(){
		//the function has been bound via MN.MakeBound, so "this" references the anchor element
		var width = this.getAttribute('popup_width') || 650;
		var height = this.getAttribute('popup_height') || 664;
		var scroll = this.getAttribute('popup_scroll') != 'false' ? 'yes' : 'no';
		var resize = this.getAttribute('popup_resize') != 'false' ? 'yes' : 'no';
		var title = this.getAttribute('popup_title') ? this.getAttribute('popup_title').replace(/ /g,'_') : 'popup';
		window.open(this.getAttribute('href'),title,'width=' + width + ',height=' + height + ',status=yes,scrollbars=' + scroll + ',resizable=' + resize + ',location=no,toolbar=no');
};

MN.Event.Observe(window, 'load', WindowLoaded);