/**********************************************************************************************************************/
/****************************************** MOBILE BROWSER DETECTION CODE *********************************************/
/**********************************************************************************************************************/
var contavid=1;
var relidGlobal = '';

// JavaScript Document
// Web: www.hand-interactive.com
// 
// License info: http://creativecommons.org/licenses/by/3.0/us/

//Initialize some initial string variables we'll look for later.
var deviceIphone = "iphone";
var deviceIPad = "ipad";
var deviceIpod = "ipod";
var devicePlaystation = "playstation";
var deviceWap = "wap";

var deviceWinMob = "windows ce";
var enginePie = "wm5 pie";
var deviceIeMob = "iemobile";

var deviceS60 = "series60";
var deviceSymbian = "symbian";
var deviceS60 = "series60";
var deviceS70 = "series70";
var deviceS80 = "series80";
var deviceS90 = "series90";

var deviceBB = "blackberry";

var deviceAndroid = "android";
var motorollaDroid = " droid ";

var deviceMidp = "midp";
var deviceWml = "wml";
var deviceBrew = "brew";

var devicePalm = "palm";
var engineXiino = "xiino";
var engineBlazer = "blazer"; //Old Palm

var devicePda = "pda";
var deviceNintendoDs = "nitro";

var engineWebKit = "webkit";
var engineNetfront = "netfront";


var manuSonyEricsson = "sonyericsson";
var manuericsson = "ericsson";
var manuSamsung1 = "sec-sgh";

var svcDocomo = "docomo";
var svcKddi = "kddi";
var svcVodafone = "vodafone";

//Due to the flexibility of the S60 OSSO Browser, 
//   you may wish to let new S60 devices get the regular pages instead.
var s60GetsMobile = true;

//Due to the flexibility of the iPhone/iPod Touch Browser, 
//   you may wish to let new S60 devices get the regular pages instead.
var iphoneIpodGetsMobile = true;

var origenVideo = "bc";
var externoIdVideo;
var externoIdWidth;
var externoIdHeight;

//**************************
// Detects if the current device is an iPhone.
function DetectIphone()
{
   if (uagent.search(deviceIphone) > -1)
   {
      //The iPod touch says it's an iPhone! So let's disambiguate.
      if (uagent.search(deviceIpod) > -1)
         return false;
      else 
         return true;
   }
   else
      return false;
}

//**************************
// Detects if the current device is an iPhone.
function DetectIPad()
{
    if (uagent.search(deviceIPad) > -1) {
	return true;       
   }
    else {
      return false;
    }
}

//**************************
// Detects if the current device is an iPod Touch.
function DetectIpod()
{
   if (uagent.search(deviceIpod) > -1)
      return true;
   else
      return false;
}

//**************************
// Detects if the current device is an iPhone or iPod Touch.
function DetectIphoneOrIpodOrIPad()
{
   //We repeat the searches here because some iPods 
   //  may report themselves as an iPhone, which is ok.
   if (uagent.search(deviceIphone) > -1 ||
       uagent.search(deviceIpod) > -1 ||
       uagent.search(deviceIPad) > -1)

       return true;
    else
       return false;
}

//**************************
// Detects if the current device is an Android OS-based device.
function DetectAndroid()
{
   if (uagent.search(deviceAndroid) > -1)
      return true;
   else
      return false;
}

function DetectMotorollaDroid()
{
	if (uagent.search(motorollaDroid) > -1)
		return true;
	else
		return false;
}

//**************************
// Detects if the current device is an Android OS-based device and
//   the browser is based on WebKit.
function DetectAndroidWebKit()
{
   if (DetectAndroid())
   {
     if (DetectWebkit())
        return true;
     else
        return false;
   }
   else
      return false;
}

//**************************
// Detects if the current browser is based on WebKit.
function DetectWebkit()
{
   if (uagent.search(engineWebKit) > -1)
      return true;
   else
      return false;
}

//**************************
// Detects if the current browser is the Nokia S60 Open Source Browser.
function DetectS60OssBrowser()
{
   if (DetectWebkit())
   {
     if ((uagent.search(deviceS60) > -1 || 
          uagent.search(deviceSymbian) > -1))
        return true;
     else
        return false;
   }
   else
      return false;
}

//**************************
// Detects if the current device is any Symbian OS-based device,
//   including older S60, Series 70, Series 80, Series 90, and UIQ, 
//   or other browsers running on these devices.
function DetectSymbianOS()
{
   if (uagent.search(deviceSymbian) > -1 ||
       uagent.search(deviceS60) > -1 ||
       uagent.search(deviceS70) > -1 ||
       uagent.search(deviceS80) > -1 ||
       uagent.search(deviceS90) > -1)
      return true;
   else
      return false;
}


//**************************
// Detects if the current browser is a BlackBerry of some sort.
function DetectBlackBerry()
{
   if (uagent.search(deviceBB) > -1)
      return true;
   else
      return false;
}

//**************************
// Detects if the current browser is a Windows Mobile device.
function DetectWindowsMobile()
{
   //Most devices use 'Windows CE', but some report 'iemobile' 
   //  and some older ones report as 'PIE' for Pocket IE. 
   if (uagent.search(deviceWinMob) > -1 ||
       uagent.search(deviceIeMob) > -1 ||
       uagent.search(enginePie) > -1)
      return true;
   else
      return false;
}

//**************************
// Detects if the current browser is on a PalmOS device.
function DetectPalmOS()
{
   //Most devices nowadays report as 'Palm', 
   //  but some older ones reported as Blazer or Xiino.
   if (uagent.search(devicePalm) > -1 ||
       uagent.search(engineBlazer) > -1 ||
       uagent.search(engineXiino) > -1)
      return true;
   else
      return false;
}

//**************************
// Sets whether S60 devices running the 
//   Open Source Browser (based on WebKit)
//   should be detected as 'mobile' or not.
//   Set TRUE to be detected as mobile.
//   Set FALSE and it will not be detected as mobile.
function SetS60GetsMobile(setMobile)
{
   s60GetsMobile = setMobile;
};

//**************************
// Sets whether iPhone/iPod Touch devices running the 
//   Open Source Browser (based on WebKit)
//   should be detected as 'mobile' or not.
//   Set TRUE to be detected as mobile.
//   Set FALSE and it will not be detected as mobile.
function SetS60GetsMobile(setMobile)
{
   iphoneIpodGetsMobile = setMobile;
};


//**************************
// Check to see whether the device is a 'smartphone'.
//   You might wish to send smartphones to a more capable web page
//   than a dumbed down WAP page. 
function DetectSmartphone()
{
   //First, look for iPhone and iPod Touch.
   if (DetectIphoneOrIpodOrIPad())
      return true;

   if (DetectAndroid())
      return true;
		
   //Now, look for S60 Open Source Browser on S60 release 3 devices.
   if (DetectS60OssBrowser())
      return true;

   //Check for other Symbian devices - older S60, UIQ, other.
   if (DetectSymbianOS())
      return true;

   //Check for Windows Mobile devices.
   if (DetectWindowsMobile())
      return true;

   //Next, look for a BlackBerry
   if (DetectBlackBerry())
      return true;

   //PalmOS.
   if (DetectPalmOS())
      return true;

   //Otherwise, return false.
   return false;
};


//**************************
// Detects if the current device is a mobile device.
//  This method catches most of the popular modern devices.
function DetectMobileQuick()
{
   //Attempt to detect most mobile devices, 
   //   especially mass market feature phones.
   // NOTE: Doesn't usually work reliably...
   if (uagent.search(deviceWap) > -1   || 
	uagent.search(deviceMidp) > -1 ||
	uagent.search(deviceWml) > -1  ||
	uagent.search(deviceBrew) > -1  )
   {
      return true;
   }

   //Detect for most smartphones.
   if (DetectSmartphone())
      return true;

   //Check for a NetFront browser
   if (uagent.search(engineNetfront) > -1)
      return true;

   //Check for a Playstation
   if (uagent.search(devicePlaystation) > -1)
      return true;

   //Check for a generic PDA
   if (uagent.search(devicePda) > -1)
      return true;

   return false;
};


//**************************
// Detects in a more comprehensive way if the current device is a mobile device.
function DetectMobileLonger()
{
   //Run the quick check first.
   if (DetectMobileQuick())
      return true;

   //Check for NTT Docomo
   if (uagent.search(svcDocomo) > -1)
      return true;

   //Check for KDDI
   if (uagent.search(svcKddi) > -1)
      return true;

   //Check for Nintendo DS
   if (uagent.search(deviceNintendoDs) > -1)
      return true;

   //Check for Vodafone 3G
   if (uagent.search(svcVodafone) > -1)
      return true;

   //Finally, detect for certain very old devices with stupid useragent strings.
   if (uagent.search(manuSamsung1) > -1 ||
	uagent.search(manuSonyEricsson) > -1 || 
	uagent.search(manuericsson) > -1)
   {
      return true;
   }

   return false;
};

/**********************************************************************************************************************/
/****************************************** BC VIDEO CODE *********************************************/
/**********************************************************************************************************************/

//añadido por jsj inSkin
var inSkin = false;



var iID_PlayerABC = 86420195001;
var iID_PlayerABCSevilla = 89109300001;
//añadido por jsj
var iID_PlayerABCINSKIN = 1168613457001;
var iID_PlayerABCSevillaINSKIN = 1173947627001;
//
var iID_PlayerABCPub = 55814260001;
var iID_PlayerABCSevillaPub = 78536835001;
var BCReadAPITokenABC = "mktQkMtsK79ovsIrktL3WfIGFQUgmNzsYQDJYkCj_Wqgl2kdJFVS2g..";
var BCReadAPITokenABCSevilla = "g8-skE-PoYrWXzgvA0WDv-yN9IYqIxW4WHul_q8zqcmEeLdwOKLRCA..";

var sMarcaAgua = '';//'marcasagua/boton_player_def.png';//'marcasagua/play.png';
var sPosmarca='C';
var sTransparencia=85;
//Initialize our user agent string.
var uagent = navigator.userAgent.toLowerCase();

//detect if this is a smartphone or not
var thisIsSmartPhone = DetectSmartphone();

