// === FUNCION ACTIVADA DESDE LA BARRA DE MANTENIMIENTO(tablas) ====
function edicion(tipo, tabla) {
  // 1.- Identifica el registro seleccionado para editar (radio button)
  var opts = document.getElementsByName('CLAVEPRI');
  var reg = '';
  for (var i=0; i < opts.length; i++) {
    if (opts[i].checked) {
      reg = opts[i].value;
    }
  }
  // 2.- Si no hubo seleccion de registro muestra mensaje
  if ((reg == '') && (tipo !== 'Nuevo')) {
    alert('Por favor recuerde seleccionar un registro');
  } else {
    // 3.- Muestra el DIV de edicion, cambiando el estilo de visualizacion
    document.getElementById('edicion').style.display = 'inline';
    if (tipo !== 'Nuevo') { 
      // 4.- Recupera los valores de los TH (nombres de campos)
      var nombres = document.getElementById('campos');
      // 5.- Recupera los valores de los TD en el TR Seleccionado
      var fila = document.getElementById(reg);
      // 6.- Declara e inicializa variables para concatenar datos GET
    }
    //alert(c);
    // 8.- Ejecuta rutina Ajax, con los datos de la operacion seleccionada
    url = "./entorno/edicion.php" + "?tipo=" + tipo + "&tabla=" + tabla + "&indice=" + reg;
    //alert(url);
    ObtenerDatos('edicion', url);
    //url = "./entorno/edicion.php" + "?tipo=" + tipo + "&tabla=" + tabla + "&indice=" + reg;
    //ObtenerDatos('edicion', url);
  }
}

  
function aceptar_xml(operacion,tabla) {
  // 1.- Obtiene los datos del formulario, y los estructura en un string XML
  var sXML = "<?xml version='1.0' encoding='ISO-8859-1' ?>";
  sXML = sXML + "<registros>";
  sXML = sXML + "<registro accion='" + operacion + "' entidad='" + tabla + "'>";
  for (var i=0; i < document.forms[0].length; i++) {
    if (document.forms[0].elements[i].type !== "button") {
      // 2.- Arma la cadena XML con los nombres de los campos y sus valores
      sXML = sXML + "<" + document.forms[0].elements[i].name + ">";
      sXML = sXML + document.forms[0].elements[i].value;
      sXML = sXML + "</" + document.forms[0].elements[i].name + ">";
    }
  }
  // 4.- Cierra la cadena XML, cerrando el nodo de datos y el nodo raiz
  sXML = sXML + "</registro>";
  sXML = sXML + "</registros>";
  // 5.- Ejecuta la operacion de edicion de tablas BD
  var url = "./entorno/accion.php?paquete=" + sXML;
  ObtenerDatos('edicion', url);
  // 6.- Muestra mensaje con el resultado de la operacion
  //alert('Los datos fueron actualizados satisfactoriamente');
  alert(sXML);
  // 5.- Si es satisfactoria, oculta la capa de edicion de tablas
  document.getElementById('edicion').style.display = 'none';
}


function aceptar(operacion, tabla) {

  // 1.- Obtiene los datos del formulario, y los estructura en array GET/POST
  var get = '&entidad=' + tabla;
  var datos = ArrayGET();
  // 4.- Ejecuta la operacion de edicion de tablas BD
  url = "./entorno/accion.php" + '?accion=' + operacion +  get + datos; 
  ObtenerDatos('edicion', url);
  // 5.- Muestra mensaje con el resultado de la operacion
  //alert(e);
  // 6.- Si es satisfactoria, oculta la capa de edicion de tablas
  //document.getElementById('edicion').style.display = 'none';
}

function GuardarMT(operacion, tabla, vista) {
//alert(operacion+'    '+ tabla +'       '+vista);
  var get = '?accion=' + operacion + '&entidad=' + tabla;
  // 1.- Obtiene los datos del formulario, y los estructura en array GET/POST
  var datos = SerializarDatos();
  
  //if (tabla=='grupo_sanguineo'){
  //  var grupo = document.getElementById('grupo').value;
  //  var grupoaux = document.getElementById('grupoaux').value;
  //  url = "./entorno/accion.php" + '?accion=' + operacion + '&entidad=' + tabla + "&grupo="+ encodeURIComponent(grupo)+ "&grupoaux="+ encodeURIComponent(grupoaux);   
  //}else{
     url = "./entorno/accion.php" + get + datos ;   
  //}
  // 4.- Ejecuta la operacion de edicion de tablas BD
  ObtenerDatos('Trans', url);

  document.getElementById('Trans').style.display = 'none';
  setTimeout("document.getElementById('buscar').onclick();",500);
 


}

