///<reference path="globalfw.js">

function checkBrowser()
{
	this.ver=navigator.appVersion
	this.dom=document.getElementById?1:0
	this.ie5=(this.ver.indexOf("MSIE 5")>-1	&& this.dom)?1:0;
	this.ie6=(this.ver.indexOf("MSIE 6")>-1	&& this.dom)
	if(this.ie6){this.ie5=1;}
	this.ie4=(document.all && !this.dom)?1:0;
	this.ns5=(this.dom && parseInt(this.ver) >= 5) ?1:0;
	this.ns4=(document.layers && !this.dom)?1:0;
	this.bw=(this.ie5 || this.ie4 || this.ns4 || this.ns5)
	return this
}


function ConsultaUrl(parametro)
{
	var valorParametro="";
	var search=window.location.search
	search=search.substring(1,search.length);
	var querystring=search.split("&");
	
	for (i=0;i<querystring.length;i++)			
	{
		if(querystring[i].toLowerCase().indexOf(parametro.toLowerCase())==0)
		{
			return querystring[i].split("=")[1];
		}
	}
	return null;
}
	function ValidarLongitudTexto(CajaTexto,Numero)
{

var Cadena= new String();
if(event.type=='paste'){
Cadena=CajaTexto.value+window.clipboardData.getData("Text");
}else{
Cadena=CajaTexto.value;


}

 if (Cadena.length>Numero-1)
 {

 //Cadena=window.document.Form1.txtDescripcion.value;

 CajaTexto.value=Cadena.substring(0,Numero);
 alert('El campo solo admite ' + Numero + ' caracteres.');
event.keyCode='';
 event.returnValue=false; }
 }
 	
function MM_preloadImages() { //v3.0
var d=document;	if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var	i,j=d.MM_p.length,a=MM_preloadImages.arguments;	for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length)	{
    d=parent.frames[n.substring(p+1)].document;	n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x	&& document.getElementById) x=document.getAspElementById(n); return x;
}

function MM_swapImage()	{ //v3.0
  var i,j=0,x,a=MM_swapImage.arguments;	document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function MM_showHideLayers() { //v3.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if	((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v='hide')?'hidden':v; }
    obj.visibility=v; }
}

function popup(web_ventana,resx,resy,posx,posy,scroll)
{
	var ancho_interface=10
	var alto_interface=29	
	if ((posx==-1) && (posy==-1))
	{
		var tamx=screen.width;
		var tamy=screen.height;
		posx=(tamx-(resx+ancho_interface))/2;
		posy=(tamy -(resy+alto_interface))/2;
	}
	
	var inicioNombre = web_ventana.lastIndexOf('/')+1;
	var nombre_ventana = web_ventana.substring(inicioNombre,web_ventana.lastIndexOf('.'));
		
	var cadena_opciones="width=" + resx + ",height=" + resy + ",left=" + posx + ",top=" + posy +((scroll)?",scrollbars=yes":"");
	var vent= window.open(web_ventana,nombre_ventana,cadena_opciones);
}

function goToHome(){
	parent.location.href='/privado/inicio.aspx';
}
function P7_ReDoIt() { //v1.21 by PVII
 if(document.layers) {MM_reloadPage(false);}
}
function P7_Snap() { //v2.62 by PVII
try
{
  var x,y,ox,bx,oy,p,tx,a,b,k,d,da,e,el,args=P7_Snap.arguments;a=parseInt(a);
  for (k=0; k<(args.length-3); k+=4)
   if ((g=MM_findObj(args[k]))!=null) {
    el=eval(MM_findObj(args[k+1]));
    a=parseInt(args[k+2]);b=parseInt(args[k+3]);
    x=0;y=0;ox=0;oy=0;p="";tx=1;da="document.all['"+args[k]+"']";
    if(document.getElementById) {
     d="document.getElementsByName('"+args[k]+"')[0]";
     if(!eval(d)) {d="document.getElementById('"+args[k]+"')";if(!eval(d)) {d=da;}}
    }else if(document.all) {d=da;} 
    if (document.all || document.getElementById) {
     while (tx==1) {p+=".offsetParent";
      if(eval(d+p)) {x+=parseInt(eval(d+p+".offsetLeft"));y+=parseInt(eval(d+p+".offsetTop"));
      }else{tx=0;}}
     ox=parseInt(g.offsetLeft);oy=parseInt(g.offsetTop);var tw=x+ox+y+oy;
     if(tw==0 || (navigator.appVersion.indexOf("MSIE 4")>-1 && navigator.appVersion.indexOf("Mac")>-1)) {
      ox=0;oy=0;if(g.style.left){x=parseInt(g.style.left);y=parseInt(g.style.top);
      }else{var w1=parseInt(el.style.width);bx=(a<0)?-5-w1:-10;
      a=(Math.abs(a)<1000)?0:a;b=(Math.abs(b)<1000)?0:b;
      x=document.body.scrollLeft + event.clientX + bx;
      y=document.body.scrollTop + event.clientY;}}
   }else if (document.layers) {x=g.x;y=g.y;var q0=document.layers,dd="";
    for(var s=0;s<q0.length;s++) {dd='document.'+q0[s].name;
     if(eval(dd+'.document.'+args[k])) {x+=eval(dd+'.left');y+=eval(dd+'.top');break;}}}
   if(el) {e=(document.layers)?el:el.style;
   var xx=parseInt(x+ox+a),yy=parseInt(y+oy+b);
   if(navigator.appName=="Netscape" && parseInt(navigator.appVersion)>4){xx+="px";yy+="px";}
   if(navigator.appVersion.indexOf("MSIE 5")>-1 && navigator.appVersion.indexOf("Mac")>-1){
    xx+=parseInt(document.body.leftMargin);yy+=parseInt(document.body.topMargin);
    xx+="px";yy+="px";}e.left=xx;e.top=yy;}}
}catch(e)
{
	//Se ha puesto este try catcha pq en ocasiones se producía un error javascript al hacer postback con las listas.
}
}
function fechamayor(fecha,fech){

/*************************************************************************/

// Devuelve true si la segunda fecha es mayor que la primera. False en caso contrario

/*************************************************************************/


if (fecha!=fech){

//Comprobar q no sea mayor q la fecha actual 

fecha2=fecha.split("/");

fech2=fech.split("/");

if (fecha2[2]<=fech2[2]){

if (fecha2[2]==fech2[2]){

if (fecha2[1]<=fech2[1]){

if (fecha2[1]==fech2[1]){

if (fecha2[0]<=fech2[0]){

return true;

}else{

//alert('fecha de fin');

return false;

}

}else{

return true;

}

}else{

//alert('La fecha ');

return false;

}

}else{

return true;

}

}else{

//alert('o no puede ser mayor q');

return false;

} 

}else{ // si es la misma fecha ...

return true;

}


return true;

}