function mandarOAS() {
return getOAS_sitepage(OAS_sitepage);
}
function obtenerVideoBC(idDiv,code_publisher,code_player,code_video,width,height,isVideoMP,classIframe){

	if ('bc'==origenVideo) {
		if (!thisIsSmartPhone) {
			var s1 ='<object id="flashObj-'+code_video+'" width="'+width+'" height="'+height+'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,47,0">';
			s1 +='<param name="movie" value="http://c.brightcove.com/services/viewer/federated_f9/'+code_player+'?isVid=1&isUI=1" />';
			s1 +='<param name="bgcolor" value="#000000" />';
			s1 +='<param name="flashVars" value="@videoPlayer='+code_video+'&playerID='+code_player+'&domain=embed&dynamicStreaming=true&videoSmoothing='+isVideoMP+'" />';
			s1 +='<param name="base" value="http://admin.brightcove.com" />';
			s1 +='<param name="seamlesstabbing" value="false" />';
			s1 +='<param name="allowFullScreen" value="true" />';
			s1 +='<param name="swLiveConnect" value="true" />';
			s1 +='<param name="wmode" value="opaque" />';
			s1 +='<param name="allowScriptAccess" value="always" />';
			s1 +='<embed src="http://c.brightcove.com/services/viewer/federated_f9/'+code_player+'?isVid=1&isUI=1" bgcolor="#000000" ';
			s1 +='flashVars="@videoPlayer='+code_video+'&playerID='+code_player+'&&domain=embed&dynamicStreaming=true&videoSmoothing='+isVideoMP+'" ';
			
			//MODIFICADO POR JSJ
			//s1 +='base="http://admin.brightcove.com" name="flashObj" width="'+width+'" height="'+height+'" seamlesstabbing="false" ';
			s1 +='base="http://admin.brightcove.com" name="flashObj-'+code_video+'" width="'+width+'" height="'+height+'" seamlesstabbing="false" ';
			s1 +='type="application/x-shockwave-flash" allowFullScreen="true" allowScriptAccess="always" swLiveConnect="true" wmode="opaque"';
			s1 +='pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash">';
			s1 +='</embed>';
			s1 +='</object>';
			return s1;
		}else{
			if (code_player==iID_PlayerABC){
				sReadToken=BCReadAPITokenABC;
				//Cambiamos el code_player para quitar el autoplay
				code_player=903427157001;
			}else{
				sReadToken=BCReadAPITokenABCSevilla;
				//Cambiamos el code_player para quitar el autoplay
				code_player=899459075001;
				
			}

			
			var sMobile = makeMobileCompatible(idDiv, code_video,code_player,code_video,width,height,sReadToken);
			return sMobile;
		}
	} else if ('youtube'==origenVideo) {
		
		var codeYoutube ='<iframe width="640" height="360" class="'+classIframe+'" src="http://www.youtube.com/embed/'+code_video+'?wmode=transparent" frameborder="0" allowfullscreen="true"></iframe>';
		/*var codeYoutube = '<object width="640" height="360">';       
		codeYoutube += '<param name="movie" value="http://www.youtube.com/v/'+code_video+'&amp;hl=es_ES&amp;rel=0"/>';
		codeYoutube += '<param name="allowFullScreen" value="true"/>';
		codeYoutube += '<param name="allowScriptAccess" value="always"/>';
		codeYoutube += '<param name="wmode" value="opaque" />'; 
		codeYoutube += '<embed wmode="opaque" src="http://www.youtube.com/v/'+code_video+'?fs=1&amp;hl=es_ES&amp;rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="360"/>';
		codeYoutube += '</object>';*/
		return codeYoutube;
	} else if ('vimeo'==origenVideo) {
		//var codeVimeo = '<object width="640" height="360" type="application/x-shockwave-flash" id="vimeo_clip_'+code_video+'" name="vimeo_clip_'+code_video+'" data="http://www.vimeo.com/moogaloop.swf?clip_id='+code_video+'&amp;server=www.vimeo.com&amp;fullscreen=0&amp;show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;color=01AAEA">';
		/*var codeVimeo = '<object width="640" height="360" type="application/x-shockwave-flash" data="http://www.vimeo.com/moogaloop.swf?clip_id='+code_video+'&amp;server=www.vimeo.com&amp;fullscreen=1&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=">';
		codeVimeo += '<param name="quality" value="best" />';
		codeVimeo += '<param name="allowfullscreen" value="true" />';
		codeVimeo += '<param name="scale" value="showAll" />';
		codeVimeo += '<param name="movie" value="http://www.vimeo.com/moogaloop.swf?clip_id='+code_video+'&amp;server=www.vimeo.com&amp;fullscreen=1&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=" />';
		codeVimeo += '</object>';*/
		var codeVimeo='<iframe src="http://player.vimeo.com/video/'+code_video+'" width="640" height="360" frameborder="0"></iframe>';
		return codeVimeo;
	} else if ('ning'==origenVideo) {
		//revisar pone embed
	
	} else if ('metacafe'==origenVideo) {
		//var codeMetacafe='<embed height="360" width="640" wmode="transparent" autoplay="false" allowscriptaccess="never" allownetworking="internal" type="application/x-shockwave-flash" quality="high" src="http://www.metacafe.com/fplayer/'+code_video+'/.swf"></embed>';
		var codeMetacafe = '<object width="640" height="360">'; 
		codeMetacafe += '<embed height="360" width="640" wmode="opaque" autoplay="false" allowscriptaccess="never" allownetworking="internal" type="application/x-shockwave-flash" quality="high" src="http://www.metacafe.com/fplayer/'+code_video+'/.swf"></embed>';
		codeMetacafe += '</object>';
		return codeMetacafe;
	
	} else if ('blip'==origenVideo) {
		//var codeBlip='<embed src="http://blip.tv/play/'+code_video+'" type="application/x-shockwave-flash" width="640" height="360" allowscriptaccess="always" allowfullscreen="true"></embed>';
		var codeBlip = '<object width="640" height="360" wmode="opaque">'; 
		codeBlip += '<embed src="http://blip.tv/play/'+code_video+'" type="application/x-shockwave-flash" width="640" height="360" allowscriptaccess="always" allowfullscreen="true" wmode="opaque"></embed>';
		codeBlip += '</object>';
		return codeBlip;
		
	} else if ('msn'==origenVideo) {	
		
	}				
		
	/*var uid = obtenerIDCapaUnica('video');
	var s1 ='<script language="JavaScript" type="text/javascript" src="http://admin.brightcove.com/js/BrightcoveExperiences.js"></script>';
	s1 +='<object id="myExperience'+uid+'" class="BrightcoveExperience">';
	s1 +='  <param name="bgcolor" value="#000000" />';
	s1 +='  <param name="width" value="'+width+'" />';
	s1 +='  <param name="height" value="'+height+'" />';
	s1 +='  <param name="playerID" value="'+code_player+'" />';
	s1 +='  <param name="publisherID" value="'+code_publisher+'"/>';
	s1 +='  <param name="isVid" value="true" />';
	s1 +='  <param name="isUI" value="true" />';
	s1 +='  <param name="dynamicStreaming" value="true" />';
	s1 +='	<param name="wmode" value="transparent" />';
	s1 +='	<param name="@videoPlayer" value="'+code_video+'" /></object>';
	s1 +='<script type="text/javascript">brightcove.createExperiences();</script>';
	return s1;*/
	
}

function clickModal (relid, sVideoOrigen, sIdVideo,isVideoMP) {
	ejecutar=$(relid+" .photo-center2").html();
	eval(ejecutar);
	var idPublisherAux = ('bc'!=sVideoOrigen)?'':idPublisher;
	var idPlayerAux = ('bc'!=sVideoOrigen)?'':idPlayer;
	var idVideoAux = ('bc'!=sVideoOrigen)?sIdVideo:idVideo;
	var iWidthAux = '';
	var iHeightAux = '';
	
	//añadido por jsj si es capa modal con inskin pondemos el tamaño adecuado y usamos el player con inskin
	if (inSkin  && !DetectSmartphone()){
		iWidthAux = ('bc'!=sVideoOrigen)?externoIdWidth:'900';
		iHeightAux = ('bc'!=sVideoOrigen)?externoIdHeight:'460';	
		//sCad +='<div id="modal_'+idDiv +'" class="player player-inskin mymodal" style="display:none;">';
		if ('bc'==sVideoOrigen){
			$(''+relid).addClass('player-inskin');
			if (idPublisherAux==iID_PlayerABCPub)idPlayerAux=iID_PlayerABCINSKIN;
			if (idPublisherAux==iID_PlayerABCSevillaPub)idPlayerAux=iID_PlayerABCSevillaINSKIN;
		}
	}else{	
		iWidthAux = ('bc'!=sVideoOrigen)?externoIdWidth:'640';
		iHeightAux = ('bc'!=sVideoOrigen)?externoIdHeight:'360';	
	}
	
	var bMostrarComentariosAux =('bc'!=sVideoOrigen)?false:bMostrarComentarios;
	origenVideo = sVideoOrigen;
	
	pintarvideoobj=obtenerVideoBC(relid+" .photo-center",idPublisherAux,idPlayerAux,idVideoAux,iWidthAux,iHeightAux,isVideoMP,'');
	
	if (bMostrarComentariosAux){
		sURLComentarios = 'http://comm.'+sPortal+'/comentarios/xml/count.php?ids=abc-'+ idVideo + '&json=1&callback=?'
		comentariosvidmod=relid.replace('#modal_','');
		$.getJSON(sURLComentarios,function(data){
					try{
						var total = data.resultados['abc-' + idVideo + ''];
						$('#comentarios_'+comentariosvidmod+'').html('<a href="'+sEnlace+'#formcomentarios"> ' + data.resultados['abc-'+idVideo] + ' comentarios</a>');
					}catch(err){
						$('#comentarios_'+idDiv+'').html('<a href="'+sEnlace+'#formcomentarios"> comentarios</a>');
					}
					}
				);
	}
	
	$(relid+" .photo-center").html('<img src="http://secure-uk.imrworldwide.com/cgi-bin/m?ci=es-vocento&cg=0&si='+escape(window.location)+'&rp='+escape(document.referrer)+'&rnd='+(new Date()).getTime()+'" width="1" height="1" alt=""/>'+pintarvideoobj);
	$(relid+" .red-social").html('<iframe scrolling="no" frameborder="0" allowtransparency="true" src="http://www.facebook.com/plugins/like.php?href='+sEnlace+'&layout=button_count&show_faces=true&width=120&action=like&font=arial&colorscheme=light&height=21" style="border: medium none; overflow: hidden; width: 125px; height: 22px;"></iframe><a href="http://twitter.com/share" class="twitter-share-button" data-url="'+sEnlace+'" data-count="horizontal">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script><a target="_blank" href="http://www.tuenti.com/share?url='+sEnlace+'"><img src="/img/tuentishare_button22_ca.png" alt="Compartir tuenti"/></a>');
	
	//alert($(relid).html());
	
	abrirModalRetardado(relid);
	if (thisIsSmartPhone){
		relidGlobal = relid;
	}
		
	elipsis();
	return false;	
}