function SerializarDatos(){
//var e = '?accion=' + operacion + '&entidad=' + tabla;
var e = '';

for (var a=0; a < document.forms.length; a++) {
  for (var i=0; i < document.forms[a].length; i++) {
    if (document.forms[a].elements[i].type !== "button") {
      if (document.forms[a].elements[i].type == "checkbox" ) {
  // 3.- Anexa cada par campo-valor del formulario si es un checkbox
          e = e + '&' + document.forms[a].elements[i].name + '=';
          e = e + document.forms[a].elements[i].checked;}
      else{
  // 4.- Anexa cada par campo-valor del formulario
          e = e + '&' + document.forms[a].elements[i].name + '=';
          e = e + document.forms[a].elements[i].value;

          }
        }
    }
}
 return e;

}


//*************************Funcion Para Formatos a Valores Numericos***********************
//format_moneda(Pesototal, 2, ',', '.');	
function format_moneda(a, b, c, d) {
 a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
 e = a + '';
 //alert(e);
 f = e.split('.');
//--------------------Asigna este valor cuando es cero--------------------------
 if (!f[0]) {
  f[0] = '0';
 }
 if (!f[1]) {
  f[1] = '';
 }
//------------------------------------------------------------------------------
//---------------Para Asignar Ceros Si viene Sin Decimales----------------------
 if (f[1].length < b) {
  g = f[1];
  for (i=f[1].length + 1; i <= b; i++) {
   g += '0';
  }
  f[1] = g;
 }
//------------------------------------------------------------------------------

 if(d != '' && f[0].length > 3) {
  h = f[0];

  f[0] = '';

  for(j = 3; j < h.length; j+=3) {
   i = h.slice(h.length - j, h.length - j + 3);
   f[0] = d + i +  f[0] + '';
  }

  j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
  f[0] = j + f[0];
 }
 c = (b <= 0) ? '' : c;
 return f[0] + c + f[1];
}
//*********************************************************************************************
function number_format(ValorTotal){
//Obtiene el Valor en Formato Moneda y lo regresa a Formato Reconocido por Java Script
//Ya Que JavaScript Reconoce los Formatos con Puntos como Decimales Esta Funcion Obtiene
//Estos Numeros Y los Regresa a un Estado Donde JavaScript los Reconoce y Pueden Hacerse
//Operaciones Matematicas Con Ellos
m=ValorTotal + '';
n=m.split('.');
m= n + '';
f=m.split(',');

var valor='';
for (var i=0; i < f.length; i++ ){

    if ( i < f.length - 1){
       valor = valor + f[i];
    }else{
       valor = valor+'.'+f[i];
    }
}
return valor;
}




function cancelar() {
  // 1.- Oculta la capa de edicion de tablas
  document.getElementById('edicion').style.display = 'none';
}

function CerrarVentana(control){
// alert('activo');
//document.getElementById(control).innerHTML = '';
document.getElementById(control).style.display = 'none';

}
// === FUNCIONES de Validacion de Acceso al Sistema ====
function Enter(event, control) {
  // 1.- Verifica la tecla pulsada a traves del objeto event
  if (event.keyCode == 13) {
    // 2.- Si es ENTER pasa el enfoque al control indicado
    document.getElementById(control).focus();
  }
}



function PaginarConAjax(tabla , pagina) {
    	//alert(tabla)
	url = "./entorno/generarlistabd.php" +"?pagina=" + pagina + "&tabla=" + tabla;
	//alert(url);
	ObtenerDatos('listabd',url);
}


function PaginarConAjaxXcriterio(tabla , pagina) {
    	
      var campo = document.getElementById('campo').value;
      var criterio = document.getElementById('criterio').value;
      // 3.-Recupera los contenidos HTML segun la consulta
  	url = "./entorno/genlistabdxcriterio.php"  + "?pagina=" + pagina + "&tabla=" + tabla + "&campo=" + campo + "&criterio=" + criterio;
	ObtenerDatos('listabd',url);
}


function BuscarListBDxCriterio(evt,tabla) {
 
     if (evt.keyCode ==  13){
	if(document.getElementById('campo').value!==''){		
	var campo = document.getElementById('campo').value;
	var criterio = document.getElementById('criterio').value;
	// 3.-Recupera los contenidos HTML segun la consulta
		url = "./entorno/genlistabdxcriterio.php" + "?tabla=" + tabla + "&campo=" + campo + "&criterio=" + criterio;
		// 4.- El resultado obtenido lo almacena en el combox correspondiente
	ObtenerDatos('listabd', url);
	}else{alert('Debe haber un campo cargado por el cual Buscar!!!')}
     }
}