/*Funcion que valida la fecha insertada en un texbox y le da formato.
	Si se le pasan los parámetros descripcion (string) y DivFecha(objeto de tipo label o una capa)
	Se mostrará el mensaje de error en dicha capa y devolverá true o false dependiendo de si es válida la fecha.
	Si no se le envían estos parámetros simplemente devolverá true o false.
*/

function ValidaTextBoxFecha(txtFecha, Descripcion, divFecha,alerta)
	{
		txtFecha.value=Trim(txtFecha.value);
		while (txtFecha.value.indexOf(".")>=0)
		{
			txtFecha.value=txtFecha.value.replace(".","/");
		}
		var strFecha=txtFecha.value;
		
		if ((strFecha.indexOf("/")<0) && (!isNaN(parseInt(strFecha,10))))
		{
			var sFechaFormato="";
			for (i=0;i<strFecha.length;i++)
			{
				if ((i==2) || (i==4))
					sFechaFormato+="/"
				sFechaFormato += strFecha.charAt(i);
				
			}
			txtFecha.value=sFechaFormato;
		}
		
		
		var fechaValida=EsFechaValida(txtFecha.value);
		
		if ((!Descripcion) || (Descripcion==""))
			Descripcion="Fecha";
			
		if (!fechaValida)
		{
		
			if (txtFecha.value!="")
			{
				if (divFecha)
				{
					divFecha.innerHTML="La " + Descripcion + " no es correcta";
					divFecha.className="mensajeError";
					divFecha.style.visibility="visible";
				}
				if(alerta)
				{
					alert("La " + Descripcion + " no es correcta");
				}
				if ((divFecha) || (alerta))
				{
					try
					{
						txtFecha.focus();
						txtFecha.select();
					}catch(e)
					{
						txtFecha.value="";
						divFecha.style.visibility="hidden";
					}
				}
			}else
			{
				if (divFecha)
					divFecha.style.visibility="hidden";
				
			}	
			
			return false;
		}
		
		
		if (divFecha)
			divFecha.style.visibility="hidden";
		var partesFecha=txtFecha.value.split("/");
		var diasMes=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
		
		for (i=0;i<=1;i++)
		{
			if (partesFecha[i].length==1)
				partesFecha[i]="0" + partesFecha[i];
		}		
		
		if (partesFecha[2].length==1)
		{
			var decadaActual=new Date();
			decadaActual=decadaActual.getFullYear().toString().charAt(2);
			partesFecha[2]=decadaActual + partesFecha[2];
		}
		
		if (partesFecha[2].length==2)
			partesFecha[2]="20" + partesFecha[2];
		txtFecha.value=partesFecha[0] + "/" + partesFecha[1] + "/" + partesFecha[2];
		//Si es bisiesto ponemos 29 días en febrero
		var year=parseInt(partesFecha[2],10);
		var esBisiesto=EsAnioBisiesto(year)
		if (esBisiesto)
		{
			diasMes[1]=29;
		}
		
		if ((parseInt(partesFecha[0],10)>diasMes[parseInt(partesFecha[1],10)-1]))
		{
			if (divFecha)
			{
				divFecha.innerHTML="La " + Descripcion + " no es correcta. El mes solo tiene " + diasMes[parseInt(partesFecha[1],10)-1] +" d&iacute;as." ;
				divFecha.className="mensajeError";
				divFecha.style.visibility="visible";
			}
			if(alerta)
			{
				alert("La " + Descripcion + " no es correcta. El mes solo tiene " + diasMes[parseInt(partesFecha[1],10)-1] +" dias.");
			}
			if ((divFecha) || (alerta))
			{
				try
				{
					txtFecha.focus();
					txtFecha.select();
				}catch(e)
				{
					txtFecha.value="";
					divFecha.style.visibility="hidden";
				}
			}
			return false;
		}
		return true;
		
	}
	
	function EsAnioBisiesto(year)
	{
		return (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) ? 1 : 0;
	}
function EsFechaValida(fecha)
{
	var patron=/^((0{0,1}[1-9])|(1\d|2\d|3[0,1]))\/(0{0,1}[1-9]|1[0-2])\/((\d{1,2})|([1,2]\d{3}))$/;
	var fechaValida=false;
	if (fecha.search(patron)<0)
		fechaValida=false;
	else
		fechaValida=true;
	return fechaValida;
	
}