function abrirModalRetardado (relid) {
		
		$(relid).modal({
		onClose: function (dialog) {
			$(relid+" .photo-center").html("");
			$.modal.close(); // must call this!				
		}
							
	});

	/*function fakeClick(fn) {
		var $a = $('<a href="#" id="fakeClick"></a>');
			$a.bind("click", function(e) {
				e.preventDefault();
			fn();
			});

		$("body").append($a);

		var evt, 
		el = $("#fakeClick").get(0);

		if (document.createEvent) {
			evt = document.createEvent("MouseEvents");
			if (evt.initMouseEvent) {
				evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
				el.dispatchEvent(evt);
			}

		}

		$(el).remove();
	}

	setTimeout(function() {
		var video = $(relid + ' video').get(0);

		fakeClick(function() {
			video.play();
		});
	}, 1000);*/
}

function loadVideoABC(div, w, h, sFile, sPreview, sPortal, sOrigen, sOpciones) {
	var sPlayer;
	if (null!=sOrigen || undefined!=sOrigen) origenVideo = sOrigen;
	else { origenVideo = 'bc'; sOrigen = 'bc'; }
	
	//añadido por JSJ para verificar si hay inskin
	var sOA = mandarOAS();
	//
	
	if (sPortal=='abc'){
	
		sPlayer = iID_PlayerABC;
		sPublisher = iID_PlayerABCPub;
		
		if (w <= 146 || h<=126){
			sRutaMarcaAguaAux='http://estaticos1.abc.es/imag/boton_player_col_b.png';
			bMoscaGrande=false;
		}else{
			sRutaMarcaAguaAux='http://estaticos1.abc.es/imag/boton_player_def.png';
			bMoscaGrande=true;
		}
		
		if(location.href.indexOf('http://www.abc.es') != -1) {sURLDataBCAux='http://www.abc.es/includes/brightcove.aspx?id='+sFile+'';}
else{sURLDataBCAux='http://www.abc.es/includes/brightcove.aspx?id='+sFile+'&callback=?';}
			
	}else if (sPortal == 'abcsevilla'){
	
		sPlayer = iID_PlayerABCSevilla;
		sPublisher = iID_PlayerABCSevillaPub;
		
		if (w <= 146 || h<=126){
			sRutaMarcaAguaAux='http://estaticos1.abc.es/imag/boton_player_col_b.png';
			bMoscaGrande=false;
		}else{
			sRutaMarcaAguaAux='http://estaticos1.abc.es/imag/boton_player_def.png';
			bMoscaGrande=true;
		}
		
		if(location.href.indexOf('http://www.abcdesevilla.es') != -1) {sURLDataBCAux='http://www.abcdesevilla.es/includes/brightcove.aspx?id='+sFile+'';}
else{sURLDataBCAux='http://www.abcdesevilla.es/includes/brightcove.aspx?id='+sFile+'&callback=?';}
	
	}
	
	if ("bc"!=origenVideo){
		externoIdVideo = sFile;
		externoIdWidth = w;
		externoIdHeight = h;
	}
		
	var uid = obtenerIDCapaUnica('video');
	if (null!=sOpciones || undefined!=sOpciones) {
		var opciones = {
			imgPrevia: sPreview,
			site: sPortal,
			idVideoPlayer: sPlayer,
			idVideoPublisher: sPublisher,
			sRutaMarcaAgua: sRutaMarcaAguaAux,
			sURLDataBC: sURLDataBCAux,
			bEsMoscaGrande: bMoscaGrande,
			iDiv: div,
			sVideoOrigen: sOrigen,
			idVideo: sFile,
			isVideoMP:'',
			txtTitular: sOpciones.txtTitular,
			urlTitular: sOpciones.urlTitular,
			entradilla: sOpciones.entradilla
		};
	}
	else {
		var opciones = {
			imgPrevia: sPreview,
			site: sPortal,
			idVideoPlayer: sPlayer,
			idVideoPublisher: sPublisher,
			sRutaMarcaAgua: sRutaMarcaAguaAux,
			sURLDataBC: sURLDataBCAux,
			bEsMoscaGrande: bMoscaGrande,
			iDiv: div,
			sVideoOrigen: sOrigen,
			idVideo: sFile,
			isVideoMP:'',
			txtTitular: '',
			urlTitular: '',
			entradilla: ''
		};
	}
	
	PlayerWebTVBC.cargaVideoBC(div, sFile, w, h, opciones);
}
function obtenerIDCapaUnica (prefijo) {
	var result = [new Date().getTime(), Math.ceil(Math.random() * 1000)];
	if (prefijo) {
		result.splice(0, 0, prefijo);
	}
	return result.join("_");
}




