// cuenta atras

function cuenta_atras(capa,count,formato,tamanio,previo,tipo)
{
	count--; 
	if(previo==undefined)
		previo="";
	if(tipo==undefined)
		tipo=0;
		
	if(count>60)
		changelayer_content(capa,count,'#F5A10D',formato,tamanio,previo,tipo);
	else
		changelayer_content(capa,count,'red',formato,tamanio,"",tipo);
	
	if (count>0)
		Id = window.setTimeout("cuenta_atras('"+capa+"',"+count+","+formato+","+tamanio+",'"+previo+"',"+tipo+")",990); 
	else
		Recargar(1);

} 

function cuenta_adelante(capa,count,formato,tamanio,previo)
{
	count++; 
	changelayer_content(capa,count,'black',formato,tamanio,previo);
	
	if (count<=86499)
		Id = window.setTimeout("cuenta_adelante('"+capa+"',"+count+","+formato+","+tamanio+",'"+previo+"')",990); 
	else
		Recargar(1);
} 

function convierte_hora(counter,formato)
{
	aux_minutos=Math.floor(counter/60);
	horas=Math.floor(aux_minutos/60);
	minutos=aux_minutos%60;
	segundos=counter%60;
	
	if(horas<10)
		horas="0"+horas;
	if(minutos<10)
		minutos="0"+minutos;
	if(segundos<10)
		segundos="0"+segundos;

	if(formato==3)       // muestra todo
		msgstring=horas+":"+minutos+":"+segundos;
	else if(formato==2)  // solo muestra minutos y segundos
		msgstring=minutos+":"+segundos;
	else 		    // solo muestra segundos	
		msgstring=segundos;
	return 	msgstring;	
}	

function changelayer_content(capa,counter,color,formato,tam,previo,tipo)
{
	if(previo==undefined)
		previo="";
	if(tipo==1)	
		msgstring="<span style='font-color="+color+";font-size:"+tam+"pt;font-family:\"Kristen ITC\"'> "+previo+convierte_hora(counter,formato)+"</span>";
	else
	  msgstring="<FONT color="+color+" size="+tam+"> "+previo+convierte_hora(counter,formato)+"</Font>";
	
	var cuentalayer = document.getElementById(capa);
	cuentalayer.innerHTML =msgstring;
}

function Recargar(t)
{
  setTimeout('location.reload()', t);
}



function fila_on_off(f, st) {
	f.className = st;
}

function salir()
	{
		location="./index.php?salir=1";
	}



function fila_on_off(f, st) {
 f.className = st;
}

function VerOcultar(Bloque) {

  aux=document.getElementById(Bloque).style;
  if (aux.display == 'none')
    aux.display='block';
  else
    aux.display='none';
}



function marcar(nombreCapa)
{ 
	var Capa = document.getElementById(nombreCapa).style;
	Capa.backgroundColor = '#F7ABA1';
	//newImage = "url(tachado.jpg)";
        //Capa.backgroundImage = newImage;
} 

function quitar(nombreCapa)
{ 
	var Capa = document.getElementById(nombreCapa).style;
	Capa.backgroundColor = '#FFE4E3';
} 

function ChangeText(id, NewValue) 
{
	document.getElementById(id).innerHTML = NewValue;
	
}

function mostrar(nombreCapa)
{ 
	var Capa = document.getElementById(nombreCapa).style;
	if (Capa.display == 'none')
			Capa.display='block';
} 


function ocultar(nombreCapa)
{ 
	var Capa = document.getElementById(nombreCapa).style;
	if (Capa.display == 'block')
			Capa.display='none';
} 

function activar(nombreCapa)
{ 
	document.getElementById(nombreCapa).disabled=false;
} 

function desactivar(nombreCapa)
{ 
	document.getElementById(nombreCapa).disabled=true;
} 



function chk_email() {
	args = chk_email.arguments;
	errors = false;
	txt_error = "El email introducido no tiene un formato válido\n";
	fld_blink="";

	frm = args[0];

	for (var i=1; i<args.length - 1; i+=2) {
		fld_name = args[i];
		fld_alrt = args[i+1];
		fld = document.forms[frm].elements[fld_name];
		if ( fld.value != "" && (fld.value.search(/^[a-zA-Z](-\w+|\.\w+|\w*)*@[a-zA-Z](-\w+|\.\w+|\w*)*\.[a-zA-Z]{2,3}$/) == -1) ) {
			if (!errors)
				fld_blink=fld_name;
			errors = true;
		}
	}
	if (errors)	
	{
		MarcaErrorCampo(fld_blink, txt_error, true);
		return false;
	}
	return true;
}