function ValidaTextBoxHora(txtHora, Descripcion, divHora,alerta)
{
	txtHora.value=Trim(txtHora.value);
	while (txtHora.value.indexOf(".")>=0)
	{
		txtHora.value=txtHora.value.replace(".",":");
	}
	while (txtHora.value.indexOf(",")>=0)
	{
		txtHora.value=txtHora.value.replace(",",":");
	}
	var strHora=txtHora.value;
	if ((strHora.indexOf(":")<0) && (!isNaN(parseInt(strHora,10))))
	{
		
		var strCeros="";
		while (strHora.indexOf("0")==0)
		{
			strCeros+="0"
			strHora=strHora.replace("0","");
		}
		if (strHora!="")
			strHora=String(parseInt(strHora,10));
			
		if (strCeros!="")
			strHora=strCeros +strHora;
			
			
		var sHoraFormato="";
		for (i=0;i<strHora.length;i++)
		{
			if ((i==2) || (i==4))
				sHoraFormato+=":"
			sHoraFormato += strHora.charAt(i);
			
		}
		txtHora.value=sHoraFormato;
		
	}
	//alert(txtHora.value.lastIndexOf(":") + ", " + txtHora.value.length);
	if (txtHora.value.lastIndexOf(":")==txtHora.value.length-1)
		txtHora.value=txtHora.value.substring(0,txtHora.value.length-1);
	var HoraValida=EsHoraValida(txtHora.value)
	if(!Descripcion)
		Descripcion="Hora";
	if (!HoraValida)
	{
		if (txtHora.value!="")
		{
			if (divHora)
			{
				divHora.innerHTML="La " + Descripcion + " no es correcta.";
				divHora.className="mensajeError";
				divHora.style.visibility="visible";
			}
			if(alerta)
			{
				alert("La " + Descripcion + " no es correcta.");
			}
			if((divHora)||(alerta))
			{
				txtHora.focus();
				txtHora.select();
			}
		}else
		{
			if (divHora)
				divHora.style.visibility="hidden";
		}	
				
		return false;
	}
	
	if (divHora)
			divHora.style.visibility="hidden";
	//colocamos bien las horas
	var partesHora=txtHora.value.split(":")
	if (partesHora[0].length==1)
		partesHora[0]="0" + partesHora[0];
		
	if (partesHora.length==1)
		partesHora[1]="00";
	else
		if (partesHora[1].length==1)
			partesHora[1]="0" + partesHora[1];
	if (partesHora.length==2)
		partesHora[2]="00";
	else
		if (partesHora[2].length==1)
			partesHora[2]="0" + partesHora[2];
				
	txtHora.value=partesHora[0] + ":" + partesHora[1] + ":" + partesHora[2];

	return true;
	
}

function EsHoraValida(hora)
{
	var patron=/^((0{0,1}\d)|(1\d|2[0-3])):(0{0,1}\d|[1-5]\d):(0{0,1}\d|[1-5]\d)$/;
	var patronSinSegundos=/^((0{0,1}\d)|(1\d|2[0-3])):(0{0,1}\d|[1-5]\d)$/;
	var patronSinMinutos=/^((0{0,1}\d)|(1\d|2[0-3]))$/;
	var horaValida=false;
	if (hora.search(patron)<0)
	{
		if (hora.search(patronSinSegundos)<0)
		{
			if (hora.search(patronSinMinutos)<0)
				horaValida=false
			else
				horaValida=true;
		}
		else
			horaValida=true;
	}	
	else
		horaValida=true;
		
		
	
	return horaValida;
	
}

function stringToDate(fecha)
		{
			if (EsFechaValida(fecha))
			{
				
				var sFecha=fecha.split("/");
				if (sFecha.length==3)
				{
					sFecha=new Date(sFecha[2],sFecha[1],sFecha[0]);
					return sFecha;
				}else 
					return false;
				
			}else
				return;
		}
	
/*Funcion que valida si la fecha de inicios es menor ó igual que la fecha de fin
si es así entonces devuelve true.
en caso contrario devuelve false.
*/

function FechaInicioMenorFechaFin(fechainicio,fechafin)
		{
			var fechaI=fechainicio.split("/");
			var fechaF=fechafin.split("/");
			var decadaActual=new Date();
			decadaActual=decadaActual.getFullYear().toString().charAt(2);
			
			if (fechaI[2].length==1)
				fechaI[2]="" + decadaActual + fechaI[2];
			
			if (fechaF[2].length==1)
				fechaF[2]="" + decadaActual + fechaF[2];
			
			if (fechaI[2].length==2)
				fechaI[2]= "20" + fechaI[2];
			if (fechaF[2].length==2)
				fechaF[2]= "20" + fechaF[2];
			
			var esmenor=false;
			for (i=2;i>=0;i--)
			{
				
				var ValorInicio=parseInt(fechaI[i],10);
				var ValorFin=parseInt(fechaF[i],10);
				if (ValorInicio<ValorFin)
				{
					esmenor=true;
					break;
				}
				else
					if (ValorInicio>ValorFin)
					{
						esmenor=false;
						break;
					}
					else
						esmenor=true;
								
			}
				
			if (esmenor)
				return true;
			else
				return false;
			

		}

function HoraInicioMenorHoraFin(HoraInicio,HoraFin)
	{
		var HoraI=HoraInicio.split(":");
		var HoraF=HoraFin.split(":");
		var esmenor=false;
		for (i=0;i<=2;i++)
		{
			
			var ValorInicio=parseInt(HoraI[i],10);	
			var ValorFin=parseInt(HoraF[i],10);
			if (ValorInicio<ValorFin)
			{
				esmenor=true;
				break;
			}
			else
				if (ValorInicio>ValorFin)
				{
					esmenor=false;
					break;
				}
				else
					esmenor=true;
							
		}
			
		if (esmenor)
			return true;
		else
			return false;
		

	}
	
	//Con esta función se validarán los datos de las fechas de un formulario en el que haya que introducir un intervalo
	//las horas de inicio y fin son opcionales.
	//Esta función óptima para ponerla en el evento onclick de un link que necesita validar los datos.