function obtenerCapaModal (sOpciones, idDiv, idVideo, iAnchoImagen, iAltoImagen, bPintaCapaModal){
	sURL = null;
	sPortal = null;
	var sURLComentarios = null;
	var bMostrarComentarios = false;
	var sEnlace = "#";
		
	if ("bc"==origenVideo) {
		$.ajax({
			url: sOpciones.sURLDataBC,
			dataType: 'json',
			data: null,
			success: function(data) {
				var sPie = "";
				var sEntradilla = "";
				var iWidth=640;
				var iHeight=360;
				var sCad = "";
				var sVideoStillURL = "";
				if (data.name!=null) sPie = data.name;
				if (data.longDescription!=null) sEntradilla = data.longDescription;	  
				if (data.linkURL!=null) sEnlace = data.linkURL;
				//en el caso de que el video sea de brightcove, cargamos la variable OPCIONES.urlTitular con la pagina de
				//detalle del video
				if (isDefined("OPCIONES") && null!=OPCIONES ) {
					OPCIONES.urlTitular = sEnlace;
				}
				if (data.videoStillURL!=null) sVideoStillURL = data.videoStillURL;
				if (sOpciones.idVideoPlayer==iID_PlayerABC){
					sPortal = 'abc.es';
				}
				else {
					if (sOpciones.idVideoPlayer == iID_PlayerABCSevilla) sPortal = 'abcdesevilla.es';
				}
				//calculando la proporción del video para mostrar el player en 16:9 o en 4:3 16:9 -> 1,77, 640x360	 4:3 -> 1,33, 640x480
				iProporcion = parseInt((data.frameWidth / data.frameHeight)*100)/100;		
				if (iProporcion >= 1.77) {//16:9
					iWidth=640;
					iHeight=360;
				}
				else{//4:3
					iWidth=640;
					iHeight=480;
				}
				if (data.customFields != undefined) {
					if (data.customFields.comentarios == undefined || data.customFields.comentarios == 'SI') bMostrarComentarios=true;
				}
				else{
					bMostrarComentarios=true
				}
				if (bPintaCapaModal) {
					if (!thisIsSmartPhone) {
						//añadido por JSJ, SI ES MODAL, ES DE BC Y HAY INSKIN SE CARGA EL PLAYER ADECUADO CON LOS TAMAÑOS ADECUADOS
						if (inSkin) {
							//modificado por JJS AÑADIR ESTO CUANDO TENGAMOS INSKIN!!!!
							iWidth=900;
							iHeight=460;		
							sCad +='<div id="modal_'+idDiv +'" class="player player-inskin mymodal" style="display:none;">';
							if (sPortal=='abc.es'){
								sOpciones.idVideoPlayer=iID_PlayerABCINSKIN;
							}
							else {
								if (sPortal=='abcdesevilla.es') sOpciones.idVideoPlayer=iID_PlayerABCSevillaINSKIN;
							}
						}
						else {
							if (iWidth==900 && iHeight==460) {
								sCad +='<div id="modal_'+idDiv +'" class="player player-inskin mymodal" style="display:none;">';
							}
							else {
								sCad +='<div id="modal_'+idDiv +'" class="player mymodal" style="display:none;">';
							}
						}
					}
					else {
						if (iWidth==900 && iHeight==460) {
							sCad +='<div id="modal_'+idDiv +'" class="player player-inskin mymodal" style="display:none;">';
						}
						else {
							sCad +='<div id="modal_'+idDiv +'" class="player mymodal" style="display:none;width:' + iWidth + 'px;height:' + iHeight + 'px;">';
						}
					}
					sCad +='<div class="head">';
					if (window.objectPublishId) {
						sCad =pintaPatrocinioVideos(objectPublishId,sCad);
					}
					sCad +='<div class="cerrar"><a class="simplemodal-close" href = "javascript:void(0)"></a></div>';
					sCad +='</div>';
					sCad +='<div class="photo">'; 
					sCad +='<div class="photo-center2" style="display:none;">idDiv="'+idDiv+'";idPublisher="'+sOpciones.idVideoPublisher+'";idPlayer="'+sOpciones.idVideoPlayer+'";idVideo="'+idVideo+'";iWidth="'+iWidth+'";iHeight="'+iHeight+'";sPortal="'+sPortal+'";bMostrarComentarios="'+bMostrarComentarios+'";sEnlace="'+sEnlace+'";</div>';
					sCad +='<div class="photo-center"> '; 
					sCad +='</div>'; 
					sCad +='<div class="photo-bot"> </div>'; 
					sCad +='</div>';
					sCad +='<div class="detalle-noticia">';
					sCad +='<div class="opina clearfix">';
					sCad +='<div id="comentarios_' + idDiv + '" class="numcoment"></div>';
					if (sEnlace!=null && sEnlace!=''){
						sCad +='<div class="red-social" id="red-social">';
						sCad +='</div>';
					}
					sCad +='</div>';
					sCad +='<h3>';
					sCad +='<a class="enlaceNoticia" href="'+ sEnlace +'">' +  sPie + '</a>';
					sCad +='</h3>'; 
					sCad +='<div class="subhead">';
					sCad +=sEntradilla;
					sCad +='</div>'; 
					sCad +='</div>';
					sCad +='</div>';
					$('#' + idDiv + '-player').html(sCad);
					pintaImagenBC (sOpciones.imgPrevia,idDiv,sPortal,sVideoStillURL,iAnchoImagen,iAltoImagen);				
				}
				else{
					pintaImagenBC (sOpciones.imgPrevia,idDiv,sPortal,sVideoStillURL,iAnchoImagen,iAltoImagen);
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				console.log(textStatus, errorThrown);		
			}
		});
	} else {
		var sVideoStillURL = "";
		if (bPintaCapaModal){
			sIdVideo = idDiv.substring((idDiv.indexOf("_")+1), idDiv.indexOf("_v"));
			var sCad = "";
			sEnlace = sOpciones.urlTitular;
			sPie = sOpciones.txtTitular;
			sEntradilla = sOpciones.entradilla;
			iWidth=640;
			iHeight=360;
//			if (idPlayer==iID_PlayerABC){
			if (sOpciones.idVideoPlayer==iID_PlayerABC){
				sPortal = 'abc.es';
//			}else if (idPlayer == iID_PlayerABCSevilla){
			}else if (sOpciones.idVideoPlayer == iID_PlayerABCSevilla){
				sPortal = 'abcdesevilla.es';
			}
			if (!thisIsSmartPhone) {				
				if (iWidth==900 && iHeight==460) {
					sCad +='<div id="modal_'+idDiv +'" class="player player-inskin mymodal" style="display:none;">';
				}
				else {
					sCad +='<div id="modal_'+idDiv +'" class="player mymodal" style="display:none;">';
				}
			}
			else{
				if (iWidth==900 && iHeight==460) {
					sCad +='<div id="modal_'+idDiv +'" class="player player-inskin mymodal" style="display:none;">';
				}
				else {
					sCad +='<div id="modal_'+idDiv +'" class="player mymodal" style="display:none;width:' + iWidth + 'px;height:' + iHeight + 'px;">';
				}
			}
			sCad +='<div class="head">';

			if (window.objectPublishId){
				sCad =pintaPatrocinioVideos(objectPublishId,sCad);
			}
			sCad +='<div class="cerrar"><a class="simplemodal-close" href = "javascript:void(0)"></a></div>';
			sCad +='</div>';
			
			sCad +='<div class="photo">'; 
//			sCad +='<div class="photo-center2" style="display:none;">idDiv="'+idDiv+'";idPublisher="'+idPublisher+'";idPlayer="'+idPlayer+'";idVideo="'+idVideo+'";iWidth="'+iWidth+'";iHeight="'+iHeight+'";sPortal="'+sPortal+'";bMostrarComentarios="'+bMostrarComentarios+'";sEnlace="'+sEnlace+'";</div>'; 
			sCad +='<div class="photo-center2" style="display:none;">idDiv="'+idDiv+'";idPublisher="'+sOpciones.idVideoPublisher+'";idPlayer="'+sOpciones.idVideoPlayer+'";idVideo="'+idVideo+'";iWidth="'+iWidth+'";iHeight="'+iHeight+'";sPortal="'+sPortal+'";bMostrarComentarios="'+bMostrarComentarios+'";sEnlace="'+sEnlace+'";</div>';
			sCad +='<div class="photo-center"> '; 
			sCad +='</div>'; 
			sCad +='<div class="photo-bot"> </div>'; 
			sCad +='</div>';
			sCad +='<div class="detalle-noticia">';
			sCad +='<div class="opina clearfix">';
			sCad +='<div id="comentarios_' + idDiv + '" class="numcoment"></div>';

			if (sEnlace!=null && sEnlace!=''){
				sCad +='<div class="red-social" id="red-social">';
				sCad +='</div>';
			}
			sCad +='</div>';
			sCad +='<h3>';
			sCad +='<a class="enlaceNoticia" href="'+ sEnlace +'">' +  sPie + '</a>';
			sCad +='</h3>'; 
			sCad +='<div class="subhead">';
			sCad +=sEntradilla;
			sCad +='</div>'; 
			sCad +='</div>';
			sCad +='</div>'; 
			$('#' + idDiv + '-player').html(sCad);		
//			pintaImagenBC (sImagenPrevia,idDiv,sPortal,sVideoStillURL,iAnchoImagen,iAltoImagen);
			pintaImagenBC (sOpciones.imgPrevia,idDiv,sPortal,sVideoStillURL,iAnchoImagen,iAltoImagen);
		}else{
//			pintaImagenBC (sImagenPrevia,idDiv,sPortal,sVideoStillURL,iAnchoImagen,iAltoImagen);
			pintaImagenBC (sOpciones.imgPrevia,idDiv,sPortal,sVideoStillURL,iAnchoImagen,iAltoImagen);
		}
	}
}
function pintaImagenBC(sImagenPrevia,idDiv,sPortal,sVideoStillURL,iAnchoImagen,iAltoImagen){
	if (sImagenPrevia=="" || sImagenPrevia.src==""){	
		if (sMarcaAgua!=""){
			sVideoStillURL="http://resizer." + sPortal + "/resizer/resizer.php?imagen=" + sVideoStillURL + "&nuevoancho=" + iAnchoImagen + "&nuevoalto=" + iAltoImagen + "&copyright=false&encrypt=false&marcaagua="+sMarcaAgua+"&posmarca="+sPosmarca+"&transparencia="+sTransparencia;
		}else{
			sVideoStillURL="http://resizer." + sPortal + "/resizer/resizer.php?imagen=" + sVideoStillURL + "&nuevoancho=" + iAnchoImagen + "&nuevoalto=" + iAltoImagen + "&copyright=false&encrypt=false";
		}
		$('#img_' + idDiv).attr("class","caja");
		$('#img_' + idDiv).attr("src",sVideoStillURL);

	}
	//Para el caso de imagenes de 'ultimos videos'(comentado porque o pasamos al php que genera el modulo de ultimos videos)
	/*
	$('.caja').ready(function() {
	        redimensionado();                         
        });
    */
	//Para el resto de casos
	$('#img_' + idDiv).load(function() {
		redimensionado();
	});
}

function pintaPatrocinioVideos (objectPublishId, sCad){
	var temporalPubliSeccion=null; 
	if (window.PubliTodosVideos){
		temporalPubliSeccion=PubliTodosVideos;
		//sCad +='<div class="patrocinado"><span>' + PubliTodosVideos[0] + '</span><a ' + PubliTodosVideos[2] + '><img src="' + PubliTodosVideos[1] +'"></a></div>';
	}else{
		esPortadaYNoEncotrada=false;
		if (noticiaid==''){
			try {
				if (eval('portada_'+objectPublishId)!=''){
					var temporalPubliSeccion=eval('portada_'+objectPublishId);
					//sCad +='<div class="patrocinado"><span>' + temporalPubliSeccion[0] + '</span><a ' + temporalPubliSeccion[2] + '><img src="' + temporalPubliSeccion[1] +'"></a></div>';
				}else{
					esPortadaYNoEncotrada=true;
				}
			} catch (exc) {
				esPortadaYNoEncotrada=true;
			}
		}
		if (noticiaid!='' || esPortadaYNoEncotrada){
			try{
				if (eval(objectPublishId)!=''){
					var temporalPubliSeccion=eval(objectPublishId);

					//sCad +='<div class="patrocinado"><span>' + temporalPubliSeccion[0] + '</span><a ' + temporalPubliSeccion[2] + '><img src="' + temporalPubliSeccion[1] +'"></a></div>';
				}
			}catch(exc){
			
			}
		}
	}
	if (temporalPubliSeccion!=null){
		sCad +='<div class="patrocinado"><span>' + temporalPubliSeccion[0] + '</span>';
		if (temporalPubliSeccion[4]!=null && temporalPubliSeccion[4]!=''){
			sCad +='<a ' + temporalPubliSeccion[2] + ' onclick=pageTracker._trackEvent("' + temporalPubliSeccion[4] + '","EnlaceSeguido");' + '><img src="' + temporalPubliSeccion[1] +'"></a>';
		}else{
			sCad +='<a ' + temporalPubliSeccion[2] + '><img src="' + temporalPubliSeccion[1] +'"></a>';
		}
		sCad +='</div>';
		
		if (temporalPubliSeccion[4]!=null && temporalPubliSeccion[4]!=''){
			$(document).ready(function () {
				try	{
					pageTracker._trackEvent('"'+ temporalPubliSeccion[4] +'"',"Visualizado");
				}catch(excTracker){
				}
			});
		}
		
		//Pintamos pixelContador
		if (temporalPubliSeccion[3]!=null && temporalPubliSeccion[3]!=''){ 
			if (typeof ord=='undefined') {
				ord=Math.random()*10000000000000000;
			}
			sCad +='<img src="' + temporalPubliSeccion[3] + 'sz=1x1;ord=' + ord + '?" border=0 width=1 height=1></img>';
		}
	}
	return sCad;
}


function getOAS_sitepage(sOAS_sitepage) {

	var campos = sOAS_sitepage.split('/');		
	var campos2 = campos[0].split('.');	
	var periodico = campos2[1];	
	var separador = '/';	
	
	/*
	OAS PARA INSKIN
	vocento.abc
	vocento.abcdesevilla
	vocento.diariosur
	vocento.elcomerciodigital
	vocento.elcorreodigital
	vocento.eldiariomontanes
	vocento.diariovasco
	vocento.hoy
	vocento.ideal
	vocento.larioja
	vocento.lasprovincias
	vocento.laverdad
	vocento.lavozdigital
	vocento.nortecastilla	
	
	añadido por jsj, si un video muestra capa modal y tiene alguno de esos valores en el OAS ha de cargar el player con el OAS
	*/
	var respuesta = 'vocento.' + periodico + separador + campos[1];
	
	if (respuesta.indexOf('vocento.abc')!=-1 || respuesta.indexOf('vocento.abcdesevilla')!=-1 || respuesta.indexOf('vocento.diariosur')!=-1 
	    || respuesta.indexOf('vocento.elcomerciodigital')!=-1 || respuesta.indexOf('vocento.eldiariomontanes')!=-1 || respuesta.indexOf('vocento.elcorreodigital')!=-1 
		|| respuesta.indexOf('vocento.diariovasco')!=-1 || respuesta.indexOf('vocento.hoy')!=-1 || respuesta.indexOf('vocento.ideal')!=-1
		|| respuesta.indexOf('vocento.larioja')!=-1 || respuesta.indexOf('vocento.lasprovincias')!=-1 || respuesta.indexOf('vocento.laverdad')!=-1 
		|| respuesta.indexOf('vocento.lavozdigital')!=-1 || respuesta.indexOf('vocento.nortecastilla')!=-1) {

		//cargamos inskin en capa modal
		//alert (respuesta);
		inSkin = true;
	}
	
	return respuesta;//'vocento.' + periodico + separador + campos[1];

}
function PlayerWebTVBC() {
	this.initted = false;
	this.portal = null;
	this.rutaConfig  = null;
}
PlayerWebTVBC.MIN_ANCHO_PLAYER = 180;
PlayerWebTVBC.MIN_ALTO_PLAYER = 100;
PlayerWebTVBC.BASE_CONFIG  = "/includes/manuales/swf/PlayerWebTVBC/";
PlayerWebTVBC.VERSION_FLASH  = 8;
PlayerWebTVBC.IDS_PORTALES = {
	ABC: "abc",
	ABC_SEVILLA: "abcdesevilla"
	};
PlayerWebTVBC.ieCounter = 1;
PlayerWebTVBC.entorno = getEntorno();
PlayerWebTVBC.INFO_PORTALES = {};
PlayerWebTVBC.INFO_PORTALES[PlayerWebTVBC.IDS_PORTALES.ABC] = {
	"resizer": "abc.es",
	"servidores": ["abc.es", "http://212.81.129.25:8280", "http://212.81.129.25", "http://preproduccionabc.abc.es"],
	"dominio": "/" + PlayerWebTVBC.entorno,
	"baseConfig": "/swf/PlayerWebTVBC/"
};
PlayerWebTVBC.INFO_PORTALES[PlayerWebTVBC.IDS_PORTALES.ABC_SEVILLA] = {
	"resizer": "abc.es",
	"servidores": ["abcdesevilla.es", "http://212.81.129.25:8281", "http://212.81.129.25", "http://preproduccionsevilla.abc.es"],
	"dominio": "/" +PlayerWebTVBC.entorno,
	"baseConfig": "/swf/PlayerWebTVBC/"
};
PlayerWebTVBC.cache = {};
function getEntorno() {
	var result = "www";
	if 		(location.href.indexOf('http://www.abc.es') != -1) result = 'http://www.abc.es';
	else if (location.href.indexOf('http://www.abcdesevilla.es') != -1) result = 'http://www.abcdesevilla.es';
	else if (location.href.indexOf('http://212.81.129.25:8280') != -1) result = 'http://212.81.129.25:8280';
	else if (location.href.indexOf('http://212.81.129.25:8281') != -1) result = 'http://212.81.129.25:8281';
	else if (location.href.indexOf('http://sevilla-origin.abc.es') != -1) result = 'http://www.abcdesevilla.es';
	else if (location.href.indexOf('http://www-origin.abc.es/') != -1) result = 'http://www.abc.es';
	else if (location.href.indexOf('http://n1abc10.abc.es') !=-1) result = 'http://www.abc.es';
	else if (location.href.indexOf('http://n2abc10.abc.es') !=-1) result = 'http://www.abc.es';
	else if (location.href.indexOf('http://n3abc10.abc.es') !=-1) result = 'http://www.abc.es';
	else if (location.href.indexOf('http://n4abc10.abc.es') !=-1) result = 'http://www.abc.es';
	else if (location.href.indexOf('http://preproduccionabc.abc.es') !=-1) result = 'http://www.abc.es';
	else if (location.href.indexOf('http://preproduccionsevilla.abc.es') !=-1) result = 'http://www.abcdesevilla.es';	
	else {		
		try {
			result = location.href.split('/')[2].split('.')[0];
			if ( (result != 'www') && (result != 'desarrollo') && (result != 'rediseno') && (result != 'redisenodev') ) {
				result = 'www';
			}
		} catch (e) {
		}		
	}
	
	return result;
}

function isDesarrolloABC() {
	var result = false;
	if ( (location.href.indexOf('http://desarrollo2010.abc.es') != -1)  ||
		 (location.href.indexOf('http://desarrollo2010.abcdesevilla.es') != -1) || 
		 (location.href.indexOf('http://integracion2010.abc.es') != -1) || 
		 (location.href.indexOf('http://integracion2010.abcdesevilla.es') != -1) ) {
			result = true;
	}
	
	return result;
}

function isDesarrolloABC(fullURL) {
	var result = false;
	if ( (fullURL.indexOf('http://desarrollo2010.abc.es') != -1)  ||
		 (fullURL.indexOf('http://desarrollo2010.abcdesevilla.es') != -1) || 
		 (fullURL.indexOf('http://integracion2010.abc.es') != -1) || 
		 (fullURL.indexOf('http://integracion2010.abcdesevilla.es') != -1) ) {
			result = true;
	}
	
	return result;
}

function isABC() {
	var result = false;

	if ( (location.href.indexOf('http://www.abc.es') != -1)  ||
		 (location.href.indexOf('http://www.abcdesevilla.es') != -1)  ||
		 (location.href.indexOf('http://212.81.129.25:8280') != -1)  ||
		 (location.href.indexOf('http://212.81.129.25:8281') != -1) ||
		 (location.href.indexOf('http://sevilla-origin.abc.es') != -1)  ||
		 (location.href.indexOf('http://www-origin.abc.es/') != -1)  ||
		 (location.href.indexOf('http://n1abc10.abc.es') != -1)  ||
		 (location.href.indexOf('http://n2abc10.abc.es') != -1)  ||
		 (location.href.indexOf('http://n3abc10.abc.es') != -1)  ||
		 (location.href.indexOf('http://n4abc10.abc.es') != -1) ) {
			result = true;
	}
	
	return result;
}
function getColorFondo() {
	var colorFondo = '#000000';
	return colorFondo;
}

function activarVideo(id, origenVideo){
	
	if(origenVideo=='youtube' || origenVideo=='vimeo'){
		if($('#'+id).children("iframe").length!=0){
			$('#'+id).children('.alto').css("display","none");
			$('#'+id).children('.mosca-player').children('img').css("display","none");
			$('#'+id).children('iframe').css("display","block");	
		}
	}else{
		if($('#'+id).children("object").length!=0){
			$('#'+id).children('.alto').css("display","none");
			$('#'+id).children('.mosca-player').children('img').css("display","none");
			$('#'+id).children('object').css("display","block");	
		}
	}
}

PlayerWebTVBC.cargaVideoBC = function(div, sFile, w, h, opciones) {
	var funcion = PlayerWebTVBC.cargaVideoBC; 
	if (arguments.length < 5) {
		var uid = this.getUID("video");
		document.write('<div id="' + uid + '"></div>');
		
		var args = new Array(5);
		args[0] = uid;
		for (var i = 0; i < arguments.length; i++) {
			args[i + 1] = arguments[i];
		}
		
		funcion.call(this, args[0], args[1], args[2], args[3], args[4]);
		return;
	}
	var player = null;
	var config = null;
	if (!opciones) {
		opciones = {};
	}
	
	if (opciones) {
		config = opciones.config || opciones.site;
	}
	if (config) {
		config = config.toLowerCase();
	}
	if (config == this.IDS_PORTALES.ABC) {
		var exp = /(sevilla)|(212\.81\.129\.25:8281)/gi;
		if (exp.test(location.host)) {
			config = this.IDS_PORTALES.ABC_SEVILLA;
		}
	} else if (config == "abcsevilla") {
		config = this.IDS_PORTALES.ABC_SEVILLA;
	}
	
	if (!config) {
		player = new PlayerWebTVBC();
	} else {
		opciones.site = config;
		opciones.config = config;
		if (!PlayerWebTVBC.cache[config]) {
			PlayerWebTVBC.cache[config] = new PlayerWebTVBC();
		}
		player = PlayerWebTVBC.cache[config];
	}
	
	player.showVideoBC(div, sFile, w, h, opciones);
};
PlayerWebTVBC.nada = function() {};
PlayerWebTVBC.getPortal = function(opciones) {
	var result = null;
	
	if (opciones && opciones.site) {
		result = opciones.site;
	} else {
		var servidor = location.host;
		for (var portal in this.INFO_PORTALES) {
			var servidores = this.INFO_PORTALES[portal].servidores;
			
			for (var i = 0; i < servidores.length; i++) {
				var candidato = servidores[i];
				if (servidor.indexOf(candidato) != -1) {
					result = portal;
					break;
				}
			}
		}
	}
	
	return result;
};

PlayerWebTVBC.getUID = function(prefijo) {
	var result = [new Date().getTime(), Math.ceil(Math.random() * 1000)];
	if (prefijo) {
		result.splice(0, 0, prefijo);
	}
	return result.join("_");
}

PlayerWebTVBC.prototype = {
	init: function(opciones, video) {
		var rutaConfig = null;
		var portal = this.portal;
		if (!this.portal) {
			portal = this.portal = this.getPortal(opciones);
		}
		var config = null;
		if (opciones) {config = opciones.config || portal;}
		return true;
	},
		
	esDominioConocido: function() {
        var dominio = location.hostname;
        for (var portal in this.INFO_PORTALES) {
        	var servidores = this.INFO_PORTALES[portal].servidores;
        	for (var i = 0; i < servidores.length; i++) {
        		var candidato = servidores[i];
        		if (candidato == dominio) {
        			return true;
                }
           }
        }
         return false;
	},

	_showVideoBC : function(id, video, w, h, opciones) {
		var funcion = this._showVideoBC;
		
		if (arguments.length < 5) {
			var uid = this.getUID("video");
			document.write('<div id="' + uid + '"></div>');
			var args = new Array(5);
			args[0] = uid;
			for (var i = 0; i < arguments.length; i++) {
				args[i + 1] = arguments[i];
			}
			
			funcion.call(this, args[0], args[1], args[2], args[3], args[4]);
			return;
		}
			
		if (!opciones) {opciones = {};}
		if (!this.init(opciones, video)) {
			var _this = this;
			setTimeout(function() {
				funcion.call(_this, id, video, w, h, opciones);
			}, 500);
			return;
		}
		
		origenVideo=opciones.sVideoOrigen;
		var icodplayer  = opciones.idVideoPlayer;
		var icodPublisher  = opciones.idVideoPublisher;		
		var contenedor = document.getElementById(id);
		if (contenedor) {				
			if (w == 644) {
				$('#'+id).children('.alto').css("display","none");
				$('#'+id).children('.mosca-player').children('img').css("display","none");
				if (origenVideo=='youtube' || origenVideo=='vimeo'){
					if($('#'+id).children("iframe").length==0){
						$('#'+id).children('.alto').before( obtenerVideoBC ("#"+id,icodPublisher,icodplayer,video,w,h,opciones.isVideoMP,'iframe_reproduceDentro') );
						$('#'+id).children('.mosca-player').children('img').unbind('click');
						$('#'+id).children('.mosca-player').children('img').bind('click',function() {
							  activarVideo(id,origenVideo);
						});
					}else{
						$('#'+id).children('iframe').css("display","block");	
					}
				}else{
					if($('#'+id).children("object").length==0){
						$('#'+id).children('.alto').before( obtenerVideoBC ("#"+id,icodPublisher,icodplayer,video,w,h,opciones.isVideoMP,'iframe_reproduceDentro') );
						$('#'+id).children('.mosca-player').children('img').unbind('click');
						$('#'+id).children('.mosca-player').children('img').bind('click',function() {
							  activarVideo(id,origenVideo);
						});
					}else{
						$('#'+id).children('object').css("display","block");	
					}
				}
			}
		}	
	},
	
	
	
	showVideoBC: function(id, video, w, h, opciones) {
		var funcion = this.showVideoBC;
				
		if (arguments.length < 5) {
			var uid = this.getUID("video");
			document.write('<div id="' + uid + '"></div>');
			
			var args = new Array(5);
			args[0] = uid;
			for (var i = 0; i < arguments.length; i++) {
				args[i + 1] = arguments[i];
			}
			
			funcion.call(this, args[0], args[1], args[2], args[3], args[4]);
			return;
		}
		if (!opciones) {
			opciones = {};
		}
		
		var _this = this;
		if (!this.init(opciones, video)) {
			setTimeout(function() {
				funcion.call(_this, id, video, w, h, opciones);
			}, 500);
			return;
		}
		
		var contenedor = document.getElementById(id);
		
		if (contenedor) {
			if (opciones && opciones.imgPrevia) {				
				//var urlPreviaRedimensionada = this.getURLResizerBC(opciones.imgPrevia, w, h, sMarcaAgua);
				opciones.imgPrevia = this.getURLResizerBC(opciones.imgPrevia, w, h, sMarcaAgua);
//				this.pintarImagenBC(id, video, w, h, opciones, urlPreviaRedimensionada);
//			} else {
//				this.pintarImagenBC(id, video, w, h, opciones, null);
			}
			this.pintarImagenBC(id, video, w, h, opciones);
		}		
	},
	
//	pintarImagenBC: function(id, video, w, h, opciones, urlImgPrevia, imgPrevia) {
	pintarImagenBC: function(id, video, w, h, opciones) {
		var _this = this;
		var funcion = this.pintarImagenBC;
		
//		if(opciones.sVideoOrigen != "bc" && !imgPrevia) {
//			imgPrevia = opciones.imgPrevia;
//		}
		
/*********
 * Para que se haga el 'resizer', ya que paa el 'resizer' se coge la imagen del parametro 'opciones'.
 *********/		
//		if (urlImgPrevia!=null){
//			opciones.imgPrevia = urlImgPrevia;
//			imgPrevia = urlImgPrevia;
//		}
		
				
				
				
//		if (urlImgPrevia && !imgPrevia) {
//			var imgPrevia = new Image();
//			imgPrevia.src = urlImgPrevia;
//			if ( imgPrevia.complete ) {
//				funcion.call(_this, id, video, w, h, opciones, urlImgPrevia, imgPrevia);
//			} else{
//				imgPrevia.onload = function() {
//					funcion.call(_this, id, video, w, h, opciones, urlImgPrevia, imgPrevia);
//				};
//				imgPrevia.onerror = imgPrevia.onabort = function() {
//					funcion.call(_this, id, video, w, h, opciones, urlImgPrevia, new Image());
//				};
//			}
//		} else if (!urlImgPrevia || (urlImgPrevia && imgPrevia)) {
//			if (!urlImgPrevia) {
//				imgPrevia = new Image();
//			}
//			
			var contenedor = document.getElementById(id);
			var alto = parseInt(h, 10);
			var ancho = parseInt(w, 10);
			var tamIcono = [64, 61];			
			
			var accion = function() {
				
				_this._showVideoBC(id, video, w, h, opciones);
				this.onclick = _this.nada;
			
			};
//			this.getHTMLImagenMarcaAguaBC(id, video, ancho, alto, tamIcono, imgPrevia, contenedor, accion, opciones);
			this.getHTMLImagenMarcaAguaBC(id, video, ancho, alto, tamIcono, contenedor, accion, opciones);
//		}
	},

//	getHTMLImagenMarcaAguaBC: function(div, video,ancho, alto, tamIcono, imgPrevia, contenedor, accion, opciones) {
	getHTMLImagenMarcaAguaBC: function(div, video,ancho, alto, tamIcono, contenedor, accion, opciones) {	
		var textoAlt = 'Pulse para ver el video';
		var html = '';
		var iDivHTML5 = div;
		html += '<div class="alto" style="position:relative; width:' + ancho + 'px;height:' + alto + 'px;top: 0px; left:0px; display: block;"><div class="content-video">';
		div = div.replace(/\./g,'_');
		var uid = obtenerIDCapaUnica('video');
		div += '_' + uid;
		var divUnico = div + "_" + video;
//		if (imgPrevia.src || imgPrevia.src=='')
//			var txtSrcImagen = imgPrevia.src;
//		else var txtSrcImagen = imgPrevia;
		
//		if (imgPrevia && opciones.sVideoOrigen == "bc" ) {
		//if (opciones.imgPrevia && opciones.sVideoOrigen == "bc" ) {

		if (opciones.sVideoOrigen=="bc"){
			$.ajax({
//				  url: sURLDataBC,
				  url: opciones.sURLDataBC,
				  dataType: 'json',
				  opciones:opciones,
				  elementoPadre:this,
				  data: null,
				  success: function(data) {

						//if(data.videoFullLength.frameWidth==null && data.videoFullLength.frameHeight==null){alert("1");setVideoMPTemporal('true');}else{alert("2");setVideoMPTemporal('false');};
					if(data.videoFullLength.frameWidth==null && data.videoFullLength.frameHeight==null){ 
						opciones.isVideoMP='true';	
					}else{ 
			
						opciones.isVideoMP='false';
					};
					if (ancho==644){		
						html += '<img style="cursor: pointer" class="caja" onclick="activarVideo(\''+iDivHTML5+'\',\''+ opciones.sVideoOrigen +'\')" id = "img_' + divUnico +'" src="' + opciones.imgPrevia + '" alt="' + textoAlt + '" title="' + textoAlt + '"/>';				
						if (opciones.bEsMoscaGrande){
							html += '</div></div><div class="mosca-player" style="display:none"><img alt="' + textoAlt + '" title="' + textoAlt + '" style="cursor: pointer" onClick="$(this).parent(\'.mosca-player\').parent(\'.unvideo\').children(\'.alto\').children(\'.content-video\').click();" src="'+opciones.sRutaMarcaAgua+'"/></div>';
						}else{
							html += '</div></div><div class="mosca-player-small"><img alt="' + textoAlt + '" title="' + textoAlt + '" style="cursor: pointer" onClick="$(this).parent(\'.mosca-player-small\').parent(\'.unvideo\').children(\'.alto\').children(\'.content-video\').click();" src="'+opciones.sRutaMarcaAgua+'"/></div>';
						}
					}else{			
						html += '<a class="enlacemodal" rel="#modal_'+ divUnico +'" href="javascript:void(0);" onClick="clickModal(\'#modal_'+divUnico+'\', \''+opciones.sVideoOrigen+'\', \''+opciones.idVideo+'\',\''+opciones.isVideoMP+'\')"  ><img class="caja" style="display:none" id = "img_' + divUnico +'" src="' + opciones.imgPrevia + '" alt="' + textoAlt + '" title="' + textoAlt + '"/></a>';
						if (opciones.bEsMoscaGrande){
							html += '</div></div><div class="mosca-player" style="display:none" ><a href="javascript:void(0);" onClick="javascript:clickModal(\'#modal_'+divUnico+'\', \''+opciones.sVideoOrigen+'\', \''+opciones.idVideo+'\',\''+opciones.isVideoMP+'\')"><img alt="' + textoAlt + '" title="' + textoAlt + '" style="cursor: pointer" src="'+opciones.sRutaMarcaAgua+'"/></a></div>';
						}else{
							html += '</div></div><div class="mosca-player-small"><a href="javascript:void(0);" onClick="javascript:clickModal(\'#modal_'+divUnico+'\', \''+opciones.sVideoOrigen+'\', \''+opciones.idVideo+'\',\''+opciones.isVideoMP+'\')"><img alt="' + textoAlt + '" title="' + textoAlt + '" style="cursor: pointer" src="'+opciones.sRutaMarcaAgua+'"/></a></div>';
						}
						var sauxhtml ='<div id="fade_'+ divUnico + '" class="overlay modalfade" onclick = "document.getElementById(\'light_'+ divUnico + '\').style.display=\'none\';document.getElementById(\'fade_'+ divUnico + '\').style.display=\'none\'"></div> ';
						sauxhtml +='<div id="light_'+ divUnico + '" class="modal modallight"><div id=' + divUnico + '-player>';
						sauxhtml +='</div></div></div>';
						html = html + sauxhtml;
					}
					contenedor.innerHTML = html;
					contenedor.firstChild.firstChild.onclick = accion;

					if (ancho!=644){//la pintamos después de que se haya puesto en el DOM el id del player
						obtenerCapaModal (opciones, divUnico, video, ancho, alto, true);
					}else{
						obtenerCapaModal (opciones, divUnico, video, ancho, alto, false);
					}
					if (ancho==644 && (location.href.indexOf(".es/videos-")!=-1 || location.href.indexOf(".es/multimedia-videos/videos-de-abc.asp")!=-1)){
						PlayerWebTVBC.prototype._showVideoBC(iDivHTML5, video, ancho, alto, opciones);
					}
				 },
				  error: function(XMLHttpRequest, textStatus, errorThrown) {
					console.log(textStatus, errorThrown);		
				  }
				});
		}

	
		if (opciones.sVideoOrigen != "bc" ) {
			if (ancho==644){		
				html += '<img style="cursor: pointer" class="caja" onclick="activarVideo(\''+iDivHTML5+'\',\''+ opciones.sVideoOrigen +'\')"id = "img_' + divUnico +'" src="' + opciones.imgPrevia + '" alt="' + textoAlt + '" title="' + textoAlt + '"/>';
				if (opciones.bEsMoscaGrande){
					html += '</div></div><div class="mosca-player" style="display:none"><img alt="' + textoAlt + '" title="' + textoAlt + '" style="cursor: pointer" onClick="$(this).parent(\'.mosca-player\').parent(\'.unvideo\').children(\'.alto\').children(\'.content-video\').click();" src="'+opciones.sRutaMarcaAgua+'"/></div>';
				}else{
					html += '</div></div><div class="mosca-player-small"><img alt="' + textoAlt + '" title="' + textoAlt + '" style="cursor: pointer" onClick="$(this).parent(\'.mosca-player-small\').parent(\'.unvideo\').children(\'.alto\').children(\'.content-video\').click();" src="'+opciones.sRutaMarcaAgua+'"/></div>';
				}
			}else{			
				html += '<a class="enlacemodal" rel="#modal_'+ divUnico +'" href="javascript:void(0);" onClick="clickModal(\'#modal_'+divUnico+'\', \''+opciones.sVideoOrigen+'\', \''+opciones.idVideo+'\',\''+opciones.isVideoMP+'\')"  ><img class="caja" style="display:none" id = "img_' + divUnico +'" src="' + opciones.imgPrevia + '" alt="' + textoAlt + '" title="' + textoAlt + '"/></a>';				
				if (opciones.bEsMoscaGrande){
					html += '</div></div><div class="mosca-player" style="display:none" ><a href="javascript:void(0);" onClick="javascript:clickModal(\'#modal_'+divUnico+'\', \''+opciones.sVideoOrigen+'\', \''+opciones.idVideo+'\',\''+opciones.isVideoMP+'\')"><img alt="' + textoAlt + '" title="' + textoAlt + '" style="cursor: pointer" src="'+opciones.sRutaMarcaAgua+'"/></a></div>';
				}else{
					html += '</div></div><div class="mosca-player-small"><a href="javascript:void(0);" onClick="javascript:clickModal(\'#modal_'+divUnico+'\', \''+opciones.sVideoOrigen+'\', \''+opciones.idVideo+'\',\''+opciones.isVideoMP+'\')"><img alt="' + textoAlt + '" title="' + textoAlt + '" style="cursor: pointer" src="'+opciones.sRutaMarcaAgua+'"/></a></div>';
				}
				var sauxhtml ='<div id="fade_'+ divUnico + '" class="overlay modalfade" onclick = "document.getElementById(\'light_'+ divUnico + '\').style.display=\'none\';document.getElementById(\'fade_'+ divUnico + '\').style.display=\'none\'"></div> ';
				sauxhtml +='<div id="light_'+ divUnico + '" class="modal modallight"><div id=' + divUnico + '-player>';
				sauxhtml +='</div></div></div>';
				html = html + sauxhtml;
			}
			contenedor.innerHTML = html;
			contenedor.firstChild.firstChild.onclick = accion;
			if (ancho!=644){//la pintamos después de que se haya puesto en el DOM el id del player			
				obtenerCapaModal (opciones, divUnico, video, ancho, alto, true);
			}else{
				obtenerCapaModal (opciones, divUnico, video, ancho, alto, false);
			}
			if (ancho==644 && (location.href.indexOf(".es/videos-")!=-1 || location.href.indexOf(".es/multimedia-videos/videos-de-abc.asp")!=-1)){
				this._showVideoBC(iDivHTML5, video, ancho, alto, opciones);	
			}
		}
		
	},	
	
	getURLBaseBC: function(url) {
		if (this.portal && this.INFO_PORTALES[this.portal]) {
			if (this.INFO_PORTALES[this.portal].baseConfig) {
				// si el portal tiene un baseConfig especifico, lo uso
				return this.INFO_PORTALES[this.portal].dominio + this.INFO_PORTALES[this.portal].baseConfig + url;
			} else {
				return this.INFO_PORTALES[this.portal].dominio + this.BASE_CONFIG + url;
			}
		} else {
			return this.BASE_CONFIG + url;
		}
	},
	
	getFullURLBC: function(src) {
		if (src.indexOf("//") == -1 && !(src.charAt(0) == "/")) {

			var ruta = location.href.substring(0, location.href.lastIndexOf("/") + 1);
			src = ruta + src;
		} else if (src.charAt(0) == "/") {

			src = location.protocol + "//" + location.host + src;
		}
		return src;
	},

	getURLResizerBC: function(src, ancho, alto, marcaAgua) {
		var result = this.getFullURLBC(src);
		
		if (this.portal) {
			var medio = "";
			var medio = this.INFO_PORTALES[this.portal].resizer;
			
			if (!medio) {
				medio = this.portal + ".es";
			}
			
			//en el resizer no esta incluido el dominio ni de desarrollo2010ABC ni de integracion2010ABC, por eso no se hace para esos casos el resizer.
			if (!isDesarrolloABC(result)) {
				if (marcaAgua) {
					result = "http://resizer." + medio + "/resizer/resizer.php?imagen=" + result + "&nuevoancho=" + ancho + "&nuevoalto=" + alto + "&copyright=false&encrypt=false&marcaagua=" + marcaAgua + "&posmarca="+sPosmarca+"&transparencia="+sTransparencia;
				} else {
					result = "http://resizer." + medio + "/resizer/resizer.php?imagen=" + result + "&nuevoancho=" + ancho + "&nuevoalto=" + alto + "&copyright=conCopyright&encrypt=false";
				}
			}
		}
		
		return result;
	}
};


(function() {
	var prototipo = PlayerWebTVBC.prototype;
	for (var prop in PlayerWebTVBC) {
		if (prop != "prototype") {
			prototipo[prop] = PlayerWebTVBC[prop];
		}
	}
})();

function redimensionado(){

	$('.sombra').parent(".wrapper").children(".unvideo").children(".mosca-player").each(function(){
		ajustesMosca($(this));		
	}); //each
	
	 $('.alto').each(function(){
			//left: ((($(this).width() - $('.caja',$(this)).outerWidth())/2)<0)?0:(($(this).width() - $('.caja',$(this)).outerWidth())/2),
			//top: ((($(this).height() - $('.caja',$(this)).outerHeight())/2)<0)?0:(($(this).height() - $('.caja',$(this)).outerHeight())/2),
		 	$(this).resize(function(){
				$('.caja',$(this)).css({
				   position:'absolute',
				   top:'0px',
				   left:'0px',
				   //'margin-left': ((($(this).width() - $('.caja',$(this)).outerWidth())/2)<0)?0:(($(this).width() - $('.caja',$(this)).outerWidth())/2),
                   'margin-top': ((($(this).height() - $('.caja',$(this)).outerHeight())/2)<0)?0:(($(this).height() - $('.caja',$(this)).outerHeight())/2),
				   display: 'block'
				});
		});
		$(this).resize();
		
		$(this).parent(".unvideo").parent(".wrapper").css (
		{
				   position:'relative',
				   width: $(this).width() ,
				   height: $(this).height()
		})
		
	 });
	 
}

function ajustesMosca(elemento){

	var altosombra =elemento.parent(".unvideo").parent(".wrapper").children(".sombra").outerHeight() ;
	var diferencia =12;  // margen añadido
	var alturamosca =67; // alto de la imagen del boton
	var separacion = - (altosombra+diferencia+alturamosca);
	var $margin = separacion + 'px auto 0';	 
	elemento.css ({			
		margin: $margin,
		display: 'block'
		}
	)
} //ajustesMosca		


$(document).ready(function() {	
	redimensionado();
	
	//para ie	
   $('.sombra').resize(function(){						
		 $(this).parent(".wrapper").children(".unvideo").children(".mosca-player").each(function(){	 
			ajustesMosca($(this));	
		 }); //each		
	}) //sombra.resize
	
	//para firefox
	$('.sombra').parent(".wrapper").children(".unvideo").children(".mosca-player").each(function(){
		ajustesMosca($(this));	
	}); //each
	
	//para ie
	$(".unvideo").resize(function(){									
		mostrarMoscasOcultasSinSombra ($(this));			
	}) ; //unvideo.resize

	//para firefox
	$('.unvideo').each(function(){
		var unvideo = $(this);		
		mostrarMoscasOcultasSinSombra (unvideo);
	}) ; //unvideo.each
	

});

function mostrarMoscasOcultasSinSombra(unvideo) {
	unvideo.parent(".wrapper").each(function(){
		var wrapper = $(this);
		if (wrapper.children(".sombra").attr("class")==undefined) {			
			wrapper.children(".unvideo").children(".mosca-player").show();

		}
	}) ; //each wrapper		
}

function elipsis(){
	$('.player .subhead').each(function(){
		var len = 200; // longitud en caracteres a recortar
		var $p = $(this);
		var trunc = $p.html();
		if (trunc.length > len) {
			trunc = trunc.substring(0, len);
			trunc = trunc.replace(/[\wáéíóúÁÉÍÓÚñÑçÇàèìòùüïÜÏÀÈÌÒÙ\.]+$/, '');
			trunc += '<a href="'+$(this).parents("div").children("h3").children("a.enlaceNoticia").attr("href") +'"  > ...<\/a>';
			$p.html(trunc);
		}
	}) 
}

/*********************************************** CONFIGURATION ************************************************/

/**
 * This value indicates whether or not your account is set-up for UDS. HTML5 requires that the files be delivered
 * over HTTP.  This is accomplished by having an account that is configured for HTTP (PD) delivery or that is set-up
 * for UDS. 
 */
var isUDS = true;

/* This variable is a dictionary that contains information about the location of each
 * Brightcove video object within the DOM of the page. Specifically, it is an associative array
 * where, for each stored mapping, the keys is the playerID of a given video, and the value is
 * the next sibling of that video object in the DOM. Keeping track of this sibling will allow
 * us to re-insert the mobile compatible <video> tag into the correct place (before this sibling)
 * in the DOM of the original page.
 */
var pagePlacementInfo = new Object();

/**********************************************************************************************************************/
/*********************************************** DOM MODIFICATION CODE ************************************************/
/**********************************************************************************************************************/


/* This method works on a specific object, represented by id "strObjID". The method retrieves the
 * element with the given ID from the DOM, and then extracts the player ID from the video
 * object. Then, it removes the video object from the page's DOM and stores its location in the page
 * in a global dictionary variable (this will be useful when we want to add the corresponding
 * video tag back in the page in the appropriate place).
 *
 * Finally, the method submits an API Read request to the Brightcove server through the initiateMobileVideoRetrieval()
 * method in order to retrieve the sepcific Video URL corresponding to the given object.
 */
function makeMobileCompatible(strObjID, videoTagID,playerID,videoPlayer,iWidth,iHeight,sReadToken){
	//our video object (which we need to remove)
	//var vidObj = document.getElementById(strObjID);
	
	//extract the playerID of this video object before deleting it
	var vidPlayerID = playerID;//getParamValueForVidObject(vidObj, 'playerID');
	var programmedVideo = videoPlayer;//getParamValueForVidObject(vidObj, '@videoPlayer');

	//if the video player ID could not be extracted from the Source Code, for some reason,
	//then refer to the dictionary provided by the user
	if (vidPlayerID == null || typeof vidPlayerID == 'undefined'){
			vidPlayerID = BCVidObjects[strObjID];
	}
	
	return initiateMobileVideoRetrieval(vidPlayerID, programmedVideo, sReadToken, videoTagID, strObjID,iWidth,iHeight);
}


/** 
 * This function takes an object representing a Brigthcove video embed and a particular 'parameter' that was
 * passed to the Brightcove video object and returns the parameter.
 */
function getParamValueForVidObject(vidObj, paramName) {
	//these are the children nodes of the given object in the DOM
	var childrenNodes = vidObj.childNodes;
	var tagName;
	
	//loop through all children of the video object, searching for <param> tags.
	//each time we find a <param> tag, we check whether its name is 'flashVars'.
	//if so, we store the param's value and break from the loop, otherwise we
	//continue
	for (var i = 0; i < childrenNodes.length; i++){
	    if (childrenNodes[i].nodeType != 1) {
		continue;
	    }

	    tagName = childrenNodes[i].tagName.toLowerCase();
	    if (tagName == "param"){
		if (childrenNodes[i].getAttribute("name") == paramName){
		    return childrenNodes[i].getAttribute("value");
		}
	    }
	}

	return null;
}

/**
 * Takes a string 'str' that consists of multiple arguments separated by ampersands (&),
 * and breaks it down so that it can extract and return the paramName from the string.
 */
function parseParamFromString(str, paramName) {
	var params = str.split("&"); //array of strings
	for (var i = 0; i < params.length; i++){
		if (params[i].indexOf(paramName) != -1){
			return params[i].substr(params[i].indexOf("=")+1);
		}
	}
	
	// if we could not find the param then return null
	return null;
}



/**********************************************************************************************************************/
/****************************************** MEDIA API CALLS & VIDEO TAG INSERTION *************************************/
/**********************************************************************************************************************/

/* This method calls the Brightcove Media API to get all playlists included within a particular
 * playerID.
 */
function initiateMobileVideoRetrieval(playerID, programmedVideoID, readAPIToken, videoTagID, strObjID,iWidth,iHeight) {
    var APICall;
    var scriptNode;
    var scriptText;
    var callbackMethodName;

    if (programmedVideoID) {
		if (programmedVideoID.indexOf('ref:') != -1) {
			APICall = "http://api.brightcove.com/services/library?command=find_video_by_reference_id&reference_id="+programmedVideoID.substring(4)+"&token="
			+readAPIToken;
		}
		else {
			APICall = "http://api.brightcove.com/services/library?command=find_video_by_id&video_id="+programmedVideoID+"&token="
			+readAPIToken;
		}

		//when we make the API call, we specify a response handler (known as a callback method) that will deal with the response from
		//the Brightcove server. However, we create a customized 'callback' method for each playerID, so that when we are 'inside' the
		//callback method (after receiving the server's reponse), we will know which playerID the response corresponds to. This variable
		//stores the name (which includes the playerID) of that callback method.
		callbackMethodName = "handleJSONResponseForID"+new Date().getTime();
		scriptText = 
			"</script><script>function "+callbackMethodName+"(JSONResponse){" + 
				"var sCad = handleVideoResponse(JSONResponse, '"+playerID+"', '"+videoTagID+"', '"+strObjID+"', '"+iWidth+"', '"+iHeight+"');$('"+strObjID+"').html(sCad);"+
			"}</script>";

    }

    if (isUDS) {
		APICall += "&media_delivery=http";
    }

	//NOTE: we add to the end of the body, so that we do not disrupt any of the order of the children
	//at the top of the body's DOM tree	
	//make the API call, specifying the unique callback method for this request
	var sScript = addScriptTag("getMobileRendition",  APICall, callbackMethodName);
	return scriptText + sScript;
}

/* Methods needed to make API Calls to the Brightcove server*/
function addScriptTag(id, url, callback) {
	
	var root = document.createElement ("span");
	//var elemento = document.createElement ("script");
	var scriptTag = document.createElement("script");
	var noCacheIE = '&noCacheIE=' + (new Date()).getTime();
   
	// Add script object attributes
	scriptTag.setAttribute("type", "text/javascript");
	scriptTag.setAttribute("charset", "utf-8");
	scriptTag.setAttribute("src", url + "&callback=" + callback + noCacheIE);
	scriptTag.setAttribute("id", id);
	root.appendChild(scriptTag);
	return root.innerHTML;	
	
}

/**
 * This is the general response-handler for the JSON response from the Brightcove server for playlist based players.
 * The arguments to the method include the response object, as well as the playerID of the 
 * object which this response pertains to.
 *
 */
function handleVideoResponse(JSONResponse, playerID, videoTagID, strObjID,iWidth,iHeight) {
    return embedHTML5PlayerForVideo(JSONResponse, playerID, videoTagID, strObjID,iWidth,iHeight);
}

/** 
 * For a given video object (from the BC APIs) we will embed an HTML 5 'video' tag.
 * Requires searching through the renditions associated with the video object
 * for a rendition that is a 'best' match and passing the URL to the video
 * tag.
 *
 * In this handler, we explore the JSON object in search of the first video in the
 * first playlist that is returned by the Brightcove server. Then, once we identify
 * this first video, we examine the various renditions of the video and search
 * for the rendition that is most appropriate for a mobile (H.264 encoding 
 * and 256 kbps). 
 */
function embedHTML5PlayerForVideo(video, playerID, videoTagID, strObjID,iWidth,iHeight) {
	//obtain the array of various renditions that exist for this video.
	//NOTE: a rendition, from our perspective, has a certain encoding rate,
	//      and a certain encoding format. We wish to find the best rendition for
	//      a smartphone.
	var renditions = video.renditions;
	
	//In the for-loop that follows, we traverse all renditions of this first video, searching
	//for the H.264 (mobile-compatible) rendition whose encoding rate is closest to 256kbps
	var bestRenditionIndex = -1;
	var bestEncodingRateSoFar = -1;
	
	for (var i = 0; i < renditions.length; i = i+1){
		//if this rendition is not H264, skip it and move on to the next
		if (renditions[i].videoCodec != "H264"){
			continue;
		}
		
		//if best rendition index variable is uninitialized, then initialize it to
		//this rendition (which is H.264) - we need this because it's possible that
		//there are no H264 renditions at all, and starting our bestRenditionIndex at
		//an invalid value will help us figure out whether we came across any H264 renditions
		//as we were looping.
		if (bestRenditionIndex == -1){
			bestRenditionIndex = i;
			bestEncodingRateSoFar = renditions[i].encodingRate;
		}
		
		//otherwise check to see if this rendition has a better encoding rate than the best one before this
		else if (betterEncodingForMobile(renditions[i].encodingRate, bestEncodingRateSoFar) == renditions[i].encodingRate){
			//if so, then record this rendition as the best one so far
			bestRenditionIndex = i;
			bestEncodingRateSoFar = renditions[i].encodingRate;
		}
	}
	//after the for-loop has terminated, if best rendition index still == -1,
	//then that means we don't have ANY H264 renditions. so let the user know,
	//and don't add anything to the page
	if (bestRenditionIndex == -1){
	    bestRendition = video.videoFullLength;
	}
	else {
		bestRendition = renditions[bestRenditionIndex];
	}
	var bestRenditionURL = bestRendition.url;
	var vidName = video.name;
	var vidHeight = iHeight;//bestRendition.frameHeight;
	var vidWidth = iWidth;//bestRendition.frameWidth;
	var vidStillURL = video.videoStillURL;
	//construct the <video> tag as a DOM element
	//var videoScriptTag = formVideoTagFromInfo(videoTagID, vidName, bestRenditionURL, vidWidth, vidHeight, vidStillURL);	
	var isModal = (strObjID.match(/^.*\.photo-center$/)!=null );
	//alert (isModal);
	var videoScriptTag = formVideoTagFromInfo(videoTagID, vidName, bestRenditionURL, vidWidth, vidHeight, vidStillURL, isModal);	
	return videoScriptTag;
}

/* This function takes two encoding rates and returns the one that
 * is more apprporiate for mobile phones.
 */
function betterEncodingForMobile(encoding1, encoding2){
	IDEAL_ENCODING_RATE = 256000; //bits per second; equivalent to 256 kbps
	diff1 = Math.abs(encoding1 - IDEAL_ENCODING_RATE);
	diff2 = Math.abs(encoding2 - IDEAL_ENCODING_RATE);
	return ((diff1 <= diff2) ? encoding1 : encoding2);
}

/**
 * This method takes properties of a video, its dimensions, and its poster (still image),
 * inserts them into an HTML 5.0 <video> tag. This <video> object is then returned.
 */
function formVideoTagFromInfo(videoTagID, videoID, videoURL, vidWidth, vidHeight, vidImageURL,isModal){
	var idVideo = null;
	if (videoTagID) {
	    idVideo = videoTagID;
	}
	else {
	    idVideo = videoID;
	}
	var sReturn = '<video ';
	sReturn += 'height="'+vidHeight+'" width="'+vidWidth+'" id="'+idVideo+'" ';
	sReturn += 'poster="'+vidImageURL+'" ';
	sReturn += 'controls="true" autoplay="autoplay" ';
	if (isModal) {
		sReturn += 'onloadstart=abrirModalRetardado("' + relidGlobal + '");this.play(); ';
	}
	sReturn +='src="'+videoURL+'" >';
	sReturn += '</video>';
	return sReturn;
}

function gaweb() {
    dominiosWebTV=['www.elcorreo.com/videos','www.diariovasco.com/videos','www.nortecastilla.es/videos','www.eldiariomontanes.es/videos','www.elcomerciodigital.com/videos','www.hoy.es/videos','www.ideal.es/videos','www.larioja.com/videos','www.lavozdigital.es/videos','www.lasprovincias.es/videos','www.laverdad.es/videos','www.diariosur.es/videos','www.abc.es/videos','www.abcdesevilla.es/videos'];
    for (i=0;i<dominiosWebTV.length;i++){ 
    	var pos=document.URL.indexOf(dominiosWebTV[i]);
        if (pos>=0){
        	return 'WebTV';
        }              
    }
    dominios=['elcorreo.com','diariovasco.com','nortecastilla.es','eldiariomontanes.es','elcomerciodigital.com','hoy.es','ideal.es','larioja.com','lavozdigital.es','lasprovincias.es','laverdad.es','diariosur.es','abc.es','abcdesevilla.es'];
    for (i=0;i<dominios.length;i++){ 
    	var pos=document.domain.indexOf(dominios[i]);
        if (pos>=0){
        	return 'Embebido';
        }
    } 
    return 'Otros';
}

function isDefined(variable) { return (typeof(window[variable]) != "undefined");}

