// Carga de SWFObject (libreria de inclusion de objetos flash en html)
if (!SWFObject) {
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpr:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;
}


/**********************************************************************************************************************/
/****************************************** MOBILE BROWSER DETECTION CODE *********************************************/
/**********************************************************************************************************************/
var uagent = navigator.userAgent.toLowerCase();
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;a
}

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;
};
/**********************************************************************************************************************/
/************************************** END MOBILE BROWSER DETECTION CODE *********************************************/
/**********************************************************************************************************************/






var iCont = 0;
var iWidth1 = 0;
var iHeight1 = 0;
var sDiv1 = "";
var sFile1 = "";
var sPreview1 = "";
var floating1 = false;
var fullscreen = false;
var sZonas = "";
var idWMPlayer = "";
function getKeyWords(title) {
	title = title.toLowerCase();
	title = title.replace(/[àáâä]+/g, "a");
	title = title.replace(/[éèêë]+/g, "e");
	title = title.replace(/[ìíîï]+/g, "i");
	title = title.replace(/[óòôö]+/g, "o");
	title = title.replace(/[úùûü]+/g, "u");
	title = title.replace(/[ç]+/g, "c");
	title = title.replace(/\b/g, "_");
	title = title.replace(/\W/g, "");
	var words = title.split("_");
	var keywords = "";
	for ( var i = 0; i < words.length; i++) {
		if (3 < words[i].length)
			keywords += "," + words[i];
	}
	if (keywords != "")
		keywords = keywords.substring(1);

	return keywords;
}
//Player antiguo
function showPlayer(sPlayer, sTags, sZonas, bStretch) {
	var fo = new SWFObject(sPlayer, "movie_player", iWidth1, iHeight1, 8,
			"#000000");
	fo.addParam("allowfullscreen", fullscreen1);
	fo.addParam("wmode", "transparent");
	fo.addVariable("image", sPreview1);
	fo.addVariable("width", iWidth1);
	if (typeof (bStretch) != 'undefined')
		fo.addVariable("overstretch", bStretch);
	else
		fo.addVariable("overstretch", "true");
	fo.addVariable("height", iHeight1);
	fo.addVariable("file", sFile1);
	if (floating1)
		fo.addVariable("displayheight", iHeight1);
	fo.addVariable("sZonas", sZonas);
	fo.addVariable("p1U", sZonas);
	fo.addVariable("sTags", sTags);
	fo.write(sDiv1);
}

function loadMethodeVideo(div, w, h, sFile, sPreview, fullscreen, floating,
		sPortal, sZonas, sTitle, sCategory, bStretch) {
	
	/*var opciones = {
		categoriaPubli: sCategory,
		titulo: sTitle,
		imgPrevia: sPreview,
		site: sPortal
	};
	
	PlayerWebTV.cargaVideo(div, sFile, w, h, opciones);*/
	loadMultimedia(div, w, h, sFile, sPreview, sPortal, sTitle, sCategory);
}

function prueba(){
	$("#playervid").attr("style","position: absolute; top: 26px; left: 22px; height: 160px; width: 268px;");
}

function loadMultimedia(div, w, h, sFile, sPreview, sPortal, sTitle, sCategory, opciones) {	
	var opcionesOK = null;
	if (opciones == undefined) {
		opcionesOK = {
			categoriaPubli: sCategory,
			titulo: sTitle,
			imgPrevia: sPreview,
			site: sPortal
		};
	}
	else {
		opcionesOK = {
			categoriaPubli: (opciones.categoriaPubli == undefined) ? sCategory : opciones.categoriaPubli,
			titulo: (opciones.titulo == undefined) ? sTitle : opciones.categoriaPubli,
			imgPrevia: (opciones.imgPrevia == undefined) ? sPreview : opciones.imgPrevia,
			site: (opciones.site == undefined) ? sPortal : opciones.site,
			entradilla: (opciones.entradilla == undefined) ? '' : opciones.entradilla,
			urlTitulo: (opciones.urlTitulo == undefined) ? '' : opciones.urlTitulo,
			imgPatrocinio: (opciones.imgPatrocinio == undefined) ? '' : opciones.imgPatrocinio,
			urlPatrocinio: (opciones.urlPatrocinio == undefined) ? '' : opciones.urlPatrocinio,
			clickcommand: (opciones.clickcommand == undefined) ? '' : opciones.clickcommand,
			capaModal: (opciones.capaModal == undefined) ? true : opciones.capaModal,
			publicidadOn: (opciones.publicidadOn == undefined) ? true : opciones.publicidadOn,
			redesSociales: (opciones.redesSociales == undefined) ? true : opciones.redesSociales
		};
	}
	PlayerWebTV.cargaVideo (div, sFile, w, h, opcionesOK);
}

function mandarOAS() {
	return getOAS_sitepage(OAS_sitepage);
}
/**
  Obtiene el OAS Site Page correcto en función del valor de la variable que tiene esta pagina
*/
function getOAS_sitepage(sOAS_sitepage) {

	var campos = sOAS_sitepage.split('/');		
	var campos2 = campos[0].split('.');
	
	switch (campos2[1]) {
		case 'elcomercio-sa':
			var periodico = 'elcomerciodigital';
			break;
		case 'diario-elcorreo':
			var periodico = 'elcorreodigital';
			break;
		case 'la-verdad':
			var periodico = 'laverdad';
			break;
		case 'lavozdecadiz':
			var periodico = 'lavozdigital';
			break;
		default:
			var periodico = campos2[1];
			break;	
	}
	
	//var ediciones = new Array('alava', 'vizcaya', 'aviles', 'gijon', 'oviedo', 'almeria', 'granada', 'jaen', 'alicante', 'valencia', 'albacete', 'murcia', 'cadiz', 'jerez', 'castellon');		
	var separador = '/';	
	var respuesta = 'vocento.' + periodico;
	var cont = 1;
	while( campos[cont] != null )
	{
		respuesta += separador + campos[cont];
		cont++;	
	}
	return respuesta;

}
	

/**
 * Constructor
 */
function PlayerWebTV() {
	this.initted = false;
	this.portal = null;
	this.mosca  = null;
	this.rutaConfig  = null;
}

// ************************************************************************
// ******************  CONSTANTES *****************************************
//************************************************************************
PlayerWebTV.MIN_ANCHO_PLAYER = 180;
PlayerWebTV.MIN_ALTO_PLAYER = 100;
PlayerWebTV.BASE_CONFIG  = "/includes/manuales/swf/playerWebTV/";
PlayerWebTV.VERSION_FLASH  = 8;

/**
 * CTES identificadoras de los portales
 */
PlayerWebTV.IDS_PORTALES = {
	ABC: "abc",
	ABC_SEVILLA: "abcdesevilla",
	NORTE_CASTILLA: "nortecastilla",
	LA_VOZ: "lavozdigital",
	DIARIO_MONTANES: "eldiariomontanes",
	DIARIO_SUR: "diariosur",
	DIARIO_VASCO: "diariovasco",
	EL_COMERCIO: "elcomerciodigital",
	EL_CORREO: "elcorreo",
	EL_CORREODIGITAL: "elcorreodigital",
	HOY: "hoy",
	IDEAL: "ideal",
	LA_RIOJA: "larioja",
	LA_VERDAD: "laverdad",
	LAS_PROVINCIAS: "lasprovincias",
	SUR_INGLES:	"sureng",
	ABC_F1: "abc_f1",
	ABC_SEVILLA_F1: "abcdesevilla_f1",
	NORTE_CASTILLA_F1: "nortecastilla_f1",
	LA_VOZ_F1: "lavozdigital_f1",
	DIARIO_MONTANES_F1: "eldiariomontanes_f1",
	DIARIO_SUR_F1: "diariosur_f1",
	DIARIO_VASCO_F1: "diariovasco_f1",
	EL_COMERCIO_F1: "elcomerciodigital_f1",
	EL_CORREO_F1: "elcorreo_f1",
	EL_CORREODIGITAL_F1: "elcorreodigital_f1",
	HOY_F1: "hoy_f1",
	IDEAL_F1: "ideal_f1",
	LA_RIOJA_F1: "larioja_f1",
	LA_VERDAD_F1: "laverdad_f1",
	LAS_PROVINCIAS_F1: "lasprovincias_f1"
	
};

/**
 * Contador para retrasar la carga de multiples videos a la vez en IExplorer
 */
PlayerWebTV.ieCounter = 1;

/**
 * entorno en el que nos encontramos
 */
PlayerWebTV.entorno = getEntorno();

//TODO: faltan mas configuraciones de portales
/**
 * Informacion de los portales
 */