function ValidaTextBoxIntervaloFechas(txtFechaInicio,txtFechaFin, txtHoraInicio,txtHoraFin)
	{
		var descripcionFechaInicio="Fecha de Inicio";
						
		var descripcionFechaFin="Fecha de Fin";
		
		if (txtFechaInicio.value=="")
		{
			alert("Introduzca una " + descripcionFechaInicio);
			return false;
		}
		
		if (txtFechaFin.value=="")
		{
			alert("Introduzca una " + descripcionFechaFin);
			return false;
		}
		
		if (!ValidaTextBoxFecha(txtFechaInicio,descripcionFechaInicio,null,true))
		{
			return false;
		}
		
		if (!ValidaTextBoxFecha(txtFechaFin,descripcionFechaFin,null,true))
		{
			return false;
		}
		
		if (!FechaInicioMenorFechaFin(txtFechaInicio.value,txtFechaFin.value))
		{
			alert("La " + descripcionFechaInicio +" debe ser menor a la " + descripcionFechaFin);
			return false;
		}
		
		//Si se envían las horas también
		if (txtHoraInicio && txtHoraFin)
		{
			var descripcionHoraInicio="Hora de Inicio";
			var descripcionHoraFin="Hora de Fin";
			
			if (txtHoraInicio.value=="")
			{
				alert("Introduzca una " + descripcionHoraInicio );
				return false;
			}
			
			if (txtHoraFin.value=="")
			{
				alert("Introduzca una " + descripcionHoraFin);
				return false;
			}
			
			if (!ValidaTextBoxHora(txtHoraInicio,descripcionHoraInicio,null,true))
			{
				return false;
			}
			
			if (!ValidaTextBoxHora(txtHoraFin,descripcionHoraFin,null,true))
			{
				return false;
			}
			
			if (txtFechaInicio.value==txtFechaFin.value)
			{
				if (!HoraInicioMenorHoraFin(txtHoraInicio.value,txtHoraFin.value))
				{
					alert("La " + descripcionHoraInicio + " debe ser menor a la " + descripcionHoraFin);
					return false;
				}
			}
			
		}
		
		return true;
	}

function MostrarMiles(donde,caracter){

valor = donde.value
largo = valor.length
valorEntero='';
 for(m=0;m<largo;m++){
    if(valor.charAt(m) == "," ) 
		{
		break;
		}else
		{
		valorEntero+=valor.charAt(m);
		}
 }
 decimales='';
for(m;m<largo;m++){
    decimales+=valor.charAt(m);
 }

donde.value=AplicarMiles(valorEntero,valorEntero.length)+ decimales;


} 
function AplicarMiles(valor,largo)
{
crtr = true
 cont = 0
 var nums = new Array()
  for(m=0;m<largo;m++){
     if(valor.charAt(m) == "." || valor.charAt(m) == " "){
      continue;
      }
    else{
      nums[cont] = valor.charAt(m)
      cont++
      }
   }
   for(m=largo;m<valor.length;m++){
   nums[cont]=valor.charAt(m);
   cont+=1;
   }
   
//}

var cad1="",cad2="",tres=0
if(largo > 3 && crtr == true){
   for (k=nums.length-1;k>=0;k--){
     cad1 = nums[k]
     cad2 = cad1 + cad2
     tres++
     if((tres%3) == 0){
        if(k!=0){
          cad2 = "." + cad2
          }
        }
      }
valor = cad2

  }
    return valor;
}

function Trim(cadena){
			if (cadena!="")
			{
				cadena=cadena.replace(/^\s+/,'');
				if (cadena!="")
					cadena=cadena.replace(/\s+$/,'');
			}
			return(cadena);
}


//funciones para poner y quitar el formato de Miles

//pone el formato a una cadena
function PonerMarcadorMiles(Cadena,numeroDecimales,caracterDecimal)
{
	//alert(Cadena)
	if (isNaN(parseInt(Cadena,10)))
		return Cadena;
	
	var cDecimal=",";
	var cMiles=".";
	if (caracterDecimal==".")
	{
	    cDecimal=".";
	    cMiles=",";
	}
	//Si es un número lo convertimos a cadena;
	Cadena=Trim(String(Cadena));
	
	//si tiene parte decimal la separamos
	var decimales="";
	var Signo="";
	//comprobamos si tiene signo:
	if (Cadena.lastIndexOf("-")==0)
	{
		Signo="-"
		Cadena=Cadena.replace("-","");
	}
	
	if (Cadena.lastIndexOf(cDecimal)>=0)
	{
		var PartesCadena=Cadena.split(cDecimal);
		Cadena=PartesCadena[0];
		/*if (Cadena=="-0")
		{
			Signo="-"
		}*/
		Cadena="" + parseInt(Cadena,10);
					
		//decimales="" + parseInt(PartesCadena[1],10);
		decimales=PartesCadena[1]
		
		if (isNaN(parseInt(decimales)))
			decimales="";
	}
	else
	{
		Cadena="" + parseInt(Cadena,10);
		
	}
	var CadMiles="";
	
	for (i=0; i<Cadena.length;i++)
	{
		var ultimaPos=Cadena.length-i-1;
		//alert("ultima Pos: " + ultimaPos + "=" + (ultimaPos % 3));
		if ((i>=3) &&(i % 3==0))	
		{
			//alert("entra");
			CadMiles =cMiles + CadMiles;
		}
		CadMiles=Cadena.charAt(ultimaPos)+ CadMiles;
		
	}
	
	

	//ponemos los decimales indicados
	if (!isNaN(parseInt(numeroDecimales,10)))
	{
		if (numeroDecimales>0)
		{
			if (decimales.length<numeroDecimales)
			{
				//ponemos los decimales
				for (i=decimales.length;i<numeroDecimales;i++)
					decimales +="0";
				if (decimales!="")
					CadMiles=Signo + CadMiles+ cDecimal + decimales
			}
			else
			{
				
				//redondeamos
				if (decimales.length>numeroDecimales)
				{
					//alert(decimales.toString());
					
					decimales=decimales.toString().substring(0,numeroDecimales);
					
				}
				if ((!isNaN(decimales)) && (decimales!=""))
				{
					CadMiles=Signo + CadMiles+ cDecimal + decimales
				}
			}
		}
	}else{
		if (decimales!="")
		{
			CadMiles=Signo + CadMiles+ cDecimal + decimales
		}
	}	
		
	return CadMiles;
	
}
//Quita el formato a una cadena
function QuitarMarcadorMiles(Cadena,caracterDecimal)
{
    var cDecimal=",";
	var cMiles=".";
	if (caracterDecimal==".")
	{
	    cDecimal=".";
	    cMiles=",";
	}
	if (isNaN(parseInt(Cadena,10)))
		return Cadena;
	Cadena=""+Cadena;
	//alert(Cadena);
	var NuevaCadena="";
	do
	{
		Cadena=Cadena.replace(cMiles,"");
	}while (Cadena.indexOf(cMiles)>=0)
	NuevaCadena=Cadena;
	
	//alert(NuevaCadena);
	return NuevaCadena;
}			


