
// 
function thisMovie(movieName) {
	if(navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
};

function setInnerHTML(objectId,text)
{
	if(document.getElementById && document.getElementById(objectId)) {
		document.getElementById(objectId).innerHTML = '';
		document.getElementById(objectId).innerHTML = text;
	} else if (document.all && document.all(objectId)) {
		document.all(objectId).innerHTML = text;
	} else {
		return false;
	}
	return true;
} 

function getInnerHTML(objectId){
 if(document.getElementById && document.getElementById(objectId)) return document.getElementById(objectId).innerHTML;
 else if (document.all && document.all(objectId)) return document.all(objectId).innerHTML;
 else return "";
}

function set_pos(obj_str, left, top) {
try{
    var obj = document.getElementById(obj_str);
    obj.style.left   = left;
    obj.style.top    = top;
}
catch(er){/*alert("set_pos:"+document.URL+"*** "+obj_str+" "+left+" "+top);*/}
}

function set_pos_size(obj_str, left, top, width, height, morph) {
try{
    var obj = document.getElementById(obj_str); 
	if (morph) {
	  $(obj_str).morph('left:'+left+'px; top:'+top+'px; width:'+width+'px; height:'+height+'px;');
	} else {
	  obj.style.left=left;
      obj.style.top    = top;
      obj.style.width  = width;
      obj.style.height = height;
	}
}
catch(er){alert("set_pos_size "+er);}

}

function set_bkgrnd(obj_str,bkgrnd){
  try{
    var obj = document.getElementById(obj_str);
    var b=new BrowserDetect();
	if ((b.browser=="Explorer")&&(bkgrnd.toLowerCase().indexOf(".png")>0)&&(obj.filters)&&(obj.filters.length>0)){
		obj.style.backgroundImage='none';
		obj.filters[0].src='images/'+bkgrnd;
	}
	else obj.style.backgroundImage='url("images/'+bkgrnd+'")';
  }
  catch(er){
	alert("set_bkgrnd "+obj_str+" "+bkgrnd+" "+er);
  }


}
function set_pos_size_bkgrnd(obj_str, left, top, width, height, morph,bkgrnd) {
try{
    var obj = document.getElementById(obj_str);
	if (morph) {
	  $(obj_str).morph('left:'+left+'; top:'+top+'; width:'+width+'; height:'+height+';');
	} else {
      obj.style.left   = left;
      obj.style.top    = top;
      obj.style.width  = width;
      obj.style.height = height;
	}
	set_bkgrnd(obj_str,bkgrnd);
}
catch(er){/*alert("set_pos_size_bkgrnd");*/}

}

function set_hidden(obj_str) {
  try{document.getElementById(obj_str).style.visibility="hidden";} catch(er){/*alert("set_hidden");*/}
}
function set_visible(obj_str) {
  try{
    document.getElementById(obj_str).style.visibility="visible";} 
  catch(er){/*alert("set_visible:"+document.getElementById(obj_str));*/}
}


// ****** AJAX 
function AjaxResponse(callback){
  if (http_request.readyState == 4) {
    if (http_request.status == 200){
	  callback(http_request.responseText);
    } else {
	  callback("")
	};
  } 
} 
var http_request = false;
function makeRequest(url,callback) {
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
    http_request = new XMLHttpRequest();
    //  Si pongo esto falla en Firefox 1.5  
    //if (http_request.overrideMimeType)  http_request.overrideMimeType('text/xml');
  } else if (window.ActiveXObject) { // IE
    try { http_request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try { http_request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {}
    }
  }

  if (!http_request) return false;

  http_request.onreadystatechange = function(){AjaxResponse(callback);}
  http_request.open('GET', url, true);
  http_request.send(null);
}
 // ****** AJAX SINCRONO
function makeSynchRequest(url) {
   var http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
      } else if (window.ActiveXObject) { // IE
        try { http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
          try { http_request = new ActiveXObject("Microsoft.XMLHTTP");
          } catch (e) {}
        }
      }

      if (!http_request) return false;
      
	  try{
		http_request.open('GET', url, false);
		http_request.send(null);
		if (http_request.status == 200) {
			return http_request.responseText; 
		} else {
			return "";
		}
	  }
	  catch(e){
		return "";
	  }
 }
 
 function makeSynchRequestPost(url,params)
{
   var http_request = false;
      if (window.XMLHttpRequest) 
	  { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
      } else if (window.ActiveXObject) { // IE
        try { http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
          try { http_request = new ActiveXObject("Microsoft.XMLHTTP");
          } catch (e) {}
        }
      }
      if (!http_request) return false;     		
      http_request.open('POST', url, false);	  
	  http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");	  
      http_request.send(params);
      if (http_request.status == 200) {	
        return http_request.responseText; 
      } else {
		
        return "";
      }
}