PlayerWebTV.INFO_PORTALES = {};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.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": PlayerWebTV.entorno,
	"baseConfig": "/swf/playerWebTV/"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.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": PlayerWebTV.entorno,
	"baseConfig": "/swf/playerWebTV/"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.NORTE_CASTILLA] = {
	"resizer": "nortecastilla.es",
	"servidores": [PlayerWebTV.entorno + ".nortecastilla.es"],
	"dominio": "http://" + PlayerWebTV.entorno + ".nortecastilla.es",
	"idPlayer": "292158289001",
	"idPlayerSinPublicidad": "661006236001",
	"idPublisher": "86746486001",
	"medio": "NORCAS"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.LA_VOZ] = {
	"resizer": "lavozdigital.es",
	"servidores": [PlayerWebTV.entorno + ".lavozdigital.es"],
	"dominio": "http://" + PlayerWebTV.entorno + ".lavozdigital.es",
	"idPlayer": "292326712001",
	"idPlayerSinPublicidad": "660958362001",
	"idPublisher": "86847173001",
	"medio": "VOZCAD"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.DIARIO_MONTANES] = {
	"resizer": "eldiariomontanes.es",
	"servidores": [PlayerWebTV.entorno + ".eldiariomontanes.es"],
	"dominio": "http://" + PlayerWebTV.entorno + ".eldiariomontanes.es",
	"idPlayer": "308992240001",
	"idPlayerSinPublicidad": "660562415001",
	"idPublisher": "85707285001",
	"medio": "DIAMON"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.DIARIO_SUR] = {
	"resizer": "diariosur.es",
	"servidores": [PlayerWebTV.entorno + ".diariosur.es"],
	"dominio": "http://" + PlayerWebTV.entorno + ".diariosur.es",
	"idPlayer": "309045659001",
	"idPlayerSinPublicidad": "660562414001",
	"idPublisher": "85688293001",
	"medio": "SUR"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.SUR_INGLES] = {
	"resizer": "surinenglish.com",
	"servidores": [PlayerWebTV.entorno + ".surinenglish.com"],
	"dominio": "http://" + PlayerWebTV.entorno + ".surinenglish.com",
	"idPlayer": "309045659001",
	"idPlayerSinPublicidad": "309045659001",
	"idPublisher": "85688293001",
	"medio": "SURENG"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.DIARIO_VASCO] = {
	"resizer": "diariovasco.com",
	"servidores": [PlayerWebTV.entorno + ".diariovasco.com"],
	"dominio": "http://" + PlayerWebTV.entorno + ".diariovasco.com",
	"idPlayer": "292369646001",
	"idPlayerSinPublicidad": "660588367001",
	"idPublisher": "85688294001",
	"medio": "DIAVAS"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.EL_COMERCIO] = {
	"resizer": "elcomerciodigital.com",
	"servidores": [PlayerWebTV.entorno + ".elcomerciodigital.com"],
	"dominio": "http://" + PlayerWebTV.entorno + ".elcomerciodigital.com",
	"idPlayer": "308992247001",
	"idPlayerSinPublicidad": "660958355001",
	"idPublisher": "85707284001",
	"medio": "COMERC"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.EL_CORREO] = {
	"resizer": "elcorreo.com",
	"servidores": [PlayerWebTV.entorno + ".elcorreo.com"],
	"dominio": "http://" + PlayerWebTV.entorno + ".elcorreo.com",
	"idPlayer": "309018193001",
	"idPlayerSinPublicidad": "661006233001",
	"idPublisher": "85688292001",
	"medio": "CORREO"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.EL_CORREODIGITAL] = {
	"resizer": "elcorreo.com",
	"servidores": [PlayerWebTV.entorno + ".elcorreo.com"],
	"dominio": "http://" + PlayerWebTV.entorno + ".elcorreo.com",
	"idPlayer": "309018193001",
	"idPlayerSinPublicidad": "661006233001",
	"idPublisher": "85688292001",
	"medio": "CORREO"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.HOY] = {
	"resizer": "hoy.es",
	"servidores": [PlayerWebTV.entorno + ".hoy.es"],
	"dominio": "http://" + PlayerWebTV.entorno + ".hoy.es",
	"idPlayer": "309010012001",
	"idPlayerSinPublicidad": "661006227001",
	"idPublisher": "85688295001",
	"medio": "HOY"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.IDEAL] = {
	"resizer": "ideal.es",
	"servidores": [PlayerWebTV.entorno + ".ideal.es"],
	"dominio": "http://" + PlayerWebTV.entorno + ".ideal.es",
	"idPlayer": "309010008001",
	"idPlayerSinPublicidad": "661006234001",
	"idPublisher": "86746483001",
	"medio": "IDEALM"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.LA_RIOJA] = {
	"resizer": "larioja.com",
	"servidores": [PlayerWebTV.entorno + ".larioja.com"],
	"dominio": "http://" + PlayerWebTV.entorno + ".larioja.com",
	"idPlayer": "309010007001",
	"idPlayerSinPublicidad": "660958361001",
	"idPublisher": "86746484001",
	"medio": "RIOJA"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.LA_VERDAD] = {
	"resizer": "laverdad.es",
	"servidores": [PlayerWebTV.entorno + ".laverdad.es"],
	"dominio": "http://" + PlayerWebTV.entorno + ".laverdad.es",
	"idPlayer": "292369619001",
	"idPlayerSinPublicidad": "661006235001",
	"idPublisher": "85707286001",
	"medio": "VERMUR",
	"dominio2": "http://" + PlayerWebTV.entorno + ".lasprovincias.es"
		
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.LAS_PROVINCIAS] = {
	"resizer": "lasprovincias.es",
	"servidores": [PlayerWebTV.entorno + ".lasprovincias.es"],
	"dominio": "http://" + PlayerWebTV.entorno + ".lasprovincias.es",
	"idPlayer": "308992236001",
	"idPlayerSinPublicidad": "660588370001",
	"idPublisher": "86746485001",
	"medio": "PROVAL",
	"dominio2": "http://" + PlayerWebTV.entorno + ".laverdad.es"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.ABC_F1] = {
	"resizer": "abc.es",
	"servidores": ["abc.es", "http://212.81.129.25:8280", "http://212.81.129.25", "http://preproduccionabc.abc.es"],
	"dominio": PlayerWebTV.entorno,
	"baseConfig": "/swf/playerWebTV/"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.ABC_SEVILLA_F1] = {
	"resizer": "abc.es",
	"servidores": ["abcdesevilla.es", "http://212.81.129.25:8281", "http://212.81.129.25", "http://preproduccionsevilla.abc.es"],
	"dominio": PlayerWebTV.entorno,
	"baseConfig": "/swf/playerWebTV/"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.NORTE_CASTILLA_F1] = {
	"resizer": "nortecastilla.es",
	"servidores": [PlayerWebTV.entorno + ".nortecastilla.es"],
	"dominio": "http://" + PlayerWebTV.entorno + ".nortecastilla.es",
	"idPlayer": "292158289001",
	"idPlayerSinPublicidad": "292158289001",
	"idPublisher": "86746486001",
	"medio": "NORCAS"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.LA_VOZ_F1] = {
	"resizer": "lavozdigital.es",
	"servidores": [PlayerWebTV.entorno + ".lavozdigital.es"],
	"dominio": "http://" + PlayerWebTV.entorno + ".lavozdigital.es",
	"idPlayer": "292326712001",
	"idPlayerSinPublicidad": "292326712001",
	"idPublisher": "86847173001",
	"medio": "VOZCAD"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.DIARIO_MONTANES_F1] = {
	"resizer": "eldiariomontanes.es",
	"servidores": [PlayerWebTV.entorno + ".eldiariomontanes.es"],
	"dominio": "http://" + PlayerWebTV.entorno + ".eldiariomontanes.es",
	"idPlayer": "308992240001",
	"idPlayerSinPublicidad": "308992240001",
	"idPublisher": "85707285001",
	"medio": "DIAMON"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.DIARIO_SUR_F1] = {
	"resizer": "diariosur.es",
	"servidores": [PlayerWebTV.entorno + ".diariosur.es"],
	"dominio": "http://" + PlayerWebTV.entorno + ".diariosur.es",
	"idPlayer": "309045659001",
	"idPlayerSinPublicidad": "309045659001",
	"idPublisher": "85688293001",
	"medio": "SUR"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.SUR_INGLES_F1] = {
	"resizer": "surinenglish.com",
	"servidores": [PlayerWebTV.entorno + ".surinenglish.com"],
	"dominio": "http://" + PlayerWebTV.entorno + ".surinenglish.com",
	"idPlayer": "309045659001",
	"idPlayerSinPublicidad": "309045659001",
	"idPublisher": "85688293001",
	"medio": "SURENG"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.DIARIO_VASCO_F1] = {
	"resizer": "diariovasco.com",
	"servidores": [PlayerWebTV.entorno + ".diariovasco.com"],
	"dominio": "http://" + PlayerWebTV.entorno + ".diariovasco.com",
	"idPlayer": "292369646001",
	"idPlayerSinPublicidad": "292369646001",
	"idPublisher": "85688294001",
	"medio": "DIAVAS"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.EL_COMERCIO_F1] = {
	"resizer": "elcomerciodigital.com",
	"servidores": [PlayerWebTV.entorno + ".elcomerciodigital.com"],
	"dominio": "http://" + PlayerWebTV.entorno + ".elcomerciodigital.com",
	"idPlayer": "308992247001",
	"idPlayerSinPublicidad": "308992247001",
	"idPublisher": "85707284001",
	"medio": "COMERC"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.EL_CORREO_F1] = {
	"resizer": "elcorreo.com",
	"servidores": [PlayerWebTV.entorno + ".elcorreo.com"],
	"dominio": "http://" + PlayerWebTV.entorno + ".elcorreo.com",
	"idPlayer": "309018193001",
	"idPlayerSinPublicidad": "309018193001",
	"idPublisher": "85688292001",
	"medio": "CORREO"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.EL_CORREODIGITAL_F1] = {
	"resizer": "elcorreo.com",
	"servidores": [PlayerWebTV.entorno + ".elcorreo.com"],
	"dominio": "http://" + PlayerWebTV.entorno + ".elcorreo.com",
	"idPlayer": "309018193001",
	"idPlayerSinPublicidad": "309018193001",
	"idPublisher": "85688292001",
	"medio": "CORREO"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.HOY_F1] = {
	"resizer": "hoy.es",
	"servidores": [PlayerWebTV.entorno + ".hoy.es"],
	"dominio": "http://" + PlayerWebTV.entorno + ".hoy.es",
	"idPlayer": "309010012001",
	"idPlayerSinPublicidad": "309010012001",
	"idPublisher": "85688295001",
	"medio": "HOY"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.IDEAL_F1] = {
	"resizer": "ideal.es",
	"servidores": [PlayerWebTV.entorno + ".ideal.es"],
	"dominio": "http://" + PlayerWebTV.entorno + ".ideal.es",
	"idPlayer": "309010008001",
	"idPlayerSinPublicidad": "309010008001",
	"idPublisher": "86746483001",
	"medio": "IDEALM"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.LA_RIOJA_F1] = {
	"resizer": "larioja.com",
	"servidores": [PlayerWebTV.entorno + ".larioja.com"],
	"dominio": "http://" + PlayerWebTV.entorno + ".larioja.com",
	"idPlayer": "309010007001",
	"idPlayerSinPublicidad": "309010007001",
	"idPublisher": "86746484001",
	"medio": "RIOJA"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.LA_VERDAD_F1] = {
	"resizer": "laverdad.es",
	"servidores": [PlayerWebTV.entorno + ".laverdad.es"],
	"dominio": "http://" + PlayerWebTV.entorno + ".laverdad.es",
	"idPlayer": "292369619001",
	"idPlayerSinPublicidad": "292369619001",
	"idPublisher": "85707286001",
	"medio": "VERMUR",
	"dominio2": "http://" + PlayerWebTV.entorno + ".lasprovincias.es"
};
PlayerWebTV.INFO_PORTALES[PlayerWebTV.IDS_PORTALES.LAS_PROVINCIAS_F1] = {
	"resizer": "lasprovincias.es",
	"servidores": [PlayerWebTV.entorno + ".lasprovincias.es"],
	"dominio": "http://" + PlayerWebTV.entorno + ".lasprovincias.es",
	"idPlayer": "308992236001",
	"idPlayerSinPublicidad": "308992236001",
	"idPublisher": "86746485001",
	"medio": "PROVAL",
	"dominio2": "http://" + PlayerWebTV.entorno + ".laverdad.es"
};

/* 
	Inicio: ARRAY DE TAGS PATROCINADOS
*/
var tagsPatrocinados = ['abc', 'abcdesevilla', 'nortecastilla', 'lavozdigital', 'eldiariomontanes', 'diariosur', 'diariovasco', 'elcomerciodigital', 'elcorreo', 'elcorreodigital', 'hoy', 'ideal', 'larioja', 'laverdad', 'lasprovincias', 'sureng'];
tagsPatrocinados['abc']	= null;
tagsPatrocinados['abcdesevilla'] = null;
tagsPatrocinados['nortecastilla'] = null;
tagsPatrocinados['lavozdigital'] = null;
tagsPatrocinados['eldiariomontanes'] = null;
tagsPatrocinados['diariosur'] = null;
tagsPatrocinados['diariovasco'] = null;
tagsPatrocinados['elcomerciodigital'] = null;
tagsPatrocinados['elcorreo'] = null;
tagsPatrocinados['elcorreodigital'] = null;
tagsPatrocinados['ideal'] = null;
tagsPatrocinados['larioja'] = null;
tagsPatrocinados['laverdad'] = null;
tagsPatrocinados['lasprovincias'] = null;
tagsPatrocinados['sureng'] = null;
tagsPatrocinados['hoy'] = null;/*['Sociedad', 'nacional'];
	tagsPatrocinados['hoy']['Sociedad'] = {
		"imgPatrocinio": "/img/logo-instanet.gif",
		"urlPatrocinio": "http://www.abc.es/",
		"clickcommand": ""	
	};
	tagsPatrocinados['hoy']['nacional'] = {
		"imgPatrocinio": "/img/logo-instanet.gif",
		"urlPatrocinio": "http://www.hoy.es/",
		"clickcommand": ""	
	};*/
// Fin: ARRAY DE TAGS PATROCINADOS

/**
 * Caché de controladores para el player
 */
PlayerWebTV.cache = {};

//************************************************************************
//******************  METODOS ESTATICOS **********************************
//************************************************************************

/**
 * Obtiene la extension del fichero multimedia
 */
PlayerWebTV.getExtension = function(video) {
	var result = video;
	
	while (result.indexOf('/') != -1) {
		result = result.substring(result.indexOf('/')+1, result.length);
	}
	
	if (result.indexOf('.') != -1) {
		result = result.substring(result.indexOf('.')+1, result.length);
	}
	
	return result;
};

/**
 * Obtiene el entorno en el que nos encontramos
 */
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;
}

/**
 * Comprueba si es ABC Desarrollo
 */
function isDesarrolloABC() {
	var result = false;

	if ( (location.href.indexOf('http://212.81.129.25:8280') != -1)  ||
		 (location.href.indexOf('http://212.81.129.25:8281') != -1) ) {
			result = true;
	}
	
	return result;
}

/**
 * Comprueba si es ABC en cualquier entorno
 */
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;
}

/**
 * Obtiene el color de fondo
 */
function getColorFondo() {
	var colorFondo = '#000000';

	if (isABC()) colorFondo = '#f1f1f1';
	
	return colorFondo;
}

/**
 * Muestra el player cargandolo en la cache de portales
 */