//Formatea el valor de un Objeto
function FormateaMiles(obj,numeroDecimales,caracterDecimal)
{
	txtFormato=obj;
	//	alert(this.name);
	if (txtFormato.value)
	{
		//txtFormato.value=QuitarMarcadorMiles(txtFormato.value);
		txtFormato.value=PonerMarcadorMiles(QuitarMarcadorMiles(txtFormato.value,caracterDecimal),numeroDecimales,caracterDecimal);
		
	}
}

function QuitarFormato(obj,caracterDecimal)
{
	obj.value=QuitarMarcadorMiles(obj.value,caracterDecimal);
}


function SoloNumeros()
{
    //alert(event.keyCode);
    
            //48- 0
            //49- 1
            //57- 9
            //13- Intro
            //46- .
            //44- ,
            
    var keys=[44,46,48,49,50,51,52,53,54,55,56,57];
    var i=0;
    while (i<keys.length)
    {
        if (keys[i]==event.keyCode)
        {
            return true;
        }
        i++;
    }
    return false;
    
    //alert(keys.length);
    
    
    
}

function PegarNumeros()
{
    try
    {
        var datosCopiados=clipboardData.getData('text');
        if(!isNaN(parseInt(datosCopiados)))
        {
            return true;
        }
        return false;
    }catch(e)
    {
        return false;
    }
}


//Funcion que Establece la hora
function MueveReloj(){
	var momentoActual = new Date();
	hora = momentoActual.getHours();
	minuto = momentoActual.getMinutes();
	segundo = momentoActual.getSeconds();
	
	if(minuto<10){
		minuto="0" + minuto;
	}
	
	if(hora<10){
		hora="0" + hora;
	}
	
	if(segundo<10){
		segundo="0" + segundo;
	}
	
	horaImprimible = hora + ":" + minuto + ":" + segundo;
	//fechaImprimible = dia + "/" + mes + "/" + anno;
	return horaImprimible;

}

function CalculaDiferenciaHoraria(HoraInicio,HoraFin)
{
	//HoraInicio="00:00:00"
	//HoraFin="00:00:59";
	
	
	if (!HoraInicioMenorHoraFin(HoraInicio,HoraFin))
	{
		var aux;
		aux=HoraInicio;
		HoraInicio=HoraFin;
		HoraFin=aux;
	}
	var diferencia;
	var hoy=new Date();
	var inicio=HoraInicio.split(":");
	var segundos;
	if (inicio.length<3)
		segundos=0;
	else
		segundos=parseInt(inicio[2],10);
	
	//var hInicio=new Date(hoy.getFullYear(),hoy.getMonth(),hoy.getDate(),parseInt(inicio[0],10),parseInt(inicio[1],10),segundos);

		
	var fin=HoraFin.split(":");
	var segundosFin;
	if (fin.length<3)
		segundosFin=0;
	else
		segundosFin=parseInt(fin[2],10);
	
	//var hFin=new Date(hoy.getFullYear(),hoy.getMonth(),hoy.getDate(),parseInt(fin[0],10),parseInt(fin[1],10),segundosFin);
	//diferencia=(hFin.getTime()- hInicio.getTime());
	
	hDiferencia=new Date(diferencia)
	hDiferencia=new Date(hoy.getFullYear(),hoy.getMonth(),hoy.getDate(),parseInt(fin[0],10)-parseInt(inicio[0],10),parseInt(fin[1],10)-parseInt(inicio[1],10),segundosFin-segundos);
	
	return FormatoHora(hDiferencia, "hh:mm:ss");

	
	
	
}