// unescape HTML 
function unescapeHTML(str){
	txt = str.replace(/(&#)([0-9]{1,5})(;)/g,
             function (a1, a2, a3, a4) {
				return String.fromCharCode(a3);
             }
    );
	return txt;
}

// ***** WM
function detectWMP_OBJmodel()
{   var b=new BrowserDetect();
	var wmp64 = "MediaPlayer.MediaPlayer.1";
	var wmp7 = "WMPlayer.OCX.7";
	if(createActiveXObject(wmp7)&&(b.browser=="Explorer"))return 7;
	if(createActiveXObject(wmp64)&&(b.browser=="Explorer"))return 6;
	if(navigator.mimeTypes){
        // VER http://msdn.microsoft.com/en-us/library/bb614511(VS.85).aspx 
	    // VER http://msdn.microsoft.com/en-us/library/bb614515(VS.85).aspx
		try{ var player1 = navigator.mimeTypes['application/x-mplayer2'].enabledPlugin;} catch (error){;}
		try{ var player2 = navigator.mimeTypes['application/x-ms-wmp'].enabledPlugin;} catch (error){;}
		
		if(player2)return 2;
		if(player1)return 1;
	}
	return 0;
}

function PlayerObjectCode(ObjectName,ObjectWidth,ObjectHeight,Stream)
  		{   
  			var wmp_version = detectWMP_OBJmodel();
			var txt="";  					
  			if (wmp_version==0) txt+= "Windows media not installed"; // ???? Poner Texto Fetén con descarga .......
  			if(wmp_version>6)
  			{
				txt+= "<object id='" + ObjectName + "' name='" + ObjectName + "' width='" + ObjectWidth + "' height='" + ObjectHeight + "'";			
  				txt+= " classid='CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6'";
  				txt+= " TYPE='application/x-oleobject'>";
//  				txt+= "<param name='URL' value=''>";
  				txt+= "<param name='URL' value='" + Stream + "'>\n";
  				txt+= "<param name='EnableContextMenu' value='false'>\n"; //??? poner true si debug
  				txt+= '<param name="AutoStart" value="true">'; 
   				txt+= '<param name="invokeURLs" value="false">'; 
   				txt+= '<param name="stretchToFit" value="true">';
  				txt+= "</OBJECT>";
 		}
  			if(wmp_version==6)
  			{
  				txt+= "<object id='" + ObjectName + "' name='" + ObjectName + "' width='" + ObjectWidth + "' height='" + ObjectHeight + "'";			
  				txt+= "CLASSID=CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95 ";
  				txt+= "CODEBASE=http://activex.microsoft.com/activex/controls/mdocAudioPlayer/en/nsmp2inf.cab#Version=6,4,5,715 ";
  				txt+= "TYPE='application/x-oleobject'>";
  				txt+= "<PARAM NAME='FileName' value='" + Stream + "'>\n";
  				txt+= "<param name='EnableContextMenu' value='false'>\n";
  				txt+= '<param name="AutoStart" value="true">'; 
  				txt+= '<param name="stretchToFit" value="true">';
  				txt+= "</OBJECT>";
  			}
			var PlugIn,invokeUrls,defaultFrame;
			if(wmp_version==1) {PlugIn = 'application/x-mplayer2'; invokeUrls='1'; defaultFrame="MACCMD";}
			if(wmp_version==2) {PlugIn = 'application/x-ms-wmp'; invokeUrls='false'; defaultFrame="";} //NO LO SOPORTA EN 2 (FF windows)=> SE HACE POR CODIGO Cuando el player ya ha arrancado: document["NSplayer"]["settings"]["invokeURLs"] = "false";
  			if((wmp_version==1) || (wmp_version==2))
  			{	// VER http://msdn.microsoft.com/en-us/library/bb614511(VS.85).aspx	
  				//plugins;		
  				var MediaPlugInPage = "http://www.microsoft.com/windows/windowsmedia/";  
  				txt+= "<embed name='" + ObjectName + "' id='" + ObjectName + "' width='" + ObjectWidth + "' height='" + ObjectHeight + "'\n";
  				txt+= " type='"+ PlugIn +"'\n"; 
  				txt+= " pluginspage='"+ MediaPlugInPage +"'\n";
  				txt+= " enableContextMenu='false'";
  				txt+= " src='" + Stream + "'\n";
  				txt+= " autoStart='true'";
  				txt+= " ShowStatusBar='true'";
  				txt+= " invokeURLs='"+invokeUrls+"'"; 
				if (defaultFrame!="") txt+= "defaultFrame='"+defaultFrame+"'";
				txt+= " stretchToFit='true'"; //m-player2 no lo soporta.
				txt+= " >";
  				txt+= "</embed>\n";
  			}
			return txt;
}


// ***** WM
function detectFLASH_version(){
  var version = deconcept.SWFObjectUtil.getPlayerVersion();
  return version['major'];


}

function createActiveXObject(id)
	{
		var error;
		var control = null;
		try
		{
			if (window.ActiveXObject)control = new ActiveXObject(id);
			else if (top.GeckoActiveXObject)control = new top.GeckoActiveXObject(id);
		}
		catch (error){;}
		return control;
}

function BrowserDetect () {
    // PUBLIC INTERFACE
	this.browser = "An unknown browser";
	this.version = "an unknown version";
	this.OS      = "an unknown OS";

	//  this.BrowserDetect.browser
	// "Chrome","OmniWeb","Safari","Opera","iCab","Konqueror","Firefox","Camino","Netscape","Explorer","Mozilla","Netscape", "An unknown browser"
	//
	// this.BrowserDetect.version; 
	// version o "an unknown version".
    // 
	// this.BrowserDetect.OS;
	// "Windows","Mac","Linux", "an unknown OS"


    // PRIVATE Interface
    this.searchString = searchString;
	this.searchVersion = searchVersion;

	this.dataBrowser = [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	];

	this.dataOS = [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

	this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
	this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
	this.OS = this.searchString(this.dataOS) || "an unknown OS";

	function searchString(data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	}

	function searchVersion(dataString) {
		var index = dataString.indexOf(this.versionSearchString);
      if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	}

}

function isAbsoluteURL(url){
   var s=new String(url);
   return ((s.indexOf("http://")==0)||(s.indexOf("https://")==0));
}

function EncodeStreamType(str){
  switch (str){
    case ('VOD'): st='tv'; break; 
    case ('VOD_EXPRESS'): st='tx'; break;
    case ('DIRECTO'): st='td'; break;
    case ('PLAYLIST'): st='tp'; break;
    default: st='tv'; break; 
  }
  if (st=='tv') st=''; //Por defecto, vod
  return st;
}

function EncodeEvent(sty,eve){
  if (sty!='VOD') return '';
  var e="e"+eve;
  if (e=="e0") e="";
  return e;
}

function EncodeSession(sty,ses){
  if ((sty=='DIRECTO')||(sty=='VOD')) return '';
  var s="s"+ses;
  if (s=="s0") s="";
  return s;
}

function EncodeActivity(sty,act){
  if (sty!='VOD') return '';
  var a="a"+act;
  if (a=="a0") a="";
  return a;
}

function EncodePortal(sty,po){
  if (portalCode[po.toLowerCase()]==undefined) return "";
  var p="p"+portalCode[po.toLowerCase()];
  if (p=="p"+portalCode['fundatel']) p="";
  return p;
}


function EncodeUser(sty,usu){
  var us="";
  if (usu == 'DISTRIB') us='u2'; 
  else if (usu == 'EDIT') us='u1'; 
  else if (usu == 'ADMIN') us='u0'; 
  else us='u2'; 
  if (us=='u2') us='';
  return us;
}

function EncodeMode(sty,mod){
  if (sty!='DIRECTO') return '';
  var m='m0';
  if (mod.toLowerCase()=='normal') m="m0";
  if (mod.toLowerCase()=='test') m="m1";
  if (m=="m0") m="";
  return m;
}

function EncodeHashtag(sty,h){
  if ((sty=='VOD')||(sty=='PLAYLIST')) return '';
  if (h=='') return '';
  var ht="h"+h;
  return ht;
 
}

function EncodeVisor(sty,v){
  var r='';
  var x=v.toUpperCase();
  if (x == 'COMPLETO')  r='v0'; 
  else if (x == 'MINI') r='v1';
  else if (x == 'EMBUTIDO') r='v2';
  else if (x == 'IPHONE') r='v3';
  else if (x == 'IPAD') r='v4';
  else if (x == 'ANDROID') r='v5';
  else r='v0';
  if (r=='v0') return '';
  return r;
}

function EncodeIdiomaVideo(sty,i){
  var iv='';
  if (i=='') return '';
  var iv="i"+i;
  return iv;
}

function EncodeIdiomaDatos(sty,i){
  var len='';
  if (i=='') return '';
  var len="l"+i;
  return len;
}

function EncodeCtrlAcceso(sty,c){
   if (c=='') return '';
   else return 'x'+c;
}

function EncodeCalidad(sty,cal){
  var q="";
  if (cal!=""){
	q="q"+cal;
    if (q=="q0") q="";
  }
  return q;
}

function Encode(sty,eve,ses,act,por,usu,mod,hashtag,visor,idioma_video,idioma_datos,ctrlAcceso,calidad){
  var r=""; var x="";
  x=EncodeStreamType(sty); if (x!="") r+=(r=="")?x:"-"+x;
  x=EncodeEvent(sty,eve); if (x!="") r+=(r=="")?x:"-"+x;
  x=EncodeSession(sty,ses); if (x!="") r+=(r=="")?x:"-"+x;
  x=EncodeActivity(sty,act); if (x!="") r+=(r=="")?x:"-"+x;
  x=EncodePortal(sty,por); if (x!="") r+=(r=="")?x:"-"+x;
  x=EncodeUser(sty,usu); if (x!="") r+=(r=="")?x:"-"+x;
  x=EncodeMode(sty,mod); if (x!="") r+=(r=="")?x:"-"+x;
  x=EncodeHashtag(sty,hashtag); if (x!="") r+=(r=="")?x:"-"+x;
  x=EncodeVisor(sty,visor); if (x!="") r+=(r=="")?x:"-"+x;
  x=EncodeIdiomaVideo(sty,idioma_video); if (x!="") r+=(r=="")?x:"-"+x;
  x=EncodeIdiomaDatos(sty,idioma_datos); if (x!="") r+=(r=="")?x:"-"+x;
  x=EncodeCtrlAcceso(sty,ctrlAcceso); if (x!="") r+=(r=="")?x:"-"+x;
  x=EncodeCalidad(sty,calidad); if (x!="") r+=(r=="")?x:"-"+x;
  
  if (r!="") r="?"+r; 
  return r;
}
function EncodeStreamType35(str){
  var st='NotValid';
  switch (str){
    case ('VOD'): st='9548'; break;
    case ('VOD_EXPRESS'): st='352'; break;
    case ('DIRECTO'): st='5744'; break;
  }
  return st;
}

function EncodeEvent35(eve){
  var ev;
  if (eve==0) return 25;
  if (isNaN(eve)) return eve;
  ev=(eve*113)-15;
  return ev;
}

function EncodeSession35(ses){
  var se;
  se=(ses*167)+23;
  return se;
}

function EncodeActivity35(act){
  var ac;
  ac=(act*149)+6;
  return ac;
}

function EncodePortal35(p){
   if (p.toLowerCase()=='ekiss') return 2926;
   if (p.toLowerCase()=='ekiss_uk') return 4707;
   else return 'NotValid';
}


function EncodeUser35(usu){
  var us;
  if (usu == 'DISTRIB'){ us='1849'; }
  else if (usu == 'EDIT'){ us='4122'; }
  else if (usu == 'ADMIN'){ us='3115'; }
  return us;
}

function EncodeMode35(mod){
  var mo='NotValid';
  if (mod == 'normal'){ mo='3485'; }
  else if (mod == 'TEST'){ mo='849'; }
  return mo;
}

function EncodeCalidad35(cal){
  var ca='NotValid';
  if (cal == 'ADSL'){ ca='375'; }
  else if (cal == 'ADSL2'){ ca='989'; }
  else if (cal == 'RTB'){ ca='1447'; }
  else if (cal=='ANY'){ca='7878';}
  return ca;
}

function EncodeVisor35(v){
  var r='NotValid';
  var x=v.toUpperCase();
  if (x == 'COMPLETO'){ r='358'; }
  else if (x == 'MINI'){ r='966'; }
  return r;
}


function DummySlides35(){return '6845';}

function DummyAvance35(){return '0';}

function DummyChequeo35(){return '615';}

function Encode35(sty,eve,ses,act,por,usu,mod,cal,sala,visor){
  var r="?code=";
  r+=EncodeStreamType35(sty);
  r+="-"+EncodeEvent35(eve);
  r+="-"+EncodeSession35(ses);
  r+="-"+EncodeActivity35(act);
  r+="-"+EncodePortal35(por);
  r+="-"+EncodeUser35(usu);
  r+="-"+EncodeMode35(mod);
  r+="-"+EncodeCalidad35(cal);
  r+="-"+DummySlides35();
  r+="-"+DummyAvance35();
  r+="-"+sala;
  r+="-"+EncodeVisor35(visor); //
  return r;
}

function loadXMLString(dname){
	if (window.DOMParser)
	{
	  parser=new DOMParser();
	  var xmlDoc = parser.parseFromString(dname,"text/xml");
	}
	else // Internet Explorer
	{
	  var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	  	try 
		{
		  xmlDoc.async="false";
		  xmlDoc.loadXML(dname);
		}catch(e) {}  
	}		
		return xmlDoc;
}

function obten_dato(xmlObj, elementStr){
	return obten_dato_lista(xmlObj, elementStr,0);
}

function obten_dato_lista_len (xmlObj, elementStr){
   if (xmlObj == null) return 0;
   return xmlObj.getElementsByTagName(elementStr).length;
}
function obten_dato_lista (xmlObj, elementStr,i){
    if (xmlObj == null) return "";
	var dato=xmlObj.getElementsByTagName(elementStr);
   var datoStr = "";
	if (dato.length > 0) {
	   try{datoStr = trim(dato[i].childNodes[0].nodeValue);} catch(er){datoStr = "";}
	}
    return datoStr;
}
 
function trim(s){
	return s.replace(/^\s+/g,'').replace(/\s+$/g,'');
}

function correctDateStr(date_str) {
  if (date_str=="") return false;
  var date_time=date_str.split(" ");
  var date=date_time[0];

  var a=date.split("/");
  if (a.length<3){ return false;}
  var d=a[0];
  var m=a[1];
  var an=a[2];
  if (!checkDay(d)) return false;
  if (!checkYear(an)) return false;
  if (!checkMonth(m))return false;

  if (date_time.length<2) return true;
  var time=date_time[1];
  var t=time.split(":");
  if (t.length<2) return false;
  var h=t[0];
  var m=t[1];
  if (!checkHour(h)) return false;
  if (!checkMin(m)) return false;
  return true;
 }

function checkDay(d){var i=parseInt(d,10); 
 return ((!isNaN(i))&&(i>=1)&&(i<=31));}

function checkMonth(m){var i=parseInt(m,10); 
 return ((!isNaN(i))&&(i>=1)&&(i<=12));}

function checkYear(y){var i=parseInt(y,10); return ((!isNaN(i))&&(i<3000));}

function checkHour(h){var i=parseInt(h,10); 
 return ((!isNaN(i))&&(i>=0)&&(i<=23));}

function checkMin(m){var i=parseInt(m,10); 
 return ((!isNaN(i))&&(i>=0)&&(i<=59));}
 
function addColourToTextField(objectId,mode){	
	if(mode=='RED')	document.getElementById(objectId).style.backgroundColor = "#F08080";	
	if(mode=='WHITE')	document.getElementById(objectId).style.backgroundColor = "#FFF";	
} 


function cambiarOrdenArriba(elemento){
	if(hayElementoSeleccionado(elemento)==true){	
		if(elemento.length>0){	
			var indexS = elemento.options[elemento.selectedIndex].index;	
				if(indexS>0){
					var actualValue = elemento.options[indexS].value;
					var actualText = elemento.options[indexS].text;
					var auxValue = elemento.options[indexS-1].value;
					var auxText = elemento.options[indexS-1].text;
					elemento.options[indexS-1].value = actualValue
					elemento.options[indexS-1].text = actualText
					elemento.options[indexS].value = auxValue;
					elemento.options[indexS].text = auxText;
					elemento.options[indexS-1].selected="selected";
				}
		}	
	}	
}

function cambiarOrdenAbajo(elemento){
	if(hayElementoSeleccionado(elemento)==true){
		if(elemento.length>0){
			var indexS = elemento.options[elemento.selectedIndex].index;	
			var max = elemento.length-1;
				if(indexS<max){
					var actualValue = elemento.options[indexS].value;
					var actualText = elemento.options[indexS].text;
					var auxValue = elemento.options[indexS+1].value;
					var auxText = elemento.options[indexS+1].text;
					elemento.options[indexS+1].value = actualValue
					elemento.options[indexS+1].text = actualText
					elemento.options[indexS].value = auxValue;
					elemento.options[indexS].text = auxText;
					elemento.options[indexS+1].selected="selected";
				}
		}	
	}		
}

function hayElementoSeleccionado(elemento){
var c = 0;
var seleccionado = false;
	for(var i=0;i<elemento.length;i++){
		if(elemento.options[i].selected==true){
			seleccionado = true;
			break;	
		}
	}
		return seleccionado;
}

function borrarElemento(elemento){
	for(var i=0;i<elemento.length;i++){
		if(elemento.options[i].selected == true)
			elemento.options[i] = null;
	}	
}

function anadirElemento(elementoOri,elementoDest){
	if(elementoOri.options[elementoOri.selectedIndex].value != -1){
		var txt = elementoOri.options[elementoOri.selectedIndex].text;
		var valor = elementoOri.options[elementoOri.selectedIndex].value;
		elementoDest.options[elementoDest.options.length] = new Option(txt,valor,"defaultSelected");	
	}
}

function toMs(hmsd){
var msec=0; var horas=0; var minutos=0; var segundos=0; var decimas=0;
var signo = +1;
var sep_signo=hmsd.split("-");
if (sep_signo.length==1) {
   var sep_dec=sep_signo[0].split("."); 
} else {
   signo = -1;
   var sep_dec=sep_signo[1].split(".")
}
if (sep_dec.length==2) decimas=parseInt(sep_dec[1],10);
var sep_hhmmss=sep_dec[0].split(":"); 
if (sep_hhmmss.length==3){horas=parseInt(sep_hhmmss[0],10); minutos=parseInt(sep_hhmmss[1],10); segundos=parseInt(sep_hhmmss[2],10);}
else if (sep_hhmmss.length==2){minutos=parseInt(sep_hhmmss[0],10); segundos=parseInt(sep_hhmmss[1],10);}
else msec+=segundos=parseInt(sep_hhmmss[0]);       
msec=1000*(3600*horas+60*minutos+segundos)+100*decimas;
	return msec*signo;
}

function toHmsd(ms){
var str="";
if (ms < 0) {
   str="-";
   ms = ms * (-1);       
}
var d=ms%1000; 
var s=(ms-d)/1000;
d=d/100;    
var m=Math.floor(s/60); s=s-m*60;
var h=Math.floor(m/60); m=m-h*60;

if (h<10) str+="0"+h; else str+=+h;
if (m<10) str+=":0"+m; else str+=":"+m;
if (s<10) str+=":0"+s; else str+=":"+s;
if (d>0) str+="."+d;
	return str;
}

function crToInputString(str){
   var aux=str.split("<br>");
   var r=aux[0];
   for (var i=1; i<aux.length; i++) r+="\r\n"+aux[i];
   aux=r.split("</br>"); r=aux[0];
   for (var i=1; i<aux.length; i++) r+="\r\n"+aux[i];
   return r;
}

function doubleQuoteCR(str){
   var aux=str.split("\r"); var r=aux[0]; 
   for (var i=1; i<aux.length; i++) r+="\\r"+aux[i];
   aux=r.split("\n"); r=aux[0];
   for (var i=1; i<aux.length; i++) r+="\\n"+aux[i];
   return r;
}

function avoidSingleQuote(str){
   var aux=str.split("'"); var r="";
   for (var i=0; i<aux.length; i++) r+=aux[i];
   return r;
}

function crToHtmlString(str){
   var aux=str.split("\\r\\n"); var r=aux[0]; 
   for (var i=1; i<aux.length; i++) r+="<br>"+aux[i];
   aux=r.split("\\n"); r=aux[0];
   for (var i=1; i<aux.length; i++) r+="<br>"+aux[i];
   aux=r.split("\r\n"); r=aux[0];
   for (var i=1; i<aux.length; i++) r+="<br>"+aux[i];
   aux=r.split("\n"); r=aux[0];
   for (var i=1; i<aux.length; i++) r+="<br>"+aux[i];
   return r;
}

function StringToHTMLString(string){
	var sb="";
	var len = string.length;
	var c;
   for (var i = 0; i < len; i++)
   {
        c = string.charAt(i);
        // HTML Special Chars
        var ci = string.charCodeAt(i);  
        if ((ci < 160 ) && (ci != 39) && (c != '"') && (c != '&') && (c != '<') && (c != '>'))
            // nothing special only 7 Bit or "'" or other special char
            sb+=c;
        else {
            // Not 7 Bit use the unicode system
            var x="&#"+ci+";";
            sb+=x;
        }
	}
	return sb;
}

function escapeXML(str){
      str = str.replace(/&#/g,"YYYY"); // Para dejar los códigos ya existentes
      str = str.replace(/&/g,"XxXx"); // Para poder reemplazar el & que luego aparece en los códigos
      str = str.replace(/</g,"&#60;");
      str = str.replace(/:/g,"&#58;");
      var retStr="";
      for (var i= 0; i < str.length; i++) {
         if ((str.charCodeAt(i) > 160) || (str.charCodeAt(i) == 39) || (str.charCodeAt(i) == 44)) {
            retStr += "&#"+str.charCodeAt(i)+";";
         }else {
            retStr += str.charAt(i);
         }
      }
      retStr = retStr.replace(/XxXx/g,"&#38;");
      retStr = retStr.replace(/YYYY/g,"&#");
   
      var aux=retStr.split("<br>"); retStr="";
      for (var i=0; i<aux.length; i++) retStr+=aux[i];
      return retStr;
}

  function isInvalidEmail(input){
     // pattern for checking if e-mail address fits the user@domain format
     var emailPat=/^(.+)@(.+)$/
     // pattern for matching special chars
     var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
     // chars allowed in a username or domainname
     var validChars="\[^\\s" + specialChars + "\]";
     // pattern applied if the "user" is a quoted string 
     var quotedUser="(\"[^\"]*\")";
     // pattern applied for domains that are IP addresses
     var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
     // series of non-special characters
     var atom=validChars + '+';
     // word in the typical username
     var word="(" + atom + "|" + quotedUser + ")";
     // pattern describing the structure of the user
     var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
     // pattern describing the structure of a normal symbolic domain
     var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
   
     var matchArray=input.match(emailPat);
     if (matchArray==null) {
       return true;
     }
     var user=matchArray[1];
     var domain=matchArray[2];
     if (user.match(userPat)==null) {
       return true;
     }
     var IPArray=domain.match(ipDomainPat);
     if (IPArray!=null) {
       // this is an IP address
       for (var i=1;i<=4;i++) {
         if (IPArray[i]>255) {
           return true;
         }
       }
       return false;
     }
     var domainArray=domain.match(domainPat);
     if (domainArray==null) {
       return true;
     }
     var atomPat=new RegExp(atom,"g");
     var domArr=domain.match(atomPat);
     var len=domArr.length;
     if (domArr[domArr.length-1].length<2 || 
         domArr[domArr.length-1].length>3) {
       return true;
     }
     if (len<2) {
       return true;
     }
     return false;
  }
  
  function pwdContainsInvalidChars(input){
     var re=new RegExp('[^A-Za-z0-9_.-]');
     var r=input.match(re);
     return (r!=null);
  }

function obtenerCodigoMac(xmlStr,concatenacionXML){
  /*El algoritmo para obtener el código es el siguiente:
		- se obtiene la longitud del xml completo.
		- Se extrae un fragmento del xml de 25 caracteres.
		- Se multiplican entre si los números codificados a ascii
		  de cuatro caracteres del fragemnto extraído.
		- Al resultado se le suma la longitud multiplicada por un número primo.
		- Y posteriormente se le suma otra cifra para asegurar los nueve dígitos.
		- Si hubiese más de 9 dígitos sólamente se tienen en cuenta los 9 primeros.*/

	var auxXml = escapeXML(xmlStr+concatenacionXML); 
  	var longXML = auxXml.length;
	var aux = "";
		if(longXML>500)	aux = auxXml.substring(475,500);
		else aux = auxXml.substring(longXML-(concatenacionXML.length+25),longXML-concatenacionXML.length);
	var auxx = (aux.charCodeAt(3)*aux.charCodeAt(5)*aux.charCodeAt(7)*aux.charCodeAt(9));
	auxx += longXML*2027;
	auxx += 141098765;
	var resultado = String(auxx);
		if(resultado.length>9)	resultado = resultado.substring(0,8);	
	return resultado;
}