PlayerWebTV.cargaVideo = function(div, sFile, w, h, adOpciones) {
	var funcion = PlayerWebTV.cargaVideo; 
	if (arguments.length < 5) {
		// Si no nos pasan un id de capa, creamos 1 en la posicion actual y la usamos para escribir el video
		// (CUIDADO!  Si la pagina ya esta cargada, siempre hay que indicar un id, sino borraria la pagina actual)
		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;
	}
	
	//Comprobación de las opciones
	var opciones = {
		categoriaPubli: ((adOpciones.categoriaPubli==undefined)?'':adOpciones.categoriaPubli),
		titulo: ((adOpciones.titulo==undefined)?'':adOpciones.titulo),
		imgPrevia: ((adOpciones.imgPrevia==undefined)?'':adOpciones.imgPrevia),
		site: ((adOpciones.site==undefined)?'':adOpciones.site),
		entradilla: ((adOpciones.entradilla==undefined)?'':adOpciones.entradilla),
		urlTitulo: ((adOpciones.urlTitulo==undefined)?'':adOpciones.urlTitulo),
		imgPatrocinio: ((adOpciones.imgPatrocinio==undefined)?'':adOpciones.imgPatrocinio),
		urlPatrocinio: ((adOpciones.urlPatrocinio==undefined)?'':adOpciones.urlPatrocinio),
		clickcommand: ((adOpciones.clickcommand==undefined)?'':adOpciones.clickcommand),
		capaModal: ((adOpciones.capaModal == undefined) ? true : adOpciones.capaModal),
		publicidadOn: ((adOpciones.publicidadOn == undefined) ? true : adOpciones.publicidadOn),
		redesSociales: (adOpciones.redesSociales == undefined) ? true : adOpciones.redesSociales
	};
	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;
	} else if (config == "sur") {
		config = this.IDS_PORTALES.DIARIO_SUR;
	} else if (config == "diavas") {
		config = this.IDS_PORTALES.DIARIO_VASCO;
	} else if (config == "comerc") {
		config = this.IDS_PORTALES.EL_COMERCIO;
	} else if (config == "correo") {
		config = this.IDS_PORTALES.EL_CORREO;
	} else if (config == "diamon") {
		config = this.IDS_PORTALES.DIARIO_MONTANES;
	} else if (config == "idealm") {
		config = this.IDS_PORTALES.IDEAL;
	} else if (config == "rioja") {
		config = this.IDS_PORTALES.LA_RIOJA;
	} else if (config == "proval") {
		config = this.IDS_PORTALES.LAS_PROVINCIAS;
	} else if (config == "vermur") {
		config = this.IDS_PORTALES.LA_VERDAD;
	} else if (config == "vozcad" || config == "Lavoz" || config == "lavoz") {
		config = this.IDS_PORTALES.LA_VOZ;
	} else if (config == "norcas") {
		config = this.IDS_PORTALES.NORTE_CASTILLA;
	} else if (config == "abc_f1") {
		config = this.IDS_PORTALES.ABC_F1;
	} else if (config == "abcsevilla_f1") {
		config = this.IDS_PORTALES.ABC_SEVILLA_F1;
	} else if (config == "sur_f1") {
		config = this.IDS_PORTALES.DIARIO_SUR_F1;
	} else if (config == "diavas_f1") {
		config = this.IDS_PORTALES.DIARIO_VASCO_F1;
	} else if (config == "comerc_f1") {
		config = this.IDS_PORTALES.EL_COMERCIO_F1;
	} else if (config == "correo_f1") {
		config = this.IDS_PORTALES.EL_CORREO_F1;
	} else if (config == "diamon_f1") {
		config = this.IDS_PORTALES.DIARIO_MONTANES_F1;
	} else if (config == "idealm_f1") {
		config = this.IDS_PORTALES.IDEAL_F1;
	} else if (config == "rioja_f1") {
		config = this.IDS_PORTALES.LA_RIOJA_F1;
	} else if (config == "proval_f1") {
		config = this.IDS_PORTALES.LAS_PROVINCIAS_F1;
	} else if (config == "vermur_f1") {
		config = this.IDS_PORTALES.LA_VERDAD_F1;
	} else if (config == "vozcad_f1" || config == "Lavoz_f1" || config == "lavoz_f1") {
		config = this.IDS_PORTALES.LA_VOZ_F1;
	} else if (config == "norcas_f1") {
		config = this.IDS_PORTALES.NORTE_CASTILLA_F1;
	}
	
	if (!config) {
		player = new PlayerWebTV();
	} else {
		opciones.site = config;
		opciones.config = config;
		if (!PlayerWebTV.cache[config]) {
			PlayerWebTV.cache[config] = new PlayerWebTV();
		}
		player = PlayerWebTV.cache[config];
	}
	
	
	/*if( isVideoBC(sFile) ) {
		player.showVideoBC(div, sFile, w, h, opciones);
	//} else {
		//player.showVideo(div, sFile, w, h, opciones);
	//}*/
	var extension = PlayerWebTV.getExtension(sFile);
	if ((sFile.indexOf('http://cache1.agilecontents.com') != -1) || (extension == 'mp3')) {
		player.showVideo(div, sFile, w, h, opciones);
	} else {
		player.showVideoBC(div, sFile, w, h, opciones);
	}	
};

/**
 * Funcion utilidad para eliminar eventos
 */
PlayerWebTV.nada = function() {};


/**
 * Obtiene el portal del que cargar su configuracion
 * 
 * Si se indica como parametro, se devuelve ese, en otro caso, se calcula de la URL
 */