function IniciarReloj(objeto,objDiferencia,objInicio, objFin)
{
	var intervalo;
	
	var propiedad;
	//comprobamos si es un textbox o una label
	if (objeto.value)
	{
		propiedad="value";
	}else 
		propiedad="innerHTML"
		
	
	if (objDiferencia)
	{
		var propiedadDiferencia;
		/*if (objDiferencia.value)
		{
			propiedadDiferencia="value";
		}else
			propiedadDiferencia="innerText";
		*/
		
		var sObj="document.getAspElementById(\'" + objeto.id + "\')." + ((objeto.value)? "value":"innerText");
		var sObjDiferencia="document.getAspElementById(\'" + objDiferencia.id + "\')." + ((objDiferencia.value)? "value":"innerText");
		var sObjInicio="document.getAspElementById(\'" + objInicio.id + "\')." + ((objInicio.value)? "value":"innerText");
		var sObjFin="document.getAspElementById(\'" + objFin.id + "\')." + ((objFin.value)? "value":"innerText");
		
		//window.setTimeout(sObjDiferencia +"=CalculaDiferenciaHoraria("+ sObjInicio+","+sObjFin+")",1);
		eval(sObj+ "=MueveReloj();" +sObjDiferencia +"=CalculaDiferenciaHoraria("+ sObjInicio+","+sObjFin+")");
		intervalo=window.setInterval(sObj+ "=MueveReloj();" +sObjDiferencia +"=CalculaDiferenciaHoraria("+ sObjInicio+","+sObjFin+")",1000)
		
	}
	else
	{
		intervalo=window.setInterval("document.getAspElementById(\'" + objeto.id + "\')." + propiedad + "=MueveReloj()",1000)	
	}
	
	
	
	return intervalo;
}

function PararReloj(intervalo)
{
	window.clearInterval(intervalo);
}


function FormatoHora(fecha,formato)
{
	var horas;
	var minutos;
	var segundos;
	
	
	if(typeof(fecha)=="string")
	{
		var tFecha=fecha.split(":");
		horas=parseInt(tFecha[0],10);
		minutos=parseInt(tFecha[1],10);
		if (tFecha.length>=3)
		{
			segundos=parseInt(tFecha[2],10);
		}else
		{
			segundos=0;
		}
		
	}
	else
	{
		horas=fecha.getHours();
		minutos=fecha.getMinutes();
		segundos=fecha.getSeconds();
	}
	
		
	
	if (horas<10)
		horas= "0" + String(horas);
		
	if (minutos<10)
		minutos= "0" + String(minutos);
	
	if (segundos<10)
		segundos= "0" + String(segundos);	
	
	formato=formato.toLowerCase();
	return formato.replace("hh",horas).replace("mm",minutos).replace("ss",segundos);
}


/******************************************
Funciones para TAMAÑO Y POSICION DEL POPUP
*******************************************/

function MaximizaPopup()
{   
    var tblGlobalnetPopup=document.getAspElementById("tblGlobalnetPopup");
    var ancho=screen.availWidth-1;
	var alto=screen.availHeight-1;
	//top.window.resizeTo(ancho, alto);
	top.window.resizeTo(ancho,alto)
	//alert(document.body.clientHeight);
	//alert(document.documentElement.clientHeight);
	//top.window.resizeBy(10,-100)
	window.moveTo(1,1);
	
	/*if (!window.opener)
	{
	    //añadimos el alto de las barras de herramientas
	    alto-=264;
		//alto+=16;
		//ancho+=4;
	
	}else
	{
	    //ancho+=2;
	    alto-=105;
	}
	*/
	//alert(document.documentElement.scrollTop);
	alto=document.documentElement.clientHeight-26;
	//if (document.getAspElementById(""))
	var imgCabeceraVisible=document.getAspElementIdFromParent("imgCabeceraVisible","ctl00");
	
	//alert(document.getElementById("ctl00_imgCabeceraVisible"));
	if (imgCabeceraVisible)
	{
	    var tblCabeceraPopup=document.getAspElementById("tblCabeceraPopup");
	    alto-=tblCabeceraPopup.clientHeight;
	}
		    
	tblGlobalnetPopup.style.height=alto-1;
	
	var divDatosPopup=document.getAspElementById("divDatosPopup");
	var celdaDatos=document.getAspElementById("tblGlobalnetPopup_CeldaDatos");
	
	divDatosPopup.style.height=parseInt(celdaDatos.clientHeight)-40;
	
	divDatosPopup.style.width=parseInt(celdaDatos.clientWidth)-24;
}


function CentrarVentana()
{
    try
    {
    var cuerpo=null;
    
    cuerpo=document.body;
    
    var anchoVentana=cuerpo.clientWidth
    var altoVentana=cuerpo.clientHeight;
    var anchoPantalla=parseInt(screen.availWidth)-1;
    var altoPantalla=parseInt(screen.availHeight)-1;
    var izquierda=((anchoPantalla-anchoVentana)/2)
    var arriba=((altoPantalla-altoVentana)/2)
    window.moveTo(izquierda,arriba);
    window.focus();
    }
    catch(e)
    {
        //alert(e.message);
    }
}



function RedimensionaPopup()
{
    var tblGlobalnetPopup=document.getAspElementById("tblGlobalnetPopup");
    var ancho=tblGlobalnetPopup.offsetWidth;
    var alto=tblGlobalnetPopup.offsetHeight;
    
    //añadimos 24 para que se añada al alto de la ventana la barra de título.
	alto+=36;
	
	//añadimos 10 para los bordes de la ventana a lo ancho
	ancho+=8;
	if (!window.opener)
	{
	    //añadimos el alto de las barras de herramientas
	    alto+=100;
		alto+=16;
		ancho+=4;
	
	}else
	{
	    ancho+=2;
	    //añadimos el alto de la barra de direcciones.
	    //alto+=32;
	}
		
	//comprobamos si la ventana tiene barras de Herramientas
	//si es así la redimensionamos a lo mínimo
	//si el alto de la ventana es mucho mayor al alto del body;
		
	
	if ((ancho=="100%") && (alto=="100%"))
	{
	        var ancho=screen.availWidth-10;
			var alto=screen.availHeight-10;
			top.window.resizeTo(ancho, alto);
			window.moveTo(10,10);
	}else
	{
	    //alto-=7; //para el estilo Clásico.
		top.window.resizeTo(ancho, alto);	
		
		//comprobamos si tiene mostrada la barra de desplazamiento.
		altoDocumento=parseInt(document.body.clientHeight);
	    altoVentana=parseInt(document.documentElement.clientHeight);
	    //alert(document.body.clientHeight)
	    //alert(document.documentElement.clientHeight);
	    
	    if (altoDocumento>=altoVentana)
	    {
	        alto+=23;
	        top.window.resizeTo(ancho,alto)
	    }
	}
 
}