function MarcaErrorCampo (target, msg, select){
  color1 = "#feff6f"; // blinking color
  color2="#EAEAEB";
  
  if (msg != null) alert(msg);


	  setTimeout('blinkExecute("'+target+'","'+color1+'")',0);
	  setTimeout('blinkExecute("'+target+'","'+color2+'")',500);
	  setTimeout('blinkExecute("'+target+'","'+color1+'")',2000);
	  setTimeout('blinkExecute("'+target+'","'+color2+'")',3500);             
	  setTimeout('blinkExecute("'+target+'","'+color1+'")',5000);
	  setTimeout('blinkExecute("'+target+'","'+color2+'")',6500);     
	  setTimeout('blinkExecute("'+target+'","'+color1+'")',7000);
	  setTimeout('blinkExecute("'+target+'","'+color2+'")',8500);     
	  setTimeout('blinkExecute("'+target+'","'+color1+'")',9000);
	  setTimeout('blinkExecute("'+target+'","'+color2+'")',10500);     
	  setTimeout('blinkExecute("'+target+'","'+color1+'")',11000);
	  setTimeout('blinkExecute("'+target+'","'+color2+'")',11500);     
	  	  	  	  
	  if (select) document.getElementById(target).select();
}

function blinkExecute(target,color){
  document.getElementById(target).style.backgroundColor = color;
}

function new_window(url, win, w, h) {
  var max_height = screen.availHeight - 30;
  h = (h > max_height) ? max_height : h;
  var posx = (screen.availWidth - w) / 2;
  var posy = (max_height - h) / 2;
  var opt = "titlebar=no,toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=" + w + ",height=" + h + ",top=" + posy + ",left=" + posx;

  var v = window.open(url, win, opt);
  v.focus();
}


function valor_moneda(campo,flag)
{
	if(flag==9)
		alert('entro en valor_moneda_de con '+campo);		

	campo=campo+"";

	resultado=campo;

	if(flag==9)
		alert('paso 1');		
	
	 if(resultado.indexOf('.')==-1)
   {
   		// no hay decimales
   		kk=resultado+".00";
   		resultado=kk;
   }
   salida=resultado.replace('.',',');	
	
		if(flag==9)
			alert('pas0 2');		
	
	 // añado al retorno el punto de millar
	 salida_total=salida.split(',');
	 tam=3;

	 	if(flag==9)
			alert('continuo en valor_moneda_de con '+salida_total);		
	 
	 // signo negrativo
	 if(campo.indexOf('-')!=-1)
			salida_total[0]=salida_total[0].replace('-','');

   // punto de millares
	 if(salida_total[0].length>tam)
	 {
	 		retorno=salida_total[0].substring(0,salida_total[0].length-tam)+"."+salida_total[0].substring(salida_total[0].length-tam,salida_total[0].length)+","+redondea(salida_total[1],flag);
   }
   else	 	
   {		
	 		if(flag==9)
	 			alert("Paso 1");
    	if(redondea(salida_total[1],flag).length>2)
    	  retorno=Suma(salida_total[0],"1.00")+","+redondea(salida_total[1],flag).replace("1","");
    	else
      	retorno=salida_total[0]+","+redondea(salida_total[1],flag);
   }   
      
   
   // signo negrativo
	 if(campo.indexOf('-')!=-1)
			retorno="-"+retorno;

	 	
	if(flag==9)
		alert('salgo de valor_moneda_de con '+retorno);		
	return retorno;
}

function Resta(valor1, valor2,flag)
{
	 if(valor2.indexOf('-')==-1)
			return Suma(valor1, "-"+valor2,flag);
	 else
	 		return Suma(valor1, valor2.replace('-',''),flag);
}


function Suma(valor1, valor2,flag)
{
   if(flag==9)
   		alert('entro en suma con ('+valor1+') y ('+valor2+')');
   		
   if(valor1=='') valor1="0,00";
   if(valor2=='') valor2="0,00";
   
   valor1=valor1.replace(',','.');
   valor2=valor2.replace(',','.');

   if(flag==9)
   		alert('antes de sumar float con ('+valor1+') y ('+valor2+')');

   resultado=parseFloat(valor1)+parseFloat(valor2);
   resultado=""+resultado;
   if(resultado.indexOf("e")!=-1)
   		resultado="0.00";
   if(flag==9)
   		alert('salgo en suma con'+resultado);   
   		
   return(resultado);
}