PlayerWebTV.getPortal = function(opciones) {
	var result = null;
	
	if (opciones && opciones.site) {
		result = opciones.site;
	} else {
		// Identificación por URL
		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;
};





/**
 * Elimina caracteres extraños del titulo
 */
PlayerWebTV.getCleanTitle = function(title) {
	title = title.toLowerCase();
	title = title.replace(/[àáâä]+/g, "a");
	title = title.replace(/[éèêë]+/g, "e");
	title = title.replace(/[ìíîï]+/g, "i");
	title = title.replace(/[óòôö]+/g, "o");
	title = title.replace(/[úùûü]+/g, "u");
	title = title.replace(/[ç]+/g, "c");
	title = title.replace(/ñ/g, "n");
	title = title.replace(/[^ \w]/g, "");
	return title;
};


/**
 * Extrae las palabras clave del titulo
 */
PlayerWebTV.getKeyWords = function(title) {
	var keywords = "";
	if (title) {
		title = title.toLowerCase();
		title = title.replace(/[àáâä]+/g, "a");
		title = title.replace(/[éèêë]+/g, "e");
		title = title.replace(/[ìíîï]+/g, "i");
		title = title.replace(/[óòôö]+/g, "o");
		title = title.replace(/[úùûü]+/g, "u");
		title = title.replace(/[ç]+/g, "c");
		title = title.replace(/[ñ]+/g, "n");
		title = title.replace(/\b/g, "_");
		title = title.replace(/\W/g, "");
		var words = title.split("_");
		var keywords = "";
		for ( var i = 0; i < words.length; i++) {
			if (3 < words[i].length)
				keywords += "," + words[i];
		}
		if (keywords != "") {
			keywords = keywords.substring(1);
		}
	}
	return keywords;
}

/**
 * Elimina caracteres extraños de una URL
 */
PlayerWebTV.cleanURL = function(url) {
	if (url) {
		return url.replace(/[^\w- ]/, "");
	} else {
		return url;
	}
}

/**
 * Genera un identificador unico (se usan 2 numeros aleatorios, ya que varias llamadas consecutivas pueden dar los
 * mismos nanosegundos.
 * @param prefijo Cadena que se contanera al principio del identificador
 * @return prefijo_numAleat_numAleat
 */
PlayerWebTV.getUID = function(prefijo) {
	var result = [new Date().getTime(), Math.ceil(Math.random() * 1000)];
	if (prefijo) {
		result.splice(0, 0, prefijo);
	}
	return result.join("_");
}

//************************************************************************
//******************  METODOS DE CLASE  **********************************
//************************************************************************
PlayerWebTV.prototype = {
	/**
	 * Inicializa el player cn la configuración pasada como parametro
	 */
	init: function(opciones, video) {
		var rutaConfig = null;
		
		// Intentamos calcular el portal desde el que se carga la libreria
		var portal = this.portal;
		if (!this.portal) {
			portal = this.portal = this.getPortal(opciones);
		}
		
		var config = null;
		
		if (opciones) {
			config = opciones.config || portal;
		}
		
		if (!this.rutaConfig) {
			var extension = PlayerWebTV.getExtension(video);
			var rutaConfig;
			if (extension == 'mp3') {
				rutaConfig = "config-por-defecto-audio.xml";
				if (config) {
					rutaConfig = "config-" + config + "-audio.xml";
				}
			}
			else {
				rutaConfig = "config-por-defecto.xml";
				if (config) {
					rutaConfig = "config-" + config + ".xml";
				}
			}			
			
			this.rutaConfig = this.getURLBase("config/" + rutaConfig);
		}
		
		if (!this.mosca) {
			// Mosca
			this.mosca = {
				url: "",
				ancho: -1,
				alto: -1,
				img: null
			};
		}
	
		if (config) {
			if (!this.mosca.img) {
				this.mosca.img = new Image();
				var urlMosca = this.getURLBase("imagenes/" + config + "/mosca.png");
				this.mosca.img.src = this.mosca.url = urlMosca;
				var moscaImg = this.mosca.img;
				
				var _this = this;
				if (moscaImg.complete) {
					_this.cargarConfigMosca(moscaImg);
				} else {
					if (!moscaImg.onload) {
						moscaImg.onload = function() {
							_this.cargarConfigMosca(moscaImg);
						}
						moscaImg.onabort = moscaImg.onerror = function() {
							_this.initted = true;
						}
					}
				}
			}
		} else {
			this.initted = true;
		}
		
		return this.initted;
	},
	
	cargarConfigMosca : function(logo) {
		this.mosca.ancho = parseInt(logo.width, 10);
		this.mosca.alto = parseInt(logo.height, 10);
		
		this.initted = true;
	},
	
	calculaMosca: function(ancho, alto) {
		try {
			var config = this.mosca;
			var mosca = "mosca.png";
			var iAncho = parseInt(ancho, 10);
			var iAlto = parseInt(alto, 10);
			
			var altoMosca = config.alto;
			var anchoMosca = config.ancho;
			
			if ((iAncho * 0.5) < anchoMosca || (iAlto * 0.3) < altoMosca) {
				mosca = "mosca-small.png";
			}
			
			if (iAncho < this.MIN_ANCHO_PLAYER || iAlto < this.MIN_ALTO_PLAYER) {
				mosca = "";
			}
			
			if (mosca) {
				return config.url.substring(0, config.url.lastIndexOf("/") + 1) + mosca;
			} else {
				return "";
			}
		} catch (e) {
			return "";
		}
	},
	/*
	utmac	UA-6773806-3
	utmcc	__utma=65922302.2025355597012597800.1252482418.1253875116.1255016623.18;+__utmz=65922302.1253699542.12.2.utmcsr=212.81.129.25:8281|utmccn=(referral)|utmcmd=referral|utmcct=/index.asp;
	utmcs	UTF-8
	utmdt	ABC WEB TV
	utme	5(video*Video servido*abctv._gente.en-abctv.Indios y Vaqueros: Alondra Bentley)
	utmfl	10.0 r32
	utmhid	1273621659
	utmhn	www.abctv.es
	utmje	0
	utmn	343073796
	utmp	/
	utmr	-
	utmsc	32-bit
	utmsr	1280x800
	utmt	event
	utmul	es-es
	utmwv	4.3as
	 */
	setValoresGoogleAnalytics : function(fo, opciones) {
		var categorias = this.getCategoriasGoogleAnalytics(opciones);
		var result = [];
		result.push("channel::" + categorias[0]);
		result.push("subChannel::" + categorias[1]);
		fo.addVariable("googleAnalytics", result.join(","));
	},
		
	getCategoriasGoogleAnalytics : function(opciones) {
		var categoria = "";
		var subcategoria = "";
		
		try {
			if (this.esDominioConocido()) {
				var url = location.pathname;
				var partes = url.split("/");
				
				// eliminamos la 1ª pq siempre llega vacia
				partes.splice(0, 1);
				
				if (partes[partes.length - 1] == "") {
					// comprobamos si la ultima partes es vacia
					partes.splice(partes.length - 1, 1);
				}
				
				if (partes.length > 0) {
					if (/^\d{8}/.test(partes[0])) {
						// la 1ª componente es 1 fecha, luego es un detalle de noticia
						// la eliminamos
						partes.splice(0, 1);
					}
				}
				if (partes.length > 0) {
					if (partes[partes.length - 1].indexOf(".") != -1) {
						if (partes[partes.length - 1].indexOf(".asp") != -1) {
							// si acaba en asp es una portada de ABC, la preparamos para intentar sacar luego la subcategoria
							var paginaTemp = partes[partes.length - 1];
							partes[partes.length - 1] = paginaTemp.replace(/\.asp/gi, "");
						} else {
							// es una página html, asp...
							// lo eliminamos
							partes.splice(partes.length - 1, 1);
						}
					}
				}
				
				if (partes.length == 0) {
					categoria = "portada";
				} else if (partes.length == 1) {
					if(this.cleanURL(partes[0])=="alava" || this.cleanURL(partes[0])=="almeria" || this.cleanURL(partes[0])=="jaen" || this.cleanURL(partes[0])=="albacete" || this.cleanURL(partes[0])=="alicante" || this.cleanURL(partes[0])=="jerez")
						categoria = "portada";
					else
						categoria = this.cleanURL(partes[0]);
				} else {
					// tenemos mas de 2 porciones de url, las cogemos como categoria y subcategoria
					categoria = this.cleanURL(partes[0]);
					if(/^\d{8}/.test(partes[1])){
						subcategoria = this.cleanURL(partes[2]);
					}
					else{
						subcategoria = this.cleanURL(partes[1]);
						if (this.cleanURL(partes[2]))
							subcategoria+= "/" +this.cleanURL(partes[2]);
					}
				}
			} else {
				var url = location.href;
				var partesURL = url.split("/");
				var pagina = partesURL[partesURL.length - 1];
				if (/\.(.)+$/.test(pagina)) {
					subcategoria = partesURL.splice(partesURL.length - 1, 1);
					categoria = partesURL.join("/");
				} else {
					categoria = url;
				}
			}
		} catch (e) {
		}
		
		return [categoria, subcategoria];
	},
	
	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;
	},

	// zoneid:126,CAT_gente,SCATen-abctv,PORabctv,indios-vaqueros-alondra-bentley-54441
	/**
	 * Las zonas se cargaran de la configuracion, asi como el portal o site
	 */
	/*setValoresAdvernet: function(fo, opciones) {
		var result = [];
		
		var tags = null;
		if (opciones) {
			tags = opciones.tags || this.getKeyWords(opciones.titulo) || "";
		}
		if (tags) {
			tags = tags.replace(/[, ]/g, "-");
			result.push("tags::" + tags);
		}
		var categoria = undefined;
		var subcategoria = undefined;
		if (opciones) {
			categoria = opciones.categoriaPubli || undefined;
			subcategoria = opciones.subcategoriaPubli || undefined;
		}
		result.push("channel::" + categoria);
		result.push("subChannel::" + subcategoria);
		
		fo.addVariable("advernet", result.join(","));
	},*/
	
	_showVideo : function(id, video, w, h, opciones) {
		var funcion = this._showVideo;
		
		if (arguments.length < 5) {
			// Si no nos pasan un id de capa, creamos 1 en la posicion actual y la usamos para escribir el video
			// (CUIDADO!  Si la pagina ya esta cargada, siempre hay que indicar un id, sino borraria la pagina actual)
			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 = {};
		}
		
		// Esperamos que se cargue la imagen de mosca para poder calcular cual de las dos mostrar
		// si la pequeña o la normal o ninguna
		if (!this.init(opciones, video)) {
			var _this = this;
			setTimeout(function() {
				funcion.call(_this, id, video, w, h, opciones);
			}, 500);
			return;
		}
		
		// con esto conseguimos ids unicos
		var idPlayer = this.getUID("movie_player");
		var fo = new SWFObject(this.getURLBase("FLVPlayer.swf"), idPlayer, w, h, this.VERSION_FLASH, getColorFondo());
	
		// transparencia
		fo.addParam("wmode", "transparent");
		
		fo.addParam("swLiveConnect", "true");
		fo.addParam("allowScriptAccess", "always");
	
		// ruta del fichero de configuracion
		if (this.rutaConfig) {
			fo.addVariable("config", this.rutaConfig);
		}
		
		// URL del video
		if (video.indexOf('youtube.com') != -1) {
			var idYoutube = video.substring(video.indexOf('=')+1, video.length);
			fo.addVariable("file", idYoutube);
			fo.addVariable("cdn", "youtube");
		}
		else {
			fo.addVariable("file", video);
		}
		
		//comprueba si es live
		if ( (video.indexOf('rtmp://') != -1) || (video.indexOf('rtmpt://') != -1) ) {
			fo.addVariable("isLive", "true");
		}
		
		// alto y ancho
		fo.addVariable("width", parseInt(w, 10));
		fo.addVariable("height", parseInt(h, 10));
		
		// google analytics
		this.setValoresGoogleAnalytics(fo, opciones);
		
		// advernet
		//this.setValoresAdvernet(fo, opciones);
		
		//DART
		if (typeof (OAS_sitepage) != 'undefined'){
			fo.addVariable("advertisement","OAS_sitepage::" + getOAS_sitepage(OAS_sitepage));
		}else{
			fo.addVariable("advertisement","OAS_sitepage::");
		}
		
		if (opciones) {
			if (!opciones.titulo) {
				opciones.titulo = "Desconocido";
			}
			opciones.titulo = this.getCleanTitle(opciones.titulo);
			
			// pantalla completa
			if (opciones.fullscreen !== false) {
				fo.addParam("allowfullscreen", "true");
			}
			
			// imagen de previa
			if (opciones.imgPrevia) {
				var imagen = this.getURLResizer(opciones.imgPrevia, w, h);
				imagen = imagen.replace(/&/g,"%26");
				fo.addVariable("image", imagen);
			}			
			if (opciones.autoplay) {
				fo.addVariable("autostart", "true");
			}
			
			// mosca
			var mosca = this.calculaMosca(w, h);
			if (mosca) {
				fo.addVariable("logo", "image::" + mosca);
			}
			
			// ajustar
			if (opciones.ajustar === true) {
				fo.addVariable("overstretch", "overstretch");
			} else if (opciones.ajustar === false) {
				fo.addVariable("overstretch", "maintain");
			} else if (opciones.ajustar) {
				fo.addVariable("overstretch", opciones.ajustar);
			} else {
				fo.addVariable("overstretch", "maintain");
			}
			
			// titulo del video
			if (opciones.titulo) {
				fo.addVariable("title", opciones.titulo);
			}
		} else {
			// Si no nos llega configuracion
			fo.addParam("allowfullscreen", "true");
			fo.addVariable("autostart", "false");
			fo.addVariable("overstretch", "maintain");
		}
	
		if (navigator && navigator.appName && navigator.appName == "Microsoft Internet Explorer") {
			setTimeout(function() {
				var contenedor = document.getElementById(id);
				if (contenedor) {
					contenedor.innerHTML = '<div style="text-align: center; margin:0 auto; position: relative"></div>';
					fo.write(contenedor.firstChild);
				}
				PlayerWebTV.ieCounter--;
			}, 500 * PlayerWebTV.ieCounter++);
		} else {
			var contenedor = document.getElementById(id);
			if (contenedor) {
				contenedor.innerHTML = '<div style="text-align: center; margin:0 auto; position: relative"></div>';
				fo.write(contenedor.firstChild);
			}
		}
	},
	
	_showAudio : function(id, video, w, h, opciones) {
		var funcion = this._showAudio;
		
		if (arguments.length < 5) {
			// Si no nos pasan un id de capa, creamos 1 en la posicion actual y la usamos para escribir el video
			// (CUIDADO!  Si la pagina ya esta cargada, siempre hay que indicar un id, sino borraria la pagina actual)
			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 = {};
		}
		
		// Esperamos que se cargue la imagen de mosca para poder calcular cual de las dos mostrar
		// si la pequeña o la normal o ninguna
		if (!this.init(opciones, video)) {
			var _this = this;
			setTimeout(function() {
				funcion.call(_this, id, video, w, h, opciones);
			}, 500);
			return;
		}
		
		// con esto conseguimos ids unicos
		var idPlayer = this.getUID("movie_player");
	
		var fo = new SWFObject(this.getURLBase("FLVPlayer.swf"), idPlayer, w, h,this.VERSION_FLASH, getColorFondo());
	
		// transparencia
		fo.addParam("wmode", "transparent");
		
		fo.addParam("swLiveConnect", "true");
		fo.addParam("allowScriptAccess", "always");
	
		// ruta del fichero de configuracion
		if (this.rutaConfig) {
			fo.addVariable("config", this.rutaConfig);
		}
		
		// URL del audio
		fo.addVariable("file", video);
		
		// alto y ancho
		fo.addVariable("width", parseInt(w, 10));
		fo.addVariable("height", parseInt(h, 10));
		
		// google analytics
		//this.setValoresGoogleAnalytics(fo, opciones);
		
		// advernet
		//this.setValoresAdvernet(fo, opciones);
		
		if (opciones) {
			if (!opciones.titulo) {
				opciones.titulo = "Desconocido";
			}
			opciones.titulo = this.getCleanTitle(opciones.titulo);
			
			// pantalla completa
			if (opciones.fullscreen !== false) {
				fo.addParam("allowfullscreen", "true");
			}
			
			// imagen de previa
			if (opciones.imgPrevia) {
				//fo.addVariable("image", this.getURLResizer(opciones.imgPrevia, w, h));
				if (w <= 253) var ancho =  253;
				else if (w > 253 && w <= 300) var ancho =  300;
				else if (w > 300 && w <= 384) var ancho =  384;
				else if (w > 384 && w <= 390) var ancho =  390;
				else if (w > 390 && w <= 665) var ancho =  665;
				var imagen = this.getURLResizer(opciones.imgPrevia, w, h, 'audio-onda_' + ancho + '.png');
				imagen = imagen.replace(/&/g,"%26");
				fo.addVariable("image", imagen);
			}
			
			if (opciones.autoplay) {
				fo.addVariable("autostart", "true");
			}
			
			// mosca
			//var mosca = this.calculaMosca(w, h);
			//if (mosca) {
			//	fo.addVariable("logo", "image::" + mosca);
			//}
			
			// ajustar
			if (opciones.ajustar === true) {
				fo.addVariable("overstretch", "overstretch");
			} else if (opciones.ajustar === false) {
				fo.addVariable("overstretch", "maintain");
			} else if (opciones.ajustar) {
				fo.addVariable("overstretch", opciones.ajustar);
			} else {
				fo.addVariable("overstretch", "maintain");
			}
			
			// titulo del video
			if (opciones.titulo) {
				fo.addVariable("title", opciones.titulo);
			}
		} else {
			// Si no nos llega configuracion
			fo.addParam("allowfullscreen", "true");
			fo.addVariable("autostart", "false");
			fo.addVariable("overstretch", "maintain");
		}
	
		if (navigator && navigator.appName && navigator.appName == "Microsoft Internet Explorer") {
			setTimeout(function() {
				var contenedor = document.getElementById(id);
				if (contenedor) {
					contenedor.innerHTML = '<div style="text-align: center;"></div>';
					fo.write(contenedor.firstChild);
				}
				PlayerWebTV.ieCounter--;
			}, 500 * PlayerWebTV.ieCounter++);
		} else {
			var contenedor = document.getElementById(id);
			if (contenedor) {
				contenedor.innerHTML = '<div style="text-align: center;"></div>';
				fo.write(contenedor.firstChild);
			}
		}
	},	
	
	showVideo: function(id, video, w, h, opciones) {
		var extension = PlayerWebTV.getExtension(video);
		
		var funcion = this.showVideo;
		if (arguments.length < 5) {
			// Si no nos pasan un id de capa, creamos 1 en la posicion actual y la usamos para escribir el video
			// (CUIDADO!  Si la pagina ya esta cargada, siempre hay que indicar un id, sino borraria la pagina actual)
			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) {
				if (extension == 'mp3') {
					var marcaAgua = 'audio-play.png';
				}
				else {
					var marcaAgua = 'play.png';
				}
				
				var urlPreviaRedimensionada = this.getURLResizer(opciones.imgPrevia, w, h, marcaAgua);
				this.pintarImagen(id, video, w, h, opciones, urlPreviaRedimensionada);
			} else {
				this.pintarImagen(id, video, w, h, opciones, null);
			}
		}
	},
	
	// Pinta los videos de BC para que se visualicen en una capa modal
	showVideoBC: function(div, video, w, h, opciones) {
		var funcion = this.showVideoBC;
		if(this.portal == null )this.portal = opciones.site;
		var idComentarios = div.substring(div.indexOf('-')+1, div.lastIndexOf('-'));
		var idPlayer = PlayerWebTV.INFO_PORTALES[opciones.site].idPlayer;
		if ((opciones.publicidadOn != undefined) && !opciones.publicidadOn) idPlayer = PlayerWebTV.INFO_PORTALES[opciones.site].idPlayerSinPublicidad;
		var idPublisher = PlayerWebTV.INFO_PORTALES[opciones.site].idPublisher;
		var bComentarios = false;
		var sVideoStillURL = "";
		var sIdVideo = "";
		var sPie = opciones.titulo;
		var sEntradilla = opciones.entradilla;
		var sEnlace = opciones.urlTitulo;
		var bVideoObtenido = (arguments.length > 5)?arguments[5]:false;
		
		// Ancho y alto por defecto para la capa modal
		var iWidth=640;
		var iHeight=360;
		if ((opciones.capaModal != undefined) && (opciones.capaModal == false)) {
			// Si no abrimos en capa modal cogemos el alto y ancho definido por el usuario
			iWidth = w;
			iHeight = h;
		}
		
		var adTags = null;
		var sAutor = "";
		var iIdModal = video +'-_-'+this.getUID("");
		// Si el video es de RC nos quedamos con la parte sin 'rc@'
		var iIdModalSinRC = ((iIdModal.toLowerCase().indexOf('rc@')!=-1)?iIdModal.substring(iIdModal.indexOf('@')+1):iIdModal);
		var sURLDataBC = '';
		if(isNaN(video)) {
			if(video.toLowerCase().indexOf('rc@') != -1) video = video.substring(video.indexOf('@')+1);
			sURLDataBC = '/includes/manuales/webtv/phpproxy/phpproxy.php?medio='+ PlayerWebTV.INFO_PORTALES[opciones.site].medio +'&command=find_video_by_reference_id&video_fields=id,name,longDescription,linkURL,videoStillURL,tags&custom_fields=origin&reference_id='+video;
		} else { // Si es video del propio portal lo buscamos por ID
			sURLDataBC = '/includes/manuales/webtv/phpproxy/phpproxy.php?medio='+ PlayerWebTV.INFO_PORTALES[opciones.site].medio +'&command=find_video_by_id&video_fields=id,name,longDescription,linkURL,videoStillURL,tags&custom_fields=origin&video_id='+video;
		}
		/*if(video.toLowerCase().indexOf('rc@') != -1) { // Si es video de RC buscamos por reference iD
			sURLDataBC = '/includes/manuales/webtv/phpproxy/phpproxy.php?medio='+ PlayerWebTV.INFO_PORTALES[opciones.site].medio +'&command=find_video_by_reference_id&video_fields=id,name,longDescription,linkURL,videoStillURL,tags&custom_fields=origin&reference_id='+video.substring(video.indexOf('@')+1);
		} else { // Si es video del propio portal lo buscamos por ID
			sURLDataBC = '/includes/manuales/webtv/phpproxy/phpproxy.php?medio='+ PlayerWebTV.INFO_PORTALES[opciones.site].medio +'&command=find_video_by_id&video_fields=id,name,longDescription,linkURL,videoStillURL,tags&custom_fields=origin&video_id='+video;
		}*/
		if(getXMLHttpRequest()){
			$.ajax({
				url: sURLDataBC,
				dataType: 'json',
				data: null,
				async: false,
				success: function(data) {
					if (data != null ) {
						// Nos quedamos con el ID del por si lo que tenemos es el ID de referenci
						if (data.id!=null && sIdVideo=='') sIdVideo = data.id;  
						//...
						if (data.name!=null && sPie=='') sPie = data.name;
						if (data.longDescription!=null && sEntradilla=='')sEntradilla=data.longDescription;	  
						if (data.linkURL!=null && sEnlace=='') sEnlace = data.linkURL;
						if (data.videoStillURL!=null) sVideoStillURL = data.videoStillURL;
						if (data.tags!=null) adTags = data.tags;
						if (data.customFields!=null) if(data.customFields.origin!=null)sAutor = data.customFields.origin;
						bVideoObtenido = true;
					}
				}
			});
		}
		
		/*
		 * Caso para noticias compartidas de la verdad a las provincias y viceversa
		 */
		if( !bVideoObtenido && ( this.portal == 'laverdad' || this.portal == 'lasprovincias' ) ) {
			var opcionesOpcional = {
				categoriaPubli: ((opciones.categoriaPubli==undefined)?'':opciones.categoriaPubli),
				titulo: ((opciones.titulo==undefined)?'':opciones.titulo),
				imgPrevia: ((opciones.imgPrevia==undefined)?'':opciones.imgPrevia),
				site: ((this.portal=='laverdad')?'lasprovincias':'laverdad'),
				entradilla: ((opciones.entradilla==undefined)?'':opciones.entradilla),
				urlTitulo: ((opciones.urlTitulo==undefined)?'':opciones.urlTitulo),
				imgPatrocinio: ((opciones.imgPatrocinio==undefined)?'':opciones.imgPatrocinio),
				urlPatrocinio: ((opciones.urlPatrocinio==undefined)?'':opciones.urlPatrocinio),
				clickcommand: ((opciones.clickcommand==undefined)?'':opciones.clickcommand),
				capaModal: ((opciones.capaModal == undefined)?true:opciones.capaModal),
				publicidadOn: ((opciones.publicidadOn == undefined)?true:opciones.publicidadOn),
				redesSociales: (opciones.redesSociales == undefined) ? true : opciones.redesSociales
			};
			(this.portal=='laverdad')?this.portal='lasprovincias':this.portal='laverdad';
			funcion.call(this, arguments[0], arguments[1], arguments[2], arguments[3], opcionesOpcional, true);
			return;
		}
		/*
		 * FIN CASO LAVERDAD Y LASPROVINCIAS
		 */
			
		

		
		//if(opciones.imgPrevia == "" && isVideoBC(video)) opciones.imgPrevia = sVideoStillURL;
		if(opciones.imgPrevia == "") opciones.imgPrevia = sVideoStillURL;
		var contenedor = document.getElementById(div);
		
		if (contenedor) {
			if (opciones && opciones.imgPrevia) {
				var marcaAgua = 'bt-video.gif';
				if(opciones.imgPrevia.indexOf("resizer.php")!= -1){
					opciones.imgPrevia = opciones.imgPrevia.substring(opciones.imgPrevia.indexOf('imagen=')+7, opciones.imgPrevia.indexOf('.jpg')+4);
				} 
				var urlPreviaRedimensionada = this.getURLResizer(opciones.imgPrevia, w, h, marcaAgua);
				this.pintarImagen(div, iIdModal, w, h, opciones, urlPreviaRedimensionada);
			} else {
				this.pintarImagen(div, iIdModal, w, h, opciones, null);
			}
			var divVars = document.createElement('div');
			divVars.setAttribute('id', 'photo-'+iIdModalSinRC+'-modal-2');
			var divCod = document.createElement('div');
			divCod.setAttribute('class', 'player-modal');
			divCod.setAttribute('id', 'photo-'+iIdModalSinRC+'-modal');
			contenedor.parentNode.appendChild(divVars);
			contenedor.parentNode.appendChild(divCod);
		}
		$('#photo-'+iIdModalSinRC+'-modal-2').attr('style', 'display: none');
		$('#photo-'+iIdModalSinRC+'-modal').attr('style', 'display: none');
				
		//Vemos si el tag del video tiene algún patrocinio asociado
		if(opciones.imgPatrocinio=='' || opciones.urlPatrocinio=='') {
			var hayPatrocinio = false;
			var numTags = (adTags != null)?adTags.length:0;
			for(var i=0;!hayPatrocinio && i < numTags; i++) {
				if(getDatosTagPatrocinado(opciones.site, adTags[i]) != null){
					opciones.imgPatrocinio = getDatosTagPatrocinado(opciones.site, adTags[i]).imgPatrocinio;
					opciones.urlPatrocinio = getDatosTagPatrocinado(opciones.site, adTags[i]).urlPatrocinio;
					opciones.clickcommand = '';//getDatosTagPatrocinado(opciones.site, adTags[i]).clickcommand;
					hayPatrocinio = true;
				}
			}
		}
		
		//Obtenemos el código del video
		sPie = sPie.replace(/"/g, "'");
		sPie = sPie.replace(/'/g, "\'");
		sEntradilla = sEntradilla.replace(/"/g, "'");
		sEntradilla = sEntradilla.replace(/'/g, "\'");
		var vars = "idVideo="+sIdVideo+"#;#w="+iWidth+"#;#h="+iHeight+"#;#idPlayer="+idPlayer+"#;#url="+sEnlace+"#;#pie="+sPie+"#;#entradilla="+sEntradilla+"#;#comentarios="+idComentarios+"#;#idDiv="+iIdModalSinRC+"#;#imgPatrocinio="+opciones.imgPatrocinio+"#;#urlPatrocinio="+opciones.urlPatrocinio+"#;#clickcommand="+opciones.clickcommand+"#;#site="+opciones.site+"#;#rSociales="+opciones.redesSociales+"#;#autor="+sAutor;
		
		var variables = document.createTextNode(vars);
		document.getElementById("photo-"+iIdModalSinRC+"-modal-2").appendChild(variables);
	},
	
	pintarImagen: function(id, video, w, h, opciones, urlImgPrevia, imgPrevia) {
		var videoBC = '';
		if(video.indexOf('-_-') != -1) {
			videoBC = video.split('-_-');
		}
		var extension = 'mp4';
		//if(videoBC=='' || !isVideoBC(videoBC[0])) {
		if(videoBC=='') {
			extension = PlayerWebTV.getExtension(video);
		}
		
		var _this = this;
		var funcion = this.pintarImagen;
		
		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];
			
			opciones.autoplay = true;
			
			var accion = function() {
				if (extension == 'mp3') {
					_this._showAudio(id, video, w, h, opciones);
					this.onclick = _this.nada;
				}
				else {
					_this._showVideo(id, video, w, h, opciones);
					this.onclick = _this.nada;
				}
			};
			
			var estrategia = "MarcaAguaEncajar";
			switch (estrategia) {
				case "SinMarcaAguaPosicionado":
					// Version con play posicionado (problemas con IE6)
					this.getHTMLImagenPosicion(ancho, alto, tamIcono, imgPrevia, contenedor, accion, extension);
				break;
				case "MarcaAguaAncho100AltoProporcional":
					// Version con ancho 100% y alto proporcional
					this.getHTMLImagenMarcaAguaAltoProporcional(ancho, alto, tamIcono, imgPrevia, contenedor, accion, extension);
				break;
				case "MarcaAguaEncajar":
				default:
					// Version con marca de agua e imagen centrada horizontal y verticalmente
					//if(isVideoBC(videoBC[0])) {
						//this.getHTMLImagenMarcaAguaBC(PlayerWebTV.INFO_PORTALES[opciones.site].resizer,PlayerWebTV.INFO_PORTALES[opciones.site].medio,ancho, alto, tamIcono, imgPrevia, id, video, opciones.capaModal);
					//} else {
						//this.getHTMLImagenMarcaAgua(ancho, alto, tamIcono, imgPrevia, contenedor, accion, extension);
					//}
					if ((video.indexOf('http://cache1.agilecontents.com')!= -1) || (extension == 'mp3')) {
						this.getHTMLImagenMarcaAgua(ancho, alto, tamIcono, imgPrevia, contenedor, accion, extension);
					} else {
						this.getHTMLImagenMarcaAguaBC(PlayerWebTV.INFO_PORTALES[opciones.site].resizer,PlayerWebTV.INFO_PORTALES[opciones.site].medio,ancho, alto, tamIcono, imgPrevia, id, video, opciones.capaModal);

					}
				break;
			}
		}
	},
	
	// Version con play posicionado (problemas con IE6)
	getHTMLImagenPosicion: function(ancho, alto, tamIcono, imgPrevia, contenedor, accion, extension) {
		if (extension == 'mp3') {
			var textoAlt = 'Pulse para escuchar el audio';
			var imagenPlay = 'imagenes/audio-play.png';
		}
		else {
			var textoAlt = 'Pulse para ver el video';
			var imagenPlay = 'imagenes/play.png';
		}
		
		var styleIcono = "margin-left: " + (ancho/2 - tamIcono[0]/2) + "px; top: " + (alto/2 - tamIcono[1]/2) + "px;";
		var html = '<div style="text-align: center; margin:0 auto; position: relative;"><div style="position: relative; margin:0 auto;cursor: pointer; background-color: ' + getColorFondo() + '; width: ' + ancho + 'px; height: ' + alto + 'px; position: relative; z-index:0;">';
		html += '<img src="' + this.getURLBase(imagenPlay) + '" alt="' + textoAlt + '" title="' + textoAlt + '" style="margin:0 auto; text-align:center; border: 0; position: absolute; z-index: 101; ' + styleIcono + '" />';
		if (imgPrevia && (imgPrevia.width + imgPrevia.height) > 0) {
			var style = "";
			var proporcionPlayer = ancho / alto;
			var proporcionImagen = imgPrevia.width / imgPrevia.height;
			
			var altoFinal = imgPrevia.height;
			var anchoFinal = imgPrevia.width;
			
			if (proporcionPlayer > proporcionImagen) {
				anchoFinal = anchoFinal * alto / altoFinal;
				altoFinal = alto;
			} else {
				altoFinal = altoFinal * ancho / anchoFinal;
				anchoFinal = ancho;
			}
			// centramos la imagen
			var coords = [(ancho - anchoFinal) / 2, (alto - altoFinal) / 2];
			var style = "height: " + altoFinal + "px; width: " + anchoFinal + "px; position: absolute; z-index: 100; top: " + coords[1] + "px; left: " + coords[0] + "px;";
			
			html += '<img src="' + imgPrevia.src + '" alt="' + textoAlt + '" title="' + textoAlt + '" style="border: 0; margin:0 auto; text-align:center;' + style + '" />';
		} else {
			html += '<img src="' + this.getURLBase(imagenPlay) + '" alt="' + textoAlt + '" title="' + textoAlt + '" style="margin:0 auto; text-align:center; border: 0; margin-top: ' + ((alto - tamIcono[1]) / 2) + 'px;" />';
		}
		if (extension == 'mp3') {
			html += '<div class="link-app2a"><div class="related-link"><a><img src="/img/bt-audio.gif">AUDIO</a><span class="rltrans"></span></div></div></div></div>';
		}else{
			html += '<div class="link-app2a"><div class="related-link"><a><img src="/img/bt-video.gif">VÍDEO</a><span class="rltrans"></span></div></div></div></div>';
		}
		
		contenedor.innerHTML = html;
		contenedor.firstChild.firstChild.onclick = accion;
	},
	
	// Version con marca de agua e imagen centrada horizontal y verticalmente
	getHTMLImagenMarcaAgua: function(ancho, alto, tamIcono, imgPrevia, contenedor, accion, extension) {

		if (extension == 'mp3') {
			var textoAlt = 'Pulse para escuchar el audio';
			var imagenPlay = 'imagenes/audio-play.png';
		}
		else {
			var textoAlt = 'Pulse para ver el video';
			var imagenPlay = 'imagenes/play.png';
		}
		
		var html = '<div style="text-align: center; margin:0 auto; position: relative;"><div style="margin:0 auto;cursor: pointer; background-color: ' + getColorFondo() + '; width: ' + ancho + 'px; height: ' + alto + 'px; position: relative; z-index:0;">';
		if (imgPrevia && (imgPrevia.width + imgPrevia.height) > 0) {
			var style = "";
			var proporcionPlayer = ancho / alto;
			var proporcionImagen = imgPrevia.width / imgPrevia.height;
			
			var altoFinal = imgPrevia.height;
			var anchoFinal = imgPrevia.width;
			
			if (proporcionPlayer > proporcionImagen) {
				anchoFinal = anchoFinal * alto / altoFinal;
				altoFinal = alto;
			} else {
				altoFinal = altoFinal * ancho / anchoFinal;
				anchoFinal = ancho;
			}
			// centramos la imagen
			var coords = [(ancho - anchoFinal) / 2, (alto - altoFinal) / 2];
			var style = "height: " + altoFinal + "px; width: " + anchoFinal + "px; margin-top: " + coords[1] + "px;";
			
			html += '<img src="' + imgPrevia.src + '" alt="' + textoAlt + '" title="' + textoAlt + '" style="margin:0 auto; text-align:center; border: 0; ' + style + '" />';
		} else {
			html += '<img src="' + this.getURLBase(imagenPlay) + '" alt="' + textoAlt + '" title="' + textoAlt + '" style="margin:0 auto; text-align:center; border: 0; margin-top: ' + ((alto - tamIcono[1]) / 2) + 'px;" />';
		}
		if (extension == 'mp3') {
			html += '<div class="link-app2a"><div class="related-link"><a><img src="/img/bt-audio.gif">AUDIO</a><span class="rltrans"></span></div></div></div></div>';
		}else{
			html += '<div class="link-app2a"><div class="related-link"><a><img src="/img/bt-video.gif">VÍDEO</a><span class="rltrans"></span></div></div></div></div>';
		}
		
		contenedor.innerHTML = html;
		var first = contenedor.firstChild.firstChild;
		if(first){
			contenedor.firstChild.firstChild.onclick = accion;
		}else
		{
			contenedor.firstChild.onclick = accion;
		}
	},
	
	// Version con marca de agua e imagen centrada horizontal y verticalmente
	
	getHTMLImagenMarcaAguaBC: function(site,medio,ancho, alto, tamIcono, imgPrevia, div, video, capaModal) {
		var textoAlt = 'Pulse para ver el video';
		var imagenPlay = 'imagenes/play.png';
		var jsPlay = '';
		// Nos quedamos con la parte buena del video sin 'rc@'
		var videoSinRC = ((video.toLowerCase().indexOf('rc@')!=-1)?video.substring(video.indexOf('@')+1):video);
		if(capaModal)
			jsPlay = 'javascript:openModal("'+site+'","'+medio+'","'+videoSinRC+'")';
		else
			jsPlay = 'javascript:openVideoDiferido("'+site+'","'+medio+'","'+videoSinRC+'", "'+div+'")';
		
		//Modificado por Diego ;-)
		//Abrimos el modal en el enlace de noticia
		//alert(jsPlay);
		$('.enlace_' + div).attr('href', jsPlay);
		
		// creamos el DOM
		var divExterno = "externo_"+PlayerWebTV.getUID("");
		var divInterno = "interno_"+PlayerWebTV.getUID("");
		var divext = document.createElement("div");
		divext.setAttribute("id", divExterno);
		//divext.setAttribute("style", "text-align: center; margin:0 auto; position: relative;");
		var divint = document.createElement("div");
		divint.setAttribute("id", divInterno);
		//divint.setAttribute("style", "margin:0 auto;cursor: pointer; background-color:" + getColorFondo() + "; width: " + ancho + "px; height: " + alto + "px; position: relative; z-index:0;");
		divext.appendChild(divint);
		if (imgPrevia && (imgPrevia.width + imgPrevia.height) > 0) {
			var style = "";
			var proporcionPlayer = ancho / alto;
			var proporcionImagen = imgPrevia.width / imgPrevia.height;
			var altoFinal = imgPrevia.height;
			var anchoFinal = imgPrevia.width;
			if (proporcionPlayer > proporcionImagen) {
				anchoFinal = anchoFinal * alto / altoFinal;
				altoFinal = alto;
			} else {
				altoFinal = altoFinal * ancho / anchoFinal;
				anchoFinal = ancho;
			}
			// centramos la imagen
			var coords = [(ancho - anchoFinal) / 2, (alto - altoFinal) / 2];
			var style = "height: " + altoFinal + "px; width: " + anchoFinal + "px; margin-top: " + coords[1] + "px;";
			// continuamos creando el DOM
			var link = document.createElement("a");
			link.setAttribute("href", jsPlay);
			divint.appendChild(link);
			var img = document.createElement("img");
			img.setAttribute("src", imgPrevia.src);
			img.setAttribute("alt", textoAlt);
			img.setAttribute("title", textoAlt);
			var uidImagen = this.getUID("imagenVisor");
			img.setAttribute("id", uidImagen);
			link.appendChild(img);
			if(ancho>84&&alto>84)	{
				var capaVideo = divint.innerHTML;
				capaVideo += "<div class='link-app2a'><div class='related-link'><a href='"+jsPlay+"'><img src='http://www."+site+"/img/bt-video.gif'>VÍDEO</a><span class='rltrans'></span></div></div></div></div>";
				divint.innerHTML = capaVideo;
			}else{
				var styleplay = document.createElement("div");
				styleplay.setAttribute('style', 'right: 2pt; position: absolute; bottom:2pt; width:30px');
				var aplay = document.createElement("a");
				aplay.setAttribute("href", jsPlay);
				var imgplay = document.createElement("img");
				imgplay.setAttribute("src", "/img/bt-video.gif");
				aplay.appendChild(imgplay);
				styleplay.appendChild(aplay);
				divint.appendChild(styleplay);
			}
			document.getElementById(div).appendChild(divext);
			if(alto > altoFinal){
				$("#" + uidImagen).attr('style', 'width:' + anchoFinal +'px;height:' + altoFinal +'px;margin:0 auto; text-align:center; border: 0;margin-top: ' + coords[1] + 'px;');
			} else {
				$("#" + uidImagen).attr('style', 'width:' + anchoFinal +'px;height:' + altoFinal +'px;margin:0 auto; text-align:center; border: 0;');
			}
			$("#"+divExterno).attr('style', 'text-align: center; margin:0 auto; position: relative;');
			$("#"+divExterno).removeAttr('id');
			$("#"+divInterno).attr('style', 'margin:0 auto;cursor: pointer; background-color:' + getColorFondo() + '; width: ' + ancho + 'px; height: ' + alto + 'px; position: relative; z-index:0;');
			$("#"+divInterno).removeAttr('id');
		} else {
			var link = document.createElement("a");
			link.setAttribute("href", jsPlay);
			divint.appendChild(link);
			var img = document.createElement("img");
			img.setAttribute("src", this.getURLBase(imagenPlay));
			img.setAttribute("alt", textoAlt);
			img.setAttribute("title", textoAlt);
			img.setAttribute("style", "margin:0 auto; text-align:center; border: 0; margin-top:"+((alto - tamIcono[1]) / 2)+"px;");
			link.appendChild(img);
			document.getElementById(div).appendChild(divext);
		}
	},
	
	// Version con ancho 100% y alto proporcional
	getHTMLImagenMarcaAguaAltoProporcional: function(ancho, alto, tamIcono, imgPrevia, contenedor, accion, extension) {
		if (extension == 'mp3') {
			var textoAlt = 'Pulse para escuchar el audio';
			var imagenPlay = 'imagenes/audio-play.png';
		}
		else {
			var textoAlt = 'Pulse para ver el video';
			var imagenPlay = 'imagenes/play.png';
		}
		
		// Version con marca de agua e imagen ocupa todo el ancho y alto proporcional
		var html = '<div style="text-align: center; margin:0 auto; position: relative"><div style="margin:0 auto; background-color: ' + getColorFondo() + '; cursor: pointer; width: ' + ancho + 'px;">';
		if (imgPrevia && (imgPrevia.width + imgPrevia.height) > 0) {
			html += '<img src="' + imgPrevia.src + '" alt="' + textoAlt + '" title="' + textoAlt + '" style="margin:0 auto; text-align:center; border: 0 " />';
		} else {
			html += '<img src="' + this.getURLBase(imagenPlay) + '" alt="' + textoAlt + '" title="' + textoAlt + '" style="margin:0 auto; text-align:center; border: 0; margin-top: ' + ((alto - tamIcono[1]) / 2) + 'px;" />';
		}
		html += '</div></div>';
		
		contenedor.innerHTML = html;
		contenedor.firstChild.firstChild.onclick = accion;
	},
	
	/**
	 * Obtiene la URL completa para un recurso, según el portal especificado
	 */
	getURLBase: 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;
		}
	},
	
	/**
	 * Combierte URL's relativas al servidor en URL's absolutas.  Utilizado para el resizer
	 */
	getFullURL: function(src) {
		if (src.indexOf("//") == -1 && !(src.charAt(0) == "/")) {
			// la ruta es relativa a la pagina
			// src = "nivel2/imagen.png"
			var ruta = location.href.substring(0, location.href.lastIndexOf("/") + 1);
			src = ruta + src;
		} else if (src.charAt(0) == "/") {
			// la ruta de la imagen es relativa al servidor, concatenamos el servidor actual
			// src = "/carpeta/imagen.png"
			src = location.protocol + "//" + location.host + src;
		}
		return src;
	},
	
	/**
	 * Devuelve la URL para pedir al resizer la nueva imagen
	 */
	getURLResizer: function(src, ancho, alto, marcaAgua) {
		var result = this.getFullURL(src);
		
		if (this.portal) {
			var medio = "";
			var medio = this.INFO_PORTALES[this.portal].resizer;
			
			if (!medio) {
				medio = this.portal + ".es";
			}
			
			if (!isDesarrolloABC()) {
				if (marcaAgua) {
					result = "http://resizer." + medio + "/resizer/resizer.php?imagen=" + result + "&nuevoancho=" + ancho + "&nuevoalto=" + alto + "&copyright=false&encrypt=false&posmarca=C&transparencia=85";
				}  else {
					result = "http://resizer." + medio + "/resizer/resizer.php?imagen=" + result + "&nuevoancho=" + ancho + "&nuevoalto=" + alto + "&copyright=conCopyright&encrypt=false";
				}
			}
		}
		
		return result;
	}
};