/******************************************
Funciones para Outlook
*******************************************/
function AgregarContactoOutlook(nombre, correoElectronico, organizacion, cargo, telefonoTrabajo)
{
    try
    {
        if (confirm("¿Desea agregar a '" + nombre + "' a los contactos de Outlook ?"))
        {
            var Const_olFolderContacts = 10;
            var objApp = new ActiveXObject("Outlook.Application");
            var objNS = objApp.GetNamespace("MAPI");
            var colContacts = objNS.GetDefaultFolder(Const_olFolderContacts).Items
            var objContact=colContacts.Add();
            var i=1;
            
            if (correoElectronico!="")
            {
                while(i<=colContacts.count)
                {
                    var contacto=colContacts.item(i)
                    //contacto.name="adfasds";
                    if ((contacto["Email1Address"]!=null) && (contacto["Email1Address"].toLowerCase()== correoElectronico.toLowerCase()))
                    {
                        
                        if (confirm("Ya existe un contacto con el correo electrónico " + contacto["Email1Address"] + " en la libreta de direcciones de Outlook.\n¿Desea acceder a los datos guardados?"))
                        {
                            contacto.Display();
                        }
                        return;
                    }
                    i++;
                }
            }
            
            with(objContact)
            {
                FullName=nombre;
                CompanyName=organizacion;
                JobTitle=cargo;
                Email1Address=correoElectronico;
                //Email1DisplayName="Javier Recio Garcia (j.recio@eurodivisas.com)";
                //Department="Tecnología y Desarrollo";
                
                BusinessTelephoneNumber=telefonoTrabajo;
            }
            objContact.Display();
        }
   } 
    catch(e)
    {
        //alert(e.message);
    }
}

/*Agrega los días al Outlook
se ha de enviar un objeto con los siguientes datos
var a = {{'November 24, 2005','Ferias y fiestas'}, 
    {'November 25, 2005','Dia de fiesta'}
}
*/

function CitaOutlook(fecha, asunto, descripcion, ubicacion) {
    this.asunto = asunto;
    this.cuerpo = descripcion;
    this.fechaInicio = fecha;
    this.ubicacion = ubicacion;
}

function CitaOutlookHora(fechainicio, fechafin, asunto, descripcion, ubicacion) {
    this.fechaInicio = fechainicio;
    this.fechaFin = fechafin;
    this.asunto = asunto;
    this.cuerpo = descripcion;
    this.ubicacion = ubicacion;
}

function ObtenerCalendarioOutlook(objOutlookCalendar, nombreCalendario) {

    var i = 0;
    var calendarioNuevo = null;

    while ((i < objOutlookCalendar.Folders().Count) && (calendarioNuevo == null)) {
        var folder = objOutlookCalendar.Folders(i + 1);
        if (folder.Name == nombreCalendario)
            calendarioNuevo = folder;
        i++;
    }

    if (calendarioNuevo == null) {
        calendarioNuevo = objOutlookCalendar.Folders.Add(nombreCalendario);
    }

    return calendarioNuevo;

}

function AgregarCitaCalendarioOutlook(dias, nombreCalendario) {

        var olFolderCalendar = 9;
        var olAppointmentItem = 1;
        var olOutOfOffice = 3;

        var objOutlook = new ActiveXObject("Outlook.Application");
        var objNamespace = objOutlook.GetNamespace("MAPI");
        var objCalendar = objNamespace.GetDefaultFolder(olFolderCalendar);

        var calendarioAplicacion = ObtenerCalendarioOutlook(objCalendar, nombreCalendario);
        

        var i = 0;

        while (dias[i]) {
            var cita = dias[i];
            var filter1 = "[Start] = '" + cita.fechaInicio + " 00:00 AM" + "' AND [Subject] = '" + cita.asunto + "'";
            var mItemCollection = calendarioAplicacion.Items.Restrict(filter1);
            if (mItemCollection.count==0)
            {
                if (document.OcultarMensajesAplicacionesAbiertos)
                    document.OcultarMensajesAplicacionesAbiertos();

                //'," & tiempo & "," & ancho & "," & alto & ",""mensajeAplicacion""
                var objHoliday = calendarioAplicacion.Items.Add(olAppointmentItem);
                objHoliday.AllDayEvent = true
                objHoliday.Subject = cita.asunto;
                objHoliday.Body = cita.cuerpo;
                objHoliday.Location = cita.ubicacion;
                objHoliday.Start = cita.fechaInicio + " 00:00 AM"
                //objHoliday.End = cita.fechaInicio + " 23:59 PM"
                
                objHoliday.ReminderSet = true
                
                objHoliday.ReminderMinutesBeforeStart = 24*60*7;
                objHoliday.Save()
            }
            i++;
        }

        //Mostramos la aplicación

        objCalendar.Display();
        var myExplorer = objOutlook.ActiveExplorer;
        myExplorer.SelectFolder(calendarioAplicacion);
        myExplorer.CurrentFolder.Display();
    }

    function AgregarCitaCalendarioOutlookHora(dias, nombreCalendario, notificacion) {
        var olFolderCalendar = 9;
        var olAppointmentItem = 1;
        var olOutOfOffice = 3;

        var objOutlook = new ActiveXObject("Outlook.Application");
        var objNamespace = objOutlook.GetNamespace("MAPI");
        var objCalendar = objNamespace.GetDefaultFolder(olFolderCalendar);

        var calendarioAplicacion = objCalendar;
        if (nombreCalendario)
            calendarioAplicacion = ObtenerCalendarioOutlook(objCalendar, nombreCalendario);

        var i = 0;

        while (dias[i]) {
            var cita = dias[i];
            var filter1 = "[Start] = '" + cita.fechaInicio + "' AND [Subject] = '" + cita.asunto + "'";
            var mItemCollection = calendarioAplicacion.Items.Restrict(filter1);
            if (mItemCollection.count == 0) {
                if (document.OcultarMensajesAplicacionesAbiertos)
                    document.OcultarMensajesAplicacionesAbiertos();

                var objHoliday = calendarioAplicacion.Items.Add(olAppointmentItem);
                objHoliday.AllDayEvent = false
                objHoliday.Subject = cita.asunto;
                objHoliday.Body = cita.cuerpo;
                objHoliday.Location = cita.ubicacion;
                objHoliday.Start = cita.fechaInicio
                objHoliday.End = cita.fechaFin
                objHoliday.ReminderSet = true
                
                if (notificacion)
                    objHoliday.ReminderMinutesBeforeStart = notificacion;
                else
                    objHoliday.ReminderMinutesBeforeStart = 24 * 60 * 7;
                objHoliday.Save()
            }
            i++;
        }


        //Mostramos la aplicación

        objCalendar.Display();
        var myExplorer = objOutlook.ActiveExplorer;
        myExplorer.SelectFolder(calendarioAplicacion);
        myExplorer.CurrentFolder.Display();
    }