function redondea(valor_red,flag)
{
	//flag=9;
	primer_cero=0;
	if(flag==9)
		alert('entro en redondea con '+valor_red);	
		
	var salida_red="";
	var retorno_red="";
	var retorno_red2="";
	//alert("entra con "+valor_red);
	
	if(valor_red.charAt(0)=="0")
		primer_cero=1;
	
	if(valor_red.length>2)
	{
			if(parseInt(valor_red.charAt(2))>=5)
				retorno_red=parseInt(valor_red.substring(primer_cero,2))+parseInt("1");
			else
				retorno_red=parseInt(valor_red.substring(primer_cero,2));
	}
	else
		retorno_red=valor_red;
	
	if(flag==9)
	{
		alert("compara con ="+valor_red.charAt(2));
		alert("resto="+parseInt(valor_red.substring(0,2)));
	}	
	
	retorno_red2=""+retorno_red;
		
	if(retorno_red2.length<2)
	{	
		if(primer_cero==0)
			salida_red=retorno_red2+"0";
		else
			salida_red="0"+retorno_red2;
	}
	else
		salida_red=retorno_red2;

  if(flag==9)
		alert('salgo de redondea con '+salida_red);	

	return salida_red;
}


function MarcaCampo (target, msg, select){
  color1 = "#feff6f"; // blinking color
  color2="#D0D0D0";
  
  if (msg != null) alert(msg);


	  setTimeout('blinkExecute("'+target+'","'+color1+'")',0);
	  setTimeout('blinkExecute("'+target+'","'+color2+'")',500);
	  setTimeout('blinkExecute("'+target+'","'+color1+'")',1000);
	  setTimeout('blinkExecute("'+target+'","'+color2+'")',1500);             
	  setTimeout('blinkExecute("'+target+'","'+color1+'")',2000);
	  setTimeout('blinkExecute("'+target+'","'+color2+'")',2500);     
	  setTimeout('blinkExecute("'+target+'","'+color1+'")',3000);
	  setTimeout('blinkExecute("'+target+'","'+color2+'")',3500);     
	  setTimeout('blinkExecute("'+target+'","'+color1+'")',4000);
	  setTimeout('blinkExecute("'+target+'","'+color2+'")',4500);             
	  setTimeout('blinkExecute("'+target+'","'+color1+'")',5000);
	  setTimeout('blinkExecute("'+target+'","'+color2+'")',5500);     
	  setTimeout('blinkExecute("'+target+'","'+color1+'")',6000);
	  setTimeout('blinkExecute("'+target+'","'+color2+'")',6500);     
	  setTimeout('blinkExecute("'+target+'","'+color1+'")',7000);
	  setTimeout('blinkExecute("'+target+'","'+color2+'")',7500);      
	  if (select) document.getElementById(target).select();
}

function blinkExecute(target,color){
  document.getElementById(target).style.backgroundColor = color;
}

function chk_date() {
	args = chk_date.arguments;
	errors = false;
	error_fld= false;
	txt_error = "ERROR. Los siguientes campos no contienen fechas correctas:\n";
	var dia=mes=ano=0;
	fld_blink="";

	frm = args[0];
	for (var i=1; i<args.length - 1; i+=2, error_fld=false) {
		fld_name = args[i];
		fld_alrt = args[i+1];
		fld = document.forms[frm].elements[fld_name];

		// Chequeo si no esta vacio y no contiene un formato de fecha valido
		if (fld.value != "") {
				fecha=fld.value.split("-"); 
			 
				if(fecha.length==3 && parseInt(fecha[2],10) > 1000) { 
						dia=parseInt(fecha[0],10);
						mes=parseInt(fecha[1],10);
						ano=parseInt(fecha[2],10);
						
				    var mifecha = new Date(ano,--mes,dia);
				    
				    if(dia != parseInt(mifecha.getDate()) || mes != parseInt(mifecha.getMonth()) ||
				    		(ano != parseInt(mifecha.getYear()) && ano != parseInt(mifecha.getYear() + 1900)))	error_fld=true;
				}
				else
					error_fld=true;
				
				if (error_fld) {
			    txt_error += "\t- " + fld_alrt + "\n";
					if (!errors) {
						fld_blink=fld_name;
						errors = true;
					}
				}
		} // IF fecha no vacia
	} // FOR
	
	if (errors)	MarcaErrorCampo(fld_blink, txt_error, true);
	
	return !errors;
}