function BusListBDxCritVista(vista) {
    if(document.getElementById('campo').value!==''){		
        var campo = document.getElementById('campo').value;
	var criterio = document.getElementById('criterio').value;
	// 3.-Recupera los contenidos HTML segun la consulta
       url = "./entorno/genlistabdxcriterio.php" + "?tabla=" + vista + "&campo=" + campo + "&criterio=" + criterio;
      // 4.- El resultado obtenido lo almacena en el combox correspondiente
	ObtenerDatos('listabd', url);
	}else{alert('Debe haber un campo cargado por el cual Buscar!!!')}

}


function BusListBDVista(vista) {
        var campo = document.getElementById('campo').value;
	var criterio = document.getElementById('criterio').value;
	// 3.-Recupera los contenidos HTML segun la consulta
       url = "./entorno/generarlistabd.php" + "?tabla=" + vista ;
      // 4.- El resultado obtenido lo almacena en el combox correspondiente
	ObtenerDatos('listabd', url);
	
}


//====================================================================
//Funciones de Pesta�s (Cambio de Pesta�s y Ocultar y Mostrar)
//====================================================================

var anterior;
var celdaant;
function mostrar(capa,celda,pestfich) {
  /// alert('Se activo 2'+ capa);
  //document.getElementById('ficha1').style.visibility="hidden";
  document.getElementById('ficha1').style.display="none";
  document.getElementById('celda1').className = 'celdaIna';
  
  if (anterior) {
    //document.getElementById(anterior).style.visibility="hidden";
    document.getElementById(anterior).style.display="none";
    //document.getElementById(celdaant).style.backgroundColor="#F0F0F0";
    document.getElementById(celdaant).className = 'celdaIna';
  }
  //document.getElementById(capa).style.visibility="visible";
  document.getElementById(capa).style.display="inline";
  document.getElementById(celda).className = 'celdaAct';
  
  //document.getElementById(celda).style.backgroundColor="#3756A6";
  //document.getElementById(pestfich).style.backgroundColor="#3756A6";
  // alert('Se activo'+ capa);
  anterior=capa;
  celdaant=celda;
}

var anterior2;
var celdaant2;

function mostrar2(capa,celda,pestfich) {
  document.getElementById('ficha11').style.display = "none";
  document.getElementById('celda11').className = 'celdaIna';
  
  if (anterior2) {
    document.getElementById(anterior2).style.display = "none";
    document.getElementById(celdaant2).className = 'celdaIna';
  }

  document.getElementById(capa).style.display = "inline";
  document.getElementById(celda).className = 'celdaAct';

  anterior2 = capa;
  celdaant2 = celda;
}


//================================================================
//Funcion JavaScript valida q solo se acepten numeros
//====================================================================

function validarnumero(evt)
{
//alert(evt);
evt = (evt) ? evt : event
var key = (evt.which) ? evt.which : evt.keyCode;
//alert(key);
if (key > 47 && key < 58 || key == 8 ||  key == 9) { return true;}
else {return false;}
}

function validarnumycoma(evt)
{
//alert(evt);
evt = (evt) ? evt : event
var key = (evt.which) ? evt.which : evt.keyCode;
//alert(key);
if (key > 47 && key < 58 || key == 8 ||  key == 9 ||  key == 44 ||  key == 46) { return true;}
else {return false;}
}

//====================================================================
//Funcion JavaScript valida q solo se acepten carateres
//====================================================================

function validartexto(evt)
{
//alert(evt);
evt = (evt) ? evt : event
var key = (evt.which) ? evt.which : evt.keyCode;
if (key > 47 && key < 58 ) { return false;}
else {return true;}
}


function BloquearteclasF(evt){
//alert(evt.which + '    '+ evt.keyCode);
evt = (evt) ? evt : event
var key = (evt.which) ? evt.which : evt.keyCode;
if (evt.keyCode >= 112 && evt.keyCode <= 123  ) { return false;}
else {return true;}
}

//Funcion para Verificar si el correo esta bien  escrito
function checkmail(){
if(document.getElementById('correo_electronico').value !=='' ){
var email = document.getElementById('correo_electronico').value;
var ind1, ind2, ind3;
ind1 = email.indexOf('@');
ind2 = email.indexOf('.');
ind3 = email.lastIndexOf('@');
if ((ind1<=0) || (ind2<ind1) || (ind3!=ind1)){
  alert('Su direccion de correo esta mal Escrita Verifiquela!!!')
  document.getElementById('correo_electronico').value="";
  Encontrado = true;
  //document.getElementById('correo_electronico').focus();
}else{document.forms['medico'].aceptar.disabled=false; document.forms['medico'].aceptar.focus();}

}else{document.forms['medico'].aceptar.disabled=false; document.forms['medico'].aceptar.focus();}

}

  
//==================================================================================================
//Funcion JavaScript valida que solo se acepten numeros y los caracteres guion(-) y barra (/)
//==================================================================================================