/******************************************
Funciones para GOOGLE ANALITICS
*******************************************/
/*
function GoogleAnalytics()
{
	try
	{
		var direccionWeb=window.location.href.toLowerCase();
		if (direccionWeb.indexOf("https")<0)
		{
			//alert("Pagina http");
			ImportarJS("http://www.google-analytics.com/urchin.js?id="+Math.random());
		}else
		{
			//alert("Pagina https");
		}
		window.setTimeout("GoogleAnalyticsParameters();",2000);
	}catch(e)
	{	
	}
}

var GoogleAnalyticFailures=0;

function GoogleAnalyticsParameters()
{
	try
	{
		_uacct = idGoogleAnalytic;
		urchinTracker();
	}catch(e)
	{
		if (GoogleAnalyticFailures<3)
			window.setTimeout("GoogleAnalyticsParameters();",2000);
		GoogleAnalyticFailures+=1;
	}
}


function LanzaGoogleAnalytics()
{
	try
	{
		var direccionWeb=window.location.href.toLowerCase();

		if (!document.body)
			window.setTimeout("LanzaGoogleAnalytics()",2000);
		else
			GoogleAnalytics();
		
		
	}
	catch(e)
	{
		//alert(e.message)
		
	}
}
*/

function ImportarJS() {
	try
	{
 
		var argumentos = arguments.length;
		var archivoJS=document.createElement("script");
		archivoJS.setAttribute("type", "text/javascript");
		archivoJS.setAttribute("src", arguments[0]);
		if(argumentos>1){
			for (var i = 1; i<argumentos; i++){
				archivoJS.setAttribute(arguments[i][0], arguments[i][1]);
			}
		}
		document.getElementsByTagName("head")[0].appendChild(archivoJS);
	}catch(e)
	{
	}
}


//version Ajax
var idGoogleAnalytic="UA-1160980-3";
function GoogleAnalyticsByAjax()
{
	try
	{
		var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
		ImportarJS(gaJsHost + "google-analytics.com/ga.js?id="+Math.random());
		window.setTimeout("GoogleAnalyticsParametersByAjax();",2000);
	}catch(e)
	{	
	}
}

var GoogleAnalyticByAjaxFailures=0;
function GoogleAnalyticsParametersByAjax()
{
    try
	{
		var pageTracker = _gat._getTracker(idGoogleAnalytic);
        pageTracker._initData();
        pageTracker._trackPageview();
	}catch(e)
	{   
	    //realizamos tres intentos
	    if (GoogleAnalyticByAjaxFailures<3)
			window.setTimeout("GoogleAnalyticsParametersByAjax();",2000);
		GoogleAnalyticByAjaxFailures+=1;
	}
}

function LanzaGoogleAnalyticsByAjax()
{
    try
	{
		var direccionWeb=window.location.href.toLowerCase();

		if (!document.body)
			window.setTimeout("LanzaGoogleAnalyticsByAjax()",2000);
		else
			GoogleAnalyticsByAjax();
	}
	catch(e)
	{
	
	}
}


var GoogleAnalyticEventsByAjaxFailures=0;
function LanzaEventoGoogleAnalyticsByAjax(pagina)
{
    try
    {
        var pageTracker = _gat._getTracker(idGoogleAnalytic);
        if (pagina)
            pageTracker._trackPageview(pagina);
        else
            pageTracker._trackPageview();
         
    }catch(e)
    {
        if (GoogleAnalyticEventsByAjaxFailures<3)
        {
            GoogleAnalyticEventsByAjaxFailures +=1;
            if (pagina)
                window.setTimeout("LanzaEventoGoogleAnalyticsByAjax('" + pagina +"');",1000)
            else
                window.setTimeout("LanzaEventoGoogleAnalyticsByAjax();",1000)
        }
    }
}

LanzaGoogleAnalyticsByAjax();

//LanzaEventoGoogleAnalyticsByAjax();