/**
 * Incluimos las propiedades estaticas en el prototipo
 */
(function() {
	var prototipo = PlayerWebTV.prototype;
	for (var prop in PlayerWebTV) {
		if (prop != "prototype") {
			prototipo[prop] = PlayerWebTV[prop];
		}
	}
})();

/**
* Funciones para la capa modal del video de directo
*/
function openModal(site,medio,id, video) {
	var simpleModalJS = '/js/jquery.simplemodal.js';
	var idComent = "";
	if(arguments.length == 2){ // Si es video en directo
		video = medio;
		id = site;
		var obj = cambiaAutoStart(video);
		obj = cambiaAltoAncho(obj);
		$("#capaVideo_"+id).html(unescape(obj));
		getIdWMPlayer(obj);
	} else { // Si es un video de BC normal
		var txt = $("#photo-"+id+"-modal-2").text();
		var variables = txt.split('#;#');
		var obj = getVideoObject(site,
								 medio,
							     variables[0].substring(variables[0].indexOf('=')+1),
								 variables[1].substring(variables[1].indexOf('=')+1),
								 variables[2].substring(variables[2].indexOf('=')+1),
								 variables[3].substring(variables[3].indexOf('=')+1),
								 variables[4].substring(variables[4].indexOf('=')+1),
								 variables[5].substring(variables[5].indexOf('=')+1),
								 variables[6].substring(variables[6].indexOf('=')+1),
								 variables[7].substring(variables[7].indexOf('=')+1),
								 variables[8].substring(variables[8].indexOf('=')+1),
								 variables[9].substring(variables[9].indexOf('=')+1),
								 variables[10].substring(variables[10].indexOf('=')+1),
								 variables[11].substring(variables[11].indexOf('=')+1),
								 variables[13].substring(variables[13].indexOf('=')+1),
								 variables[14].substring(variables[14].indexOf('=')+1));
		var site = variables[12].substring(variables[12].indexOf('=')+1);
		if( site = 'laverdad' || site == 'lasprovincias' ) { // Caso que las provincias publique para la verdad y viceversa
			var dominio = PlayerWebTV.INFO_PORTALES[site].dominio;
			simpleModalJS = ((dominio.indexOf(site) != -1 )?PlayerWebTV.INFO_PORTALES[site].dominio:PlayerWebTV.INFO_PORTALES[site].dominio2)+simpleModalJS;
		} else {
			simpleModalJS = ((site!='')?PlayerWebTV.INFO_PORTALES[site].dominio:'')+simpleModalJS;
		}
		
		$("#photo-"+id+"-modal").html(obj);
		idComent = variables[7].substring(variables[7].indexOf('=')+1);
		
	}

	$("object").attr("z-index", "-1");
	$("embed").attr("wmode", "transparent");
	$("param[name|=wmode]").attr("value", "transparent");
	$("#photo-" + id + "-modal object embed").attr("wmode", "opaque");
	$("#photo-" + id + "-modal object").attr("z-index", "10000");
	$.getScript(simpleModalJS, function() {
		$("#photo-" + id + "-modal").modal();
		if ( idComent != "" && idComent.length > 1 ) getNumComentariosPortada("'"+idComent+"'");
		errorVerdadProvincias = false;
	});
	
	$("#photo-"+id+"-modal").removeClass();
	$("#photo-"+id+"-modal").addClass('player-modal');
}