/******************************************************************************
** Funciones para la gestión de capas de visualización de mensajes de espera **
******************************************************************************/
// Funcion para la creación de una capa no visible
// Debe ser llamada después del body de la pagina y recibe como parametro el mapeo a las imagenes
function CrearCapaMensaje(mensaje, mapeo) {
  document.writeln("<div id='MensajeEspera' style='position:absolute; left:0px; top:0px; width:102%; height:100%; z-index:1; visibility: hidden'>");
  document.writeln("<table width='100%' height='100%'><tr>");
  document.writeln("<td align='center' valign='middle' background='" + mapeo + "fondo_repeat.gif'>");
  document.writeln("<table border='1' cellspacing='0' cellpadding='0' bordercolordark='#000000' bordercolorlight='#FFFFFF'><tr>");
  document.writeln("<td align='center' valign='middle' bgcolor='#FFFFFF'><br>");
 
  document.writeln("<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=4,0,2,0' width='162' height='20'>");
  document.writeln("<param name=movie value='" + mapeo + "barra_mensaje.swf'>");
  document.writeln("<param name=quality value=high>");
  document.writeln("<embed src='" + mapeo + "barra_mensaje.swf' quality=high pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash' type='application/x-shockwave-flash' width='162' height='20'>");
  document.writeln("</embed></object>");
 
  document.writeln("<br><br><span class='txt12'>&nbsp;&nbsp;&nbsp;" + mensaje + "&nbsp;&nbsp;&nbsp;<br><br></span>");
  document.writeln("</td></tr></table></td></tr></table></div>");
}


var apaga_luz=0;
function iluminaEstrella(estrella)
{
	if(estrella==0)
	{
		apaga_luz=1;
		setTimeout('apagaEstrella()',250);
	}	
	else if(estrella>0)
	{
	  apaga_luz=0;
	  for(contador=estrella+1;contador<=5;contador++)
	    document.getElementById('estrella'+contador).src="./images/estrella_off.png";
	  for(contador=1;contador<=estrella;contador++)
	    document.getElementById('estrella'+contador).src="./images/estrella.png";
	} 
	
	
}

function apagaEstrella()
{
	if(apaga_luz==1)
	{
	  for(contador=1;contador<=5;contador++)
	    document.getElementById('estrella'+contador).src="./images/estrella_off.png";
	}    

}


// Se ocultan todos los bloques de un mismo tipo y se visualiza uno solo. La nomenclatura de asociar varios bloques
// es haciendo que cada nombre sea igual y termine en un numero.
//	Parametro 1:	Nombre por el que comienzan todos los bloques del mismo tipo
//	Parametro 2:  Numero de bloque a visualizar 
//	Parametro 3:	True para indicar que siempre visualize o false para visualizar u ocultar segun su estado actual
function VerUno_OcultarTodo() {
	args = VerUno_OcultarTodo.arguments;
	aux = document.getElementById(args[0] + args[1]).style;
	EstadoAnterior=aux.display;

	// Se ocultan todos los bloques
  for (var i=1; document.getElementById(args[0] + i); i++) document.getElementById(args[0] + i).style.display='none';
  
  if (args.length == 2 || args[2] == true || EstadoAnterior == 'none')
  	aux.display='block'; // Se visualiza el bloque indicado
  else
    aux.display='none';
}


function getCheckedValue(radioObj,traza) {

	if(traza==undefined)
		traza=0;
	else
		alert("Entramos con objeto="+radioObj.name);
		
	if(radioObj==undefined)
	{
		if(traza==9)
			alert("Se devuelve vacío en el primer return");
		return "";
	}
	else
	{
		if(radioObj.length==undefined)
		{
			if(traza==9)
				alert("Length=1");

			if(radioObj.checked==true)
				return(radioObj.value);
			else
				return "";
		}
		else
		{
			if(traza==9)
				alert("Length="+radioObj.length);

			for (i=0;i<radioObj.length;i++)
			{ 
		       		if (radioObj[i].checked) 
		       		{
		        		return radioObj[i].value;  
		        	}	
		        }
		}
	}
        return "";
}

function chg_retornos(f) {
	for (var i=0; i < document.forms[f].elements.length; i++) {
		if (document.forms[f].elements[i].type == 'textarea')
			document.forms[f].elements[i].value = chg_brs_retornos(document.forms[f].elements[i].value, /\r\n/g, "<br>");
	}
}

function chg_brs(f) {
	for (var i=0; i < document.forms[f].elements.length; i++) {
		if (document.forms[f].elements[i].type == 'textarea')
			document.forms[f].elements[i].value = chg_brs_retornos(document.forms[f].elements[i].value, /<br>/g, "\n");
	}
}

function chg_brs_retornos(texto, origen, destino) {
  var start=end=0;
  var str=texto;
  var TExtraido;
  var TFinal="";

  while (end != -1) {
    if ((end=str.indexOf("<html>",start)) == -1) {
      TExtraido=str.substring(start,str.length+1);
      TFinal=TFinal.concat(TExtraido.replace(origen,destino));
    }
    else {
      TExtraido=str.substring(start,end);
      TFinal=TFinal.concat(TExtraido.replace(origen,destino));

      start=end;
      if ((end=str.indexOf("</html>",start)) == -1)
        TFinal=TFinal.concat(str.substring(start,str.length+1));
      else {
        end=end+7;
        TFinal=TFinal.concat(str.substring(start,end));
        start=end;
      }
    }
  }

  return TFinal;
}