function ValFechaTelf(evt){
//alert(evt.which +"    "+evt.keyCode);
evt = (evt) ? evt : event
var key = (evt.which) ? evt.which : evt.keyCode;
if (key > 47 && key < 58 || key == 8 || key == 37 || key == 39 || key == 44 || key == 46 || key == 9 || evt.which == 47 || evt.which == 45) { return true;}
else {return false;}
}



function ManTrans(tipo,tabla, vista){
// doLoad();
 //alert('tabla'+tabla);
  var opts = document.getElementsByName('CLAVEPRI');
  var reg = '';
  for (var i=0; i < opts.length; i++) {
    if (opts[i].checked) {
      reg = opts[i].value;
    }
  }
//alert('Resfistro' + reg);
if ((reg == '') && (tipo !== 'Nuevo')) {
    alert('Por favor recuerde seleccionar un registro');
  } else {
    //style.zIndex=auto|numberv
    document.getElementById('Trans').style.display = 'inline';
    tabla = extraer_strtabla(tabla,1);
    //document.getElementById('listabd').style.display = 'none';
  }
    
   url = "./formularios/"+tabla+".php" + "?tabla=" + tabla + "&tipo=" + tipo + "&vista=" + vista +"&reg=" + encodeURIComponent(reg) ;
   ObtenerDatos('Trans', url);

}


function  extraer_strtabla(tablaux,retorno){
var tabla;
arraytabla = tablaux.split('.');  

switch (retorno) {
		case 0 :
		tabla = arraytabla[0];
	         
		break;
		case 1 :
		  if(arraytabla[1] == undefined){
		   tabla = arraytabla;
		  }else{
 		   tabla = arraytabla[1];
                  }
		break;
		default :
		tabla = tablaux;
                }


	
return tabla;
}


function CloseVentana(Ventana){
   // 1.- Oculta la capa de edicion de tablas
 document.getElementById(Ventana).style.display = 'none';
}


function hora(){
var tiempo =new Date;
var ValorHora;
var meridiano;
/*with (tiempo){
	hora = getHours();
	cad = hora + ":" + getMinutes() + ":" + getSeconds();
	}*/
   var ahora = new Date()
   var horas = ahora.getHours()
   var minutos = ahora.getMinutes()
   var segundos = ahora.getSeconds()
   //ajusta las horas
  /* if (horas > 12) {
      //horas -= 12
     // meridiano = " P.M."
   } else {
      meridiano = " A.M."
   }
   */
      //establece las horas
   if (horas < 10)
      ValorHora = "0" + horas
   else
      ValorHora = "" + horas

   //establece los minutos
   if (minutos < 10)
      ValorHora += ":0" + minutos
   else
      ValorHora += ":" + minutos
            
   //establece los segundos
   if (segundos < 10)
      ValorHora += ":0" + segundos
   else
      ValorHora += ":" + segundos
         

document.getElementById('hora').value = ValorHora; 

}

//Funcion para Convertir caracteres a Mayuscula
function ConvertirMay(texto) 
{     
texto.value = texto.value.toUpperCase();   
}



function max(txarea, max) 
{ 
    total = max; 
    tam = txarea.value.length; 
    str=""; 
    str=str+tam; 
    
    if (tam > total){ 
        aux = txarea.value; 
        txarea.value = aux.substring(0,total); 
    
    } 
}


//====================================================================
//===============Borrar Registro del Calendario=======================
//====================================================================

function PermitirsoloBorrar(evt)
{
evt = (evt) ? evt : event
var key = (evt.which) ? evt.which : evt.keyCode;
if (key == 8 ||  evt.keyCode == 46  ) { return true;}
else {return false;}
}


//===================================================================================================

function SerializarDatosXML(tabla,campos){

var DatosXML='';
//DatosXML +='<filas>';
   for (var j=2; j < tabla.rows.length; j++) {
      DatosXML +='<fila>';
        for (var i=0; i<tabla.rows[j].cells.length -1; i++) {
          var campo = campos.cells[i].id;
          DatosXML +='<' + campo + '>';
             DatosXML += tabla.rows[j].cells[i].innerHTML;    
          DatosXML +='</'+ campo + '>';
        }
      DatosXML +='</fila>';  
  }
//DatosXML +='<filas>';
//alert(DatosXML);   
return  DatosXML;

}