function openVideoDiferido(site, medio,id, div) {
	var txt = $("#photo-"+id+"-modal-2").text();
	var variables = txt.split('#;#');


	var obj = getEmbedVideo(site,medio,div, variables[0].substring(variables[0].indexOf('=')+1),
							 variables[1].substring(variables[1].indexOf('=')+1),
							 variables[2].substring(variables[2].indexOf('=')+1),
							 variables[3].substring(variables[3].indexOf('=')+1));

	$("#"+div+"").html(obj);
}

function cambiaAutoStart(txt) {
	if( txt.toLowerCase().indexOf('microsoft') != -1 ) {
		if(txt.toLowerCase().indexOf('value="true" name="autostart"') != -1)
			txt = txt.toLowerCase().replace('value="true" name="autostart"', 'value="false" name="autostart"');
		if(txt.toLowerCase().indexOf('name="autostart" value="true"') != -1)
			txt = txt.toLowerCase().replace('name="autostart" value="true"', 'name="autostart" value="false"');
		if(txt.toLowerCase().indexOf('name="autostart" value="1"') != -1) 
			txt = txt.toLowerCase().replace('name="autostart" value="1"', 'name="autostart" value="0"');
		if(txt.toLowerCase().indexOf('value="1" name="autostart"') != -1) 
			txt = txt.toLowerCase().replace('value="1" name="autostart"', 'value="0" name="autostart"');
		if(txt.toLowerCase().indexOf('autostart="true"') != -1) 
			txt = txt.toLowerCase().replace('autostart="true"', 'autostart="false"');
		if(txt.toLowerCase().indexOf('autostart="0"') != -1) 
			txt = txt.toLowerCase().replace('autostart="0"', 'autostart="1"');
	}
	return txt;
}

function cambiaAltoAncho(txt) {
	var width='640';
	var height='360';
	var txtCambiado = '';
	if((txt.toLowerCase()).indexOf('width') != -1) {
		while((txt.toLowerCase()).indexOf('width') != -1) {
			var posIni = posInicio( txt, 'width');
			var posFin = posFinal( txt, posIni );
			txtCambiado += txt.substring(0, posIni) + width;
			txt = txt.substring(posFin);
		}
		txt = txtCambiado + txt;
	} else {
		txt = seteaAltoAncho(txt, 'width', width); 
	}
	txtCambiado = '';
	if((txt.toLowerCase()).indexOf('height') != -1) {
		while((txt.toLowerCase()).indexOf('height') != -1) {
			var posIni = posInicio( txt, 'height');
			var posFin = posFinal( txt, posIni );
			txtCambiado += txt.substring(0, posIni) + height;
			txt = txt.substring(posFin);
		}
		txtCambiado += txt;
	} else {
		txtCambiado = seteaAltoAncho(txt, 'height', height); 
	}
	
	return txtCambiado;				
}
function posInicio( txt, txt2 ) {
	var posIni = (txt.toLowerCase()).indexOf(txt2) + txt2.length;
	var aux;
	var continuar = true;
	while( continuar ) {
		aux = txt.charAt(++posIni);
		if( aux >= 0 && aux <= 9 ) {
			continuar = false;
		}
	}
	return posIni;
}
function posFinal( txt, pos ) {
	var posFin = pos;
	var aux;
	var continuar = true;
	while( continuar ) {
		aux = parseInt(txt.charAt(++posFin));
		if( isNaN(aux) ) {
			continuar = false;
		}
	}
	return posFin;
}
function seteaAltoAncho(txt, tipo, valor) {
	if( (txt.toLowerCase()).indexOf('object') != -1 ) {
		txt = txt.substring(0, ((txt.toLowerCase()).indexOf('object') + 6)) + ' ' + tipo + '="' + valor + 'px"' + txt.substring((txt.toLowerCase()).indexOf('object') + 6);  
	}
	if( (txt.toLowerCase()).indexOf('embed') != -1 ) {
		txt = txt.substring(0, ((txt.toLowerCase()).indexOf('embed') + 5)) + ' ' + tipo + '="' + valor + '"' + txt.substring((txt.toLowerCase()).indexOf('embed') + 5);  
	}
	if( (txt.toLowerCase()).indexOf('iframe') != -1 ) {
		if( (txt.toLowerCase()).indexOf('style') != -1 ) {
			txt = txt.substring(0, ((txt.toLowerCase()).indexOf('iframe="') + 8)) + ' ' + tipo + ':' + valor + 'px;' + txt.substring((txt.toLowerCase()).indexOf('iframe') + 8); 
		} else {
			txt = txt.substring(0, ((txt.toLowerCase()).indexOf('iframe') + 6)) + ' ' + 'style="' + tipo + ':' + valor + 'px;"' + txt.substring((txt.toLowerCase()).indexOf('iframe') + 6); 
		}
	}
	return txt;
}

//function isVideoBC(video) {
	//bVideoBC = true;
	//if(typeof video=="undefined" || ((video.toLowerCase().indexOf('rc@') == -1) && isNaN(video)))bVideoBC = false;
	//return bVideoBC;
//}

function getXMLHttpRequest()
{
	var xhr;
	if (window.XMLHttpRequest)
	{
		//El explorador implementa la interfaz de forma nativa
		xhr = new XMLHttpRequest();
	} 
	else if (window.ActiveXObject)
	{
		//El explorador permite crear objetos ActiveX
		try {
			xhr = new ActiveXObject("MSXML2.XMLHTTP");
		} catch (e) {
			try {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!xhr)
	{
		alert("No ha sido posible crear una instancia de XMLHttpRequest");
	}
	return xhr;
}

function getVideoObject(site,medio,sVideo, iWidth, iHeight, iIdPlayer, sEnlace, sPie, sEntradilla, iIdComentarios, iIdModal, imgPatrocinio, urlPatrocinio, clickcommand, redesSociales, autor ) {
	if(sEnlace != '' && !(sEnlace.toLowerCase().indexOf('http://') != -1)) {
		sEnlace = "http://"+ document.domain + sEnlace;
	}
	var s1 = '';
	s1 += '<div class="player-modal-t">';
	s1 += '<div class="player-modal-b">';
	s1 += '<div class="contenedor-modal">';
	if (imgPatrocinio != '' && urlPatrocinio != '' ) {
		s1 += '<div class="patrocinio">Patrocinado por: <a href="' + urlPatrocinio + '" target="_new" ><img src="' + imgPatrocinio + '" /></a></div>';
	}
	s1 += '<div class="cerrar"><a href="javascript:void(0)" class="simplemodal-close">Cerrar</a></div>';
	s1 += '<div class="centradoVideoModal" id="capaVideo_'+sVideo+'">';
	s1 += getEmbedVideo(site,medio,null, sVideo, iWidth, iHeight, iIdPlayer );
	s1 += '</div>';
	if(autor!= '')s1 +='<div class="photo-caption">Autor: '+autor+'</div>'
	s1 += '<div class="overhead"></div>'
	if(sEnlace != '') {
		s1 += '<h3><a class="enlaceNoticia" href="'+sEnlace+'">'+sPie+'</a></h3>';
	} else {
		s1 += '<h3><a>'+sPie+'</a></h3>';
	}
	s1 += '<div class="subhead">'+recortaCaracteres(sEntradilla, 200)+'</div>';
	s1 += '<div class="player-pie clearfix">';
	if(redesSociales != 'false' && sEnlace != '') {
		s1 += '<div class="redes-sociales">';
		s1 += '<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"></iframe>';
		s1 += '<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>'
		s1 += '<a target="_blank" href="http://www.tuenti.com/share?url='+sEnlace+'">';
		s1 += '<img src="/img/tuentishare_button22_ca.png" alt="Compartir tuenti"/>';
		s1 += '</a>';
		s1 += '</div>';
		s1 += '<a class="num_comentarios" href="'+sEnlace+'#opina" onclick="javascript:closeComentarios();">';
		s1 += '<span id="num-comentarios-'+iIdComentarios+'">Comenta esta noticia</span>';
		s1 += '</a>';
	}
	s1 += '</div></div></div></div>';
	return s1;
}

function getEmbedVideo(site,medio,layer, sVideo, iWidth, iHeight, iIdPlayer ) {
	if (!DetectSmartphone()) {
		var s1 = '';
		s1 += '<object id="flashObj-'+sVideo+'" width="'+iWidth+'" height="'+iHeight+'" 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/'+iIdPlayer+'?isVid=1&isUI=1" />';
		s1 += '<param name="bgcolor" value="#000000" />';
		s1 += '<param name="flashVars" value="@videoPlayer='+sVideo+'&playerID='+iIdPlayer+'&domain=embed&dynamicStreaming=true&autoStart=true" />';
		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="transparent" />';
		s1 += '<param name="allowScriptAccess" value="always" />';
		s1 += '<embed src="http://c.brightcove.com/services/viewer/federated_f9/'+iIdPlayer+'?isVid=1&isUI=1" bgcolor="#000000" ';
		s1 += 'flashVars="@videoPlayer='+sVideo+'&playerID='+iIdPlayer+'&&domain=embed&dynamicStreaming=true&autoStart=true" ';
		s1 += 'base="http://admin.brightcove.com" name="flashObj" width="'+iWidth+'" height="'+iHeight+'" seamlesstabbing="false" ';
		s1 += 'type="application/x-shockwave-flash" allowFullScreen="true" allowScriptAccess="always" swLiveConnect="true" wmode="transparent"';
		s1 += 'pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash">';
		s1 += '</embed>';
		s1 += '</object>';
		return s1;

	} else {
		var sMobile = makeMobileCompatible(site,medio,layer ? layer : "capaVideo_" + sVideo, sVideo, iIdPlayer, sVideo, iWidth, iHeight, null);
		return sMobile;
	}
}

function recortaCaracteres(text, limit) {
	//Modificado por Diego ;-)
	//Hay que limpiar el html antes de recortar
	text = strip_tags(text);
	
	if(text.length > limit) {
		if(text.charAt(limit) != ' ' && text.charAt(limit) != '') {
			var chars = izqDer(text, limit);
			if(chars > 0) {
				return text.substring(0, limit+chars) + "...";
			} else if(chars < 0){
				return text.substring(0, limit+chars) + "...";
			} else {
				return text.substring(0, limit) + "...";
			}
		} else {
			if(text.charAt(limit-4) != ' ' && text.charAt(limit-4) != '') {
				return text.substring(0, limit) + "...";
			} else {
				return text.substring(0, limit-5) + "...";
			}
		}
		return text
	} else {
		return text;
	}
}
function izqDer(text, limit) {
	var auxMas = 0;
	var auxMen = 0;
	do{
		auxMas++;
	}while(text.charAt(limit+auxMas) != ' ' && text.charAt(limit+auxMas) != '' );
	do{
		auxMen++;
	}while(text.charAt(limit-auxMen) != ' ' && text.charAt(limit+auxMas) != '' );
	if(auxMas<=auxMen && auxMas > 0) {
		return auxMas;
	} else if(auxMas>auxMen && auxMen > 0) {
		return auxMen * -1;
	} else {
		return 0;
	}
}

function getIdWMPlayer(txt) {
	if(txt.indexOf('microsoft') != -1) {
		var aux1 = txt.substring(txt.indexOf('<object'));
		var aux2 = aux1.substring(aux1.indexOf(' id="')+5);
		idWMPlayer = aux2.substring(0, aux2.indexOf('"'));
	} else {
		idWMPlayer = '';
	}
}
function stopplayer() {
	if (window.ActiveXObject != null && idWMPlayer != '') (document.getElementById(idWMPlayer)).controls.stop();
}

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 getTagsPatrocinados (idPortal) {
	var patrocinados = tagsPatrocinados[idPortal];
	return patrocinados;
}

function isTagPatrocinado (idPortal, tag) {
	var encontrado = false;
	var patrocinados = getTagsPatrocinados (idPortal);
	if (patrocinados != null) {
		for (var i = 0; (i < patrocinados.length) && !encontrado; i++) {
			if (patrocinados[i] == tag) encontrado = true;
		}	
	}
	return encontrado;
}

function getDatosTagPatrocinado (idPortal, tag) {
	if (isTagPatrocinado(idPortal, tag)) {
		return tagsPatrocinados[idPortal][tag];
	}
	else  {
		return null;
	}
}

function closeComentarios() {
	$.modal.impl.close();
}

function getThumbBC(div, site) {
	var idVideo = div.substring(0, div.indexOf('-'));
	var sEnlace = "";
	var sTitulo = "";
	var sVideoStillURL = "";
	var adTags;
	var sURLDataBC = '';
	if(isNaN(idVideo)) {
		if(idVideo.indexOf('rc@') != -1) idVideo = idVideo.substring(idVideo.indexOf('@')+1);
		sURLDataBC = '/includes/manuales/webtv/phpproxy/phpproxy.php?medio='+ PlayerWebTV.INFO_PORTALES[site].medio +'&command=find_video_by_reference_id&video_fields=name,linkURL,videoStillURL,tags&reference_id='+idVideo;
	} else {
		sURLDataBC = '/includes/manuales/webtv/phpproxy/phpproxy.php?medio='+ PlayerWebTV.INFO_PORTALES[site].medio +'&command=find_video_by_id&video_fields=name,linkURL,videoStillURL,tags&video_id='+idVideo;
	}
	
	if(getXMLHttpRequest()){
		$.ajax({
			url: sURLDataBC,
			dataType: 'json',
			data: null,
			async: false,
			success: function(data) {
				if (data.name!=null) sTitulo = data.name;
				if (data.linkURL!=null) sEnlace = data.linkURL;
				if (data.videoStillURL!=null) sVideoStillURL = data.videoStillURL;
				if (data.tags!=null) adTags = data.tags;
			}
		});
	}
	
	var codVideo = '<div class="photo">';
	codVideo += '<a href="'+sEnlace+'" title="'+sTitulo+'">';
	codVideo += '<img src="'+(getURLResizer(sVideoStillURL, 108, 62, 'play.png', site))+'" alt="'+sTitulo+'">';
	codVideo += '</a>';
	codVideo += '</div>';
	codVideo += '</div>';
	codVideo += '<div class="overhead">'+((adTags.length>0)?adTags[0]:"video")+'</div>';
	codVideo += '<h3>';
	codVideo += '<a href="'+sEnlace+'" title="'+sTitulo+'">'+recortaCaracteres(sTitulo, 28)+'</a>';
	codVideo += '</h3>';
	//$("#"+div+"").parent().html(codVideo);
	document.getElementById(div).parentNode.innerHTML = codVideo;
}



function getURLResizer(src, ancho, alto, marcaAgua, site) {
	var result = getFullURL(src);
	var medio = PlayerWebTV.INFO_PORTALES[site].resizer;
	if (!isDesarrolloABC()) {
		if (marcaAgua) {
			result = "http://resizer." + medio + "/resizer/resizer.php?imagen=" + result + "&nuevoancho=" + ancho + "&nuevoalto=" + alto + "&copyright=false&encrypt=false&posmarca=C&transparencia=85";
		} else {
			result = "http://resizer." + medio + "/resizer/resizer.php?imagen=" + result + "&nuevoancho=" + ancho + "&nuevoalto=" + alto + "&copyright=conCopyright&encrypt=false";
		}
	}
	return result;
}
	
function getFullURL(src) {
	if (src.indexOf("//") == -1 && !(src.charAt(0) == "/")) {
		// la ruta es relativa a la pagina
		// src = "nivel2/imagen.png"
		var ruta = location.href.substring(0, location.href.lastIndexOf("/") + 1);
		src = ruta + src;
	} else if (src.charAt(0) == "/") {
		// la ruta de la imagen es relativa al servidor, concatenamos el servidor actual
		// src = "/carpeta/imagen.png"
		src = location.protocol + "//" + location.host + src;
	}
	return src;
}





/*********************************************** 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 ()
 * method in order to retrieve the sepcific Video URL corresponding to the given object.
 */
function makeMobileCompatible(site,medio,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(site,medio,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(site,medio,playerID, programmedVideoID, readAPIToken, videoTagID, strObjID,iWidth,iHeight) {
	var APICall;
	var scriptNode;
	var scriptText;
	var callbackMethodName;
	//site PlayerWebTV.INFO_PORTALES[SITIO].resizer
	//medio PlayerWebTV.INFO_PORTALES[SITIO].medio
	if (programmedVideoID) {
		if(isNaN(programmedVideoID)) {
			if(programmedVideoID.indexOf('rc@') != -1) programmedVideoID = programmedVideoID.substring(programmedVideoID.indexOf('@')+1);
			APICall = 'http://' + site + '/includes/manuales/webtv/phpproxy/phpproxy.php?medio='+ medio +'&command=find_video_by_reference_id&reference_id='+programmedVideoID;
		} else {
			APICall = 'http://' + site + '/includes/manuales/webtv/phpproxy/phpproxy.php?medio='+ medio +'&command=find_video_by_id&video_id='+programmedVideoID;
		}

		if(isUDS) {
			APICall+="&media_delivery=http";
		}

		//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>function "+callbackMethodName+"(JSONResponse){" + 
		"handleVideoResponse(JSONResponse, '"+playerID+"', '"+videoTagID+"', '"+strObjID+"', '"+iWidth+"', '"+iHeight+"');"+
		"}</script>";
	}

	//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) {
	document.getElementById(strObjID).innerHTML = 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;
}
//Modificado por Diego ;-)
//Función de limpieza de html
function strip_tags (input, allowed) {
	 allowed = (((allowed || "") + "")
			.toLowerCase()
			.match(/<[a-z][a-z0-9]*>/g) || [])
			.join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
	 var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
			 commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
	 return input.replace(commentsAndPhpTags, '').replace(tags, function($0, $1){
			return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
	 });
}

function loadMultimediaSinFoto( video, opciones ) { // Metodo que se utiliza para enlazar el video a la capa Ver Video de methode
	var idComentarios = '';
	var idPlayer = PlayerWebTV.INFO_PORTALES[opciones.site].idPlayer;
	if (opciones.publicidadOn != undefined && !opciones.publicidadOn) idPlayer = PlayerWebTV.INFO_PORTALES[opciones.site].idPlayerSinPublicidad;
	var idPublisher = PlayerWebTV.INFO_PORTALES[opciones.site].idPublisher;
	var sVideoStillURL = "";
	var sIdVideo = "";
	var sPie = opciones.titulo;
	var sEntradilla = opciones.entradilla;
	var sEnlace = opciones.urlTitulo;
	var bVideoObtenido = (arguments.length > 2)?arguments[2]:false;
	var iWidth= 640;
	var iHeight= 360;
	var capaModal = false;
	var adTags = null;
	var sAutor = "";
	var iIdModal = video +'-_-'+PlayerWebTV.getUID("");
	// Si el video es de RC nos quedamos con la parte sin 'rc@'
	var iIdModalSinRC = ((iIdModal.toLowerCase().indexOf('rc@')!=-1)?iIdModal.substring(iIdModal.indexOf('@')+1):iIdModal);
	var sURLDataBC = '';
	if(isNaN(video)) {
		if(video.toLowerCase().indexOf('rc@') != -1) video = video.substring(video.indexOf('@')+1);
		sURLDataBC = '/includes/manuales/webtv/phpproxy/phpproxy.php?medio='+ PlayerWebTV.INFO_PORTALES[opciones.site].medio +'&command=find_video_by_reference_id&video_fields=id,name,longDescription,linkURL,videoStillURL,tags&custom_fields=origin&reference_id='+video;
	} else { // Si es video del propio portal lo buscamos por ID
		sURLDataBC = '/includes/manuales/webtv/phpproxy/phpproxy.php?medio='+ PlayerWebTV.INFO_PORTALES[opciones.site].medio +'&command=find_video_by_id&video_fields=id,name,longDescription,linkURL,videoStillURL,tags&custom_fields&video_id='+video;
	}
	
	if(getXMLHttpRequest()){
		$.ajax({
			url: sURLDataBC,
			dataType: 'json',
			data: null,
			async: false,
			success: function(data) {
				if (data != null ) {
					// Nos quedamos con el ID del por si lo que tenemos es el ID de referenci
					if (data.id!=null && sIdVideo=='') sIdVideo = data.id;  
					if (data.name!=null && sPie=='') sPie = data.name;
					if (data.longDescription!=null && sEntradilla=='')sEntradilla=data.longDescription;	  
					if (data.linkURL!=null && sEnlace=='') sEnlace = data.linkURL;
					if (data.videoStillURL!=null) sVideoStillURL = data.videoStillURL;
					if (data.tags!=null) adTags = data.tags;
					if (data.customFields!=null) if(data.customFields.origin!=null)sAutor = data.customFields.origin;
					bVideoObtenido = true;
				}
			}
		});
	}
	
	/*
	 * Caso para noticias compartidas de la verdad a las provincias y viceversa
	 */
	if( !bVideoObtenido && ( opciones.site == 'laverdad' || opciones.site == 'lasprovincias' ) ) {
		var opcionesOpcional = {
			categoriaPubli: ((opciones.categoriaPubli==undefined)?'':opciones.categoriaPubli),
			titulo: ((opciones.titulo==undefined)?'':opciones.titulo),
			imgPrevia: ((opciones.imgPrevia==undefined)?'':opciones.imgPrevia),
			site: ((opciones.site=='laverdad')?'lasprovincias':'laverdad'),
			entradilla: ((opciones.entradilla==undefined)?'':opciones.entradilla),
			urlTitulo: ((opciones.urlTitulo==undefined)?'':opciones.urlTitulo),
			imgPatrocinio: ((opciones.imgPatrocinio==undefined)?'':opciones.imgPatrocinio),
			urlPatrocinio: ((opciones.urlPatrocinio==undefined)?'':opciones.urlPatrocinio),
			clickcommand: ((opciones.clickcommand==undefined)?'':opciones.clickcommand),
			capaModal: ((opciones.capaModal == undefined)?true:opciones.capaModal),
			publicidadOn: ((opciones.publicidadOn == undefined)?true:opciones.publicidadOn),
			redesSociales: (opciones.redesSociales == undefined) ? true : opciones.redesSociales
		};
		cargaDatosVideo( video, opcionesOpcional, true );
	} else {
		if( video.indexOf('rc@') != -1 ) video = video.substring(video.indexOf('@')+1);
		$('.enlace_' + video).attr('href', 'javascript:openModal("'+opciones.site+'","'+PlayerWebTV.INFO_PORTALES[opciones.site].medio+'","'+iIdModalSinRC+'")');
		var contenedor = document.getElementById("ver_video_"+video);
		if (contenedor) {
			var divVars = document.createElement('div');
			divVars.setAttribute('id', 'photo-'+iIdModalSinRC+'-modal-2');
			var divCod = document.createElement('div');
			divCod.setAttribute('class', 'player-modal');
			divCod.setAttribute('id', 'photo-'+iIdModalSinRC+'-modal');
			contenedor.appendChild(divVars);
			contenedor.appendChild(divCod);
		}
		$('#photo-'+iIdModalSinRC+'-modal-2').attr('style', 'display: none');
		$('#photo-'+iIdModalSinRC+'-modal').attr('style', 'display: none');	
		
		//Vemos si el tag del video tiene algún patrocinio asociado
		if(opciones.imgPatrocinio=='' || opciones.urlPatrocinio=='') {
			var hayPatrocinio = false;
			var numTags = (adTags != null)?adTags.length:0;
			for(var i=0;!hayPatrocinio && i < numTags; i++) {
				if(getDatosTagPatrocinado(opciones.site, adTags[i]) != null){
					opciones.imgPatrocinio = getDatosTagPatrocinado(opciones.site, adTags[i]).imgPatrocinio;
					opciones.urlPatrocinio = getDatosTagPatrocinado(opciones.site, adTags[i]).urlPatrocinio;
					opciones.clickcommand = '';//getDatosTagPatrocinado(opciones.site, adTags[i]).clickcommand;
					hayPatrocinio = true;
				}
			}
		}
		
		//Obtenemos el código del video
		sPie = sPie.replace(/"/g, "'");
		sPie = sPie.replace(/'/g, "\'");
		sEntradilla = sEntradilla.replace(/"/g, "'");
		sEntradilla = sEntradilla.replace(/'/g, "\'");
		var vars = "idVideo="+sIdVideo+"#;#w="+iWidth+"#;#h="+iHeight+"#;#idPlayer="+idPlayer+"#;#url="+sEnlace+"#;#pie="+sPie+"#;#entradilla="+sEntradilla+"#;#comentarios="+idComentarios+"#;#idDiv="+iIdModalSinRC+"#;#imgPatrocinio="+opciones.imgPatrocinio+"#;#urlPatrocinio="+opciones.urlPatrocinio+"#;#clickcommand="+opciones.clickcommand+"#;#site="+opciones.site+"#;#rSociales="+opciones.redesSociales+"#;#autor="+sAutor;
		
		var variables = document.createTextNode(vars);
		document.getElementById("photo-"+iIdModalSinRC+"-modal-2").appendChild(variables);
		
	}
}
