//////////////////// EJEMPLOS DE FUNCIONES JAVASCRIPT //////////////////
//																	  //
//  Solo como ejemplo, ya que deben adaptarse a cada caso particular  //
//																	  //
////////////////////////////////////////////////////////////////////////
//document.onmousedown=derecha
var IE = document.all?true:false;
function popup(website, ancho, alto)
{
var   w = window.screen.availWidth;
var   h = window.screen.availHeight;
var ancho= ancho *1; 
var alto= alto * 1;

var leftdist = (w-ancho)/2; // distancia hasta el borde izquierdo
var topdist = (h -alto)/2; //distancia hasta el borde superior
//alert("left= "+leftdist+" top= "+topdist+" h="+h+" w= "+w+" alto= "+alto+" ancho= "+ancho);
window.open(website,'','toolbar=0,menubar=0,location=0,scrollbars=1,status=1,height='+ alto +',width=' + ancho  +",left=" + leftdist + ",top=" + topdist);
}
////para validar texto
////para validar texto
function valida_texto(e,c)//
{
	var key;
	if (navigator.appName == "Netscape") // me fijo
	{
		key= e.which;
	}
	else
	{
		key= window.event.keyCode; // leo la tecla en ASCII que ingreso
	}
	c=c.toLowerCase();
//	alert(key);
//	alert(c);
	switch(c)
	{
		case "c"://Si es Caracter
			if (key  !=63 && key !=40 && key !=41 && key != 36 && key != 39 && key!=37 ||key==8 ||key==0)
			{
				break;
			}
			else
			{
				return false;
			}
		case "e"://si es entero
			if (key  >47 && key <59 ||key==8 ||key==0)
			{
				break;
			}
			else
			{
				return false;
			}
		case "d"://si es decimal
			if (key  >47 && key <59 || key==46 ||key==8 ||key==0)
			{
				break;
			}
			else
			{
				return false;
			}
		case "r"://si es digito verificador
			if (key  >47 && key <59 || key==75 || key==107 ||key==8 ||key==0)
			{
				break;
			}
			else
			{
				return false;
			}
	}	
}
////////funcion para validar el rut
function valida_rut(rutp,digitop,formu,campo,accionn,e)
{
	
	rut=rutp.value;
	df=digitop.value;
	x=2;
    sumatorio=0;
    for (i=rut.length-1;i>=0;i--)
	{
        if (x>7)
		  {x=2;}
        sumatorio=sumatorio+(rut.charAt(i)*x);
        x++;
     }	
	 digito=(sumatorio%11);
     digito=11-digito;
     switch (digito)
	 {
        case 10:
            digito="K";
            break;
        case 11:
            digito="0";
            break; 
     }
		if (IE)
		{
		  if (window.event.keyCode >  45)
				  {
								 if (df.toUpperCase()==digito)
									{ 
										 campo.value=accionn;
										  formu.submit();
										
										 return true;
									}else
									{
										 alert(" Rut Incorrecto !!. Por Favor verifique El Rut!");  
										 digitop.select();

										 return false;
									}
			  }
		}
		else 
	{

		 if (e.which > 45)
		 {
				if (df.toUpperCase()==digito)
						{ 
					 campo.value=accionn;
					 formu.submit();
					 return true;
					}
					else
					{
					 alert(" Rut Incorrecto !!. Por Favor verifique El Rut!");  
					 digitop.select();
					 return false;
					}
		 }		 
		}
}

function validar_formulario()
{
	var i =0;
	var men="";

	for(i=0; i<document.forms[0].elements.length; i++)
	{
		check=0;
		var cad_men = document.forms[0].elements[i].id; 
		var largo=cad_men.length;
		var cad_val=cad_men.substring(0,1)
		var mensaje=cad_men.substring(1,largo)
	   		if(cad_val=="*")
		{
			switch (document.forms[0].elements[i].type)
			{
				//********** Caso si es texto  o campo password
				case "text"|| "password":
					if(document.forms[0].elements[i].value==0)
					{	
						men= men + "-     "+ mensaje +"\n" 	
					}	
		
					break;
				//********* caso si en un select combo
				case "select-one":
					if(document.forms[0].elements[i].value==0)
					{	
						men= men + "-     "+ mensaje +"\n" 	
					}
					
					break;
				 //**********caso si un select multiple
				case "select-multiple":
					nombreobj=document.forms[0].elements[i].name;
					longitud=nombreobj.length
					caso=nombreobj.substring(longitud-2,longitud)
					if(document.forms[0].elements[i].value==0)
					{	
						men= men + "-     "+ mensaje +"\n" 
					}	
					break;
				
				//************Caso del text area
				
				case "textarea":
					if(document.forms[0].elements[i].value==0)
					{	
						men= men + "-     "+ mensaje +"\n" 	
						document.forms[0].elements[i].value=0;
					}	
					break;
				
				//************** Caso del radio
				case "radio":
					var e 
					for (e=0;i<document.forms[0].elements[i].length;e++)
					{ 
					   if (document.fcolores.colorin[e].checked) 
						  break; 
					} 						
					break;
				//*************** Caso checkbox
				case "checkbox":
					if(document.forms[0].elements[i].checked==false)
					{	
						men= men + "-     "+ mensaje +"\n" 
					}
					break;
			}
		}
		 if(cad_val=="/")
		{
				if(document.forms[0].elements[i].value.indexOf("@") == -1 || document.forms[0].elements[i].value.indexOf(".") ==-1)
				{
					 men= men + "-     "+ mensaje +"\n" 	
				}
			
		}
		
	}
	if (men!="")
	 {
		 menF="_________________________\n";
		 menF=menF+"Le ha faltado introducir los siguientes datos: \n \n \n";
		 menF=menF+men +" \n"
		 menF=menF + "_________________________ \n";
		 menF=menF + "¡Por favor pulse enter, rellene los datos y pruebe de nuevo!";
		 alert(menF)
		return false;
	}
}
function deshabilitar()
{
//	alert("deshabilitar");
	for(i=0; i<document.forms[0].elements.length; i++)
	{
		document.forms[0].elements[i].disabled=true;
	}
}
function habilitar()
{
//	alert("deshabilitar");
	for(i=0; i<document.forms[0].elements.length; i++)
	{
		document.forms[0].elements[i].disabled=false;
	}
}

function limpia_select(select_limpiar,titulo)
{
	var  j;
	// ****** elimina todos los items del select
//	alert(select_limpiar.options.length);
	for (i = select_limpiar.options.length; i >= 0; i--)
	{
		select_limpiar.options[i] = null; 
	}
	//******* coloca el primer items  del select*******
	
		select_limpiar.options[0] = new Option(titulo);
	
}
//****************************************************************
//		FUNCION PARA CARGAR UN SELECT EN FORMA LOCAL
//****************************************************************
function cargar_select(id,arreglo_buscar,select_llenar,titulo)
{
	// ****	id				= id que se tiene que encontrar
	// **** arreglo_buscar	= arreglo en el cual se buscaran los id que coincidan con id
	// **** select_llenar	= select que se llenara con los datos encontrados del arreglo
	// **** titulo			= titulo del primer item que tendrï¿½el select

	var i, j;
	var prompt;
	// ****** elimina todos los items del select
//	alert(select_llenar.options.length);
	for (i = select_llenar.options.length; i >= 0; i--)
	{

		select_llenar.options[i] = null; 
	}

	//******* coloca el primer items  del select*******
	prompt = (arreglo_buscar != null) ? titulo:"0" //goodPrompt : badPrompt;
	if (prompt == null)
	{
		j = 0;
	}
	else
	{
		select_llenar.options[0] = new Option(prompt,"0");
		j = 1;
	}
	// ***** si el arreglo es diferente de vacio, comienza agregar items ******
	if (arreglo_buscar != null)
	{
		for (i = 0; i < arreglo_buscar.length; i++) 
		{
			//*** si coincide el id con el id del arreglo*****
			if(id==arreglo_buscar[i][1])
			{
				var Vvalue=arreglo_buscar[i][0];
				var Vtexto=arreglo_buscar[i][2];
//				alert(Vvalue);
				var variable = new Option(Vtexto,Vvalue,"","");
				select_llenar.options[j]=variable;
				j++;
			}
		}
	// ** deja seleccionado el primer elemento de la lista****
		select_llenar.options[0].selected = true;
	}
}


function paginas(voy,des,cuan,acc)
{
//	alert("hola");
	with (document.frm1)
	{
		switch(voy)
		{
			case "adelante": //para avanzar 1 hacia adelante
				if(des==0)
				{
					desde.value=des+cuan; 
				}else
				{
					desde.value=des;
				}
				break;
			case "atras": //para avanzar 1 hacia atras
					desde.value=des;
				break;
			default:
				desde.value=des; //para ir a una página en especial
		}
		cuantos.value=cuan;
		accion.value=acc;
		submit();
	}
} 



function ruta(cadena,idd)
{

	var arreglo=new Array();
	var cad=cadena;
	var j=0;
	var a="";
	for(i=0;i<cad.length;i++) 
	{
		if(cad.substring(i,i+1)=="-")
		{
			arreglo[j]=a;
			j++;
			a="";
		}
		else
		{
			a=a+cad.substring(i,i+1);
		}
	}
if(arreglo[3]=="LCRUDO")
{
//	popup(arreglo[0]+"?idi="+idd,arreglo[1],arreglo[2]);
	document.location=arreglo[0]+"?id_relacion="+idd,arreglo[1],arreglo[2];
}

if(arreglo[3]=="L")
{
	popup(arreglo[0]+"?id_relacion="+idd,arreglo[1],arreglo[2]);
}

if(arreglo[3]=="T")
{
	
	popup(arreglo[0]+"?id="+idd+"&tabla="+arreglo[4],arreglo[1],arreglo[2]);
}
if(arreglo[3]=="Z")
{
	inicio(arreglo[0]);
}
if(arreglo[3]=="BF")
{
	with (document.frm1)
	{
		if (confirm("Esta seguro de Borrar la Foto??") )
		{
			accion.value="borrar_foto"
			idi.value=idd;
			submit();
		}
	}
}

if(arreglo[3]=="B")
{	
	
	with (document.frm1)
	{
		if (confirm("Esta seguro de Borrar el Registro") )
		{
//			alert(idd);	
			accion.value="borrar"
			idi.value=idd;
			submit();
		}
	
	}
}
}
function buscar(cam)
	{
		document.frm1.accion.value="buscar";
		document.frm1.campo.value=cam;
		document.frm1.submit();
	}
function buscarA()
{
	document.frm1.accion.value="buscar";
	document.frm1.submit();
}


function encabezados(orden,sentido,accion)
{
	document.frm1.posicion.value=window.document.body.scrollTop;
	document.frm1.orden.value=orden
	//alert(document.frm1.ordenar.value);
	/*switch (document.frm1.ordenar.value)
	{
		case "1":
			document.frm1.ordenar.value=0;
			break;
		default:
			document.frm1.ordenar.value=1;
			break;

	} */
	document.frm1.ordenar.value=1;

//	alert(document.frm1.ordenar.value);
	
	document.frm1.sentido.value=sentido;
	document.frm1.accion.value=accion;
	
	document.frm1.submit();
}


    imagen1=new Image;imagen1.src="clases/imagenes_clases/siguiente.gif"
	imagen2=new Image;imagen2.src="clases/imagenes_clases/siguiente2.gif"
	imagen3=new Image;imagen3.src="clases/imagenes_clases/anterior.gif"
	imagen4=new Image;imagen4.src="clases/imagenes_clases/anterior2.gif"
	function cambiar(x)
	{       
		switch(x)
			{
			
			case 1:
					document.images['ejemplo'].src=imagen2.src;
			break;
			case 2:
					document.images['ejemplo'].src=imagen1.src;
			break;
			}
	}

	function cambiar2(x)
	{       
		switch(x)
			{
			
			case 1:
					document.images['ejemplo2'].src=imagen4.src;
			break;
			case 2:
					document.images['ejemplo2'].src=imagen3.src;
			break;
			}
	}	

		function derecha(e) {
			if (navigator.appName == 'Netscape' && (e.which == 3 || e.which == 2)){
			alert(' Derechos Resevados')
			return false;
		}

		else if (navigator.appName == 'Microsoft Internet Explorer' && (event.button == 2)){
		alert(' Derechos Resevados')
		}
}

//************************************** Funciones de acciones de formularios ******************



function limpiar2(foco)
{
	
		document.frm1.envio.value="ACEPTAR";
		var i =0;
	for(i=0; i<document.forms[0].elements.length; i++)
	{
		
			switch (document.forms[0].elements[i].type)
			{
		
				case "text"|| "password":
					document.forms[0].elements[i].value="";
					break;
				case "select-one":
					document.forms[0].elements[i].value=0
					break;
				 //**********caso si un select multiple
				case "select-multiple":
					document.forms[0].elements[i].value=0
					break;
				case "textarea":
							document.forms[0].elements[i].value="";

					break;
			}
	}	
		foco.focus();
}	






/*function accion_envio()
{
	if(validar_formulario()==false)
	{
		return;
	}

	if (document.frm1.envio.value=="ACEPTAR")
	{
	
		document.frm1.accion.value="insertar";
	}
	else if (document.frm1.envio.value=="MODIFICAR")
	{
		document.frm1.accion.value="modificar";
	}
	else if (document.frm1.envio.value=="BORRAR")
	{
		document.frm1.accion.value="borrar";
	}
//	alert(document.frm1.envio.value);
	document.frm1.submit();
}  */


	function buscardato(idi)
	{
		document.frm1.accion.value="encuentra";
		document.frm1.idi.value=idi;
		document.frm1.submit();
	}
	function tb(e,obj)
	{
		var key=0;
				if (navigator.appName=="Netscape") // me fijo
				{
					if (e.which==13)
					{
						//e.which=0;
					  obj.select();

					}
				}
	else
			{
				 if(window.event.keyCode==13)
				{		
				
							 window.event.keyCode=9;
				}
			}
	}


	function veri_codigo(e)
	{
		if (navigator.appName=="Netscape") // me fijo
				{
							if (e.which==13)
								{
									document.frm1.accion.value="busca_codigo";
									document.frm1.submit();
								}
				}else
			{
				 if(window.event.keyCode==13)
					{
									document.frm1.accion.value="busca_codigo";
									document.frm1.submit();
					}
			}
	}


function veri_codigo(e)
	{
		if (navigator.appName=="Netscape") // me fijo
				{
							if (e.which==13)
								{
									document.frm1.accion.value="busca_codigo";
									document.frm1.submit();
								}
				}else
			{
				 if(window.event.keyCode==13)
					{
									document.frm1.accion.value="busca_codigo";
									document.frm1.submit();
					}
			}
	}




function cierra()
{
       window.opener.document.frm1.submit();
       window.close();
}

// Funcion para fpd 
function imprimir_pdf()
{
	/*var answer=confirm("¿Desea Ver todos los registros, o solo los que buscó? .\n 'Aceptar' para ver todos, 'Cancelar' para lo seleccionado.")
	if (answer) {
		document.frm1.tipo_informe.value="todos";
	}
	else 
	{
		document.frm1.tipo_informe.value="seleccion";
	}  */
	document.frm1.target="popup";
	document.frm1.action="../../genera_pdf/informe_general.php";
	document.frm1.submit();
	document.frm1.target="";
	document.frm1.action="";
}
function imprimir_xls()
{
	//var answer=confirm("¿Desea Ver todos los registros, o solo los que buscó? .\n 'Aceptar' para ver todos, 'Cancelar' para lo seleccionado.")
	//if (answer) {
	//	document.frm1.tipo_informe.value="todos";
//	}
//	else 
//	{
		document.frm1.tipo_informe.value="seleccion";
//	}
	document.frm1.target="popup";
	document.frm1.action="genera_pdf/crea_xls.php";
	document.frm1.submit();
	document.frm1.target="";
	document.frm1.action="";
}

function posi(y)
{
	scroll(0,y);
}

function validarut(rutp,digitop)
{
	
	rut=rutp.value;
	df=digitop.value;
	x=2;
    sumatorio=0;
	//if(df=="")
	//{return false;}
    for (i=rut.length-1;i>=0;i--)
	{
        if (x>7)
		  {x=2;}
        sumatorio=sumatorio+(rut.charAt(i)*x);
        x++;
     }	
	 digito=(sumatorio%11);
     digito=11-digito;
     switch (digito)
	 {
        case 10:
            digito="K";
            break;
        case 11:
            digito="0";
            break; 
     }
	// alert(df.toUpperCase());
	 //alert(digito);
	 if (IE)
	{
		//if (window.event.keyCode >  45)
		//  {
			 if (df.toUpperCase()==digito)
				{ 
					 //campo.value=accionn;
					//  formu.submit();
					
					 return true;
				}else
				{
					 alert(" Rut Incorrecto !!. Por Favor verifique El Rut!");  
					 digitop.select();
					 return false;
				}
		//}
	}
	else 
	{
		//if (e.which > 45)
		//{
			if (df.toUpperCase()==digito)
			{ 
				 //campo.value=accionn;
				 //formu.submit();
				 return true;
			}
			else
			{
				alert(" Rut Incorrecto !!. Por Favor verifique El Rut!");  
				digitop.select();
				return false;
			}
		// }		 
	}
}
// Begin
function setDataType(cValue)
  {
    // THIS FUNCTION CONVERTS DATES AND NUMBERS FOR PROPER ARRAY
    // SORTING WHEN IN THE SORT FUNCTION
    var isDate = new Date(cValue);
    if (isDate == "NaN")
      {
        if (isNaN(cValue))
          {
            // THE VALUE IS A STRING, MAKE ALL CHARACTERS IN
            // STRING UPPER CASE TO ASSURE PROPER A-Z SORT
            cValue = cValue.toUpperCase();
            return cValue;
          }
        else
          {
            // VALUE IS A NUMBER, TO PREVENT STRING SORTING OF A NUMBER
            // ADD AN ADDITIONAL DIGIT THAT IS THE + TO THE LENGTH OF
            // THE NUMBER WHEN IT IS A STRING
            var myNum;
            myNum = String.fromCharCode(48 + cValue.length) + cValue;
            return myNum;
          }
        }
  else
      {
        // VALUE TO SORT IS A DATE, REMOVE ALL OF THE PUNCTUATION AND
        // AND RETURN THE STRING NUMBER
        //BUG - STRING AND NOT NUMERICAL SORT .....
        // ( 1 - 10 - 11 - 2 - 3 - 4 - 41 - 5  etc.)
        var myDate = new String();
        myDate = isDate.getFullYear() + " " ;
        myDate = myDate + isDate.getMonth() + " ";
        myDate = myDate + isDate.getDate(); + " ";
        myDate = myDate + isDate.getHours(); + " ";
        myDate = myDate + isDate.getMinutes(); + " ";
        myDate = myDate + isDate.getSeconds();
        //myDate = String.fromCharCode(48 + myDate.length) + myDate;
        return myDate ;
      }
  }
function sortTable(col, tableToSort)
  {
    var iCurCell = col + tableToSort.cols;
    var totalRows = tableToSort.rows.length;
    var bSort = 0;
    var colArray = new Array();
    var oldIndex = new Array();
    var indexArray = new Array();
    var bArray = new Array();
    var newRow;
    var newCell;
    var i;
    var c;
    var j;
    // ** CREA UN ARREGLO CON EL CONTENIDO DE LA COLUMNA
    for (i=1; i < tableToSort.rows.length; i++)
      {
        colArray[i - 1] = setDataType(tableToSort.cells(iCurCell).innerText);
        iCurCell = iCurCell + tableToSort.cols;
//		alert(colArray[i-1]);
      }
    // ** COPIA EL ARREGLO PARA COMPARAR DESPUES DE ORDENAR
    for (i=0; i < colArray.length; i++)
      {
        bArray[i] = colArray[i];
//		alert(bArray[i]);
      }
    // ** ORDENA LA COLUMNA SELECCIONADA
//   alert ( colArray );
    colArray.sort();
//    alert ( colArray );
    for (i=0; i < colArray.length; i++)
      { // LOOP THROUGH THE NEW SORTED ARRAY
        indexArray[i] = (i+1);
        for(j=0; j < bArray.length; j++)
          { // LOOP THROUGH THE OLD ARRAY
            if (colArray[i] == bArray[j])
              {  // WHEN THE ITEM IN THE OLD AND NEW MATCH, PLACE THE
                // CURRENT ROW NUMBER IN THE PROPER POSITION IN THE
                // NEW ORDER ARRAY SO ROWS CAN BE MOVED ....
                // MAKE SURE CURRENT ROW NUMBER IS NOT ALREADY IN THE
                // NEW ORDER ARRAY
                for (c=0; c<i; c++)
                  {
                    if ( oldIndex[c] == (j+1) )
                    {
                      bSort = 1;
                    }
                  }
				  if (bSort == 0)
					{
					  oldIndex[i] = (j+1);
					}
					  bSort = 0;
					}
          }
    }
  // ** SORTING COMPLETE, ADD NEW ROWS TO BASE OF TABLE ....
// var oTBody0.bgColor = "lemonchiffon";
  for (i=0; i<oldIndex.length; i++)
    {
//	  oRow = oTBody1.insertRow();
      newRow = tableToSort.insertRow();
	  newRow.bgColor="#EAEAEA";
	  //onmouseover="this.innerHTML='<B>Mouse out to change back.</B>'";
	  //newRow.onMouseOver="bgColor='#3399FF'";
	  //newRow.height=10; 
	  //newRow.onmouseout="#EAEAEA"; */
//	  newRow.bgcolor="#FF0000" ;
	  //alert(newRow.bgcolor);
// newRow.onMouseDown='#FF9900';

      for (c=0; c<tableToSort.cols; c++)
        {
          newCell = newRow.insertCell();
//		  newCell.className='encabezados' ;
//		  onmouseover="bgColor='#3399FF'"  onmouseout="bgColor='#EAEAEA'" bgcolor="#EAEAEA" onMouseDown="bgColor='#FF9900'"
		  //newCell.height = 65;
		  newCell.innerHTML = tableToSort.rows(oldIndex[i]).cells(c).innerHTML;
		  alert(newCell.innerHTML);
        }
      }
  //MOVE NEW ROWS TO TOP OF TABLE ....
  for (i=1; i<totalRows; i++)
    {
      tableToSort.moveRow((tableToSort.rows.length -1),1);
	   //alert(i);
    }
  //DELETE THE OLD ROWS FROM THE BOTTOM OF THE TABLE ....
  for (i=1; i<totalRows; i++)
    {
      tableToSort.deleteRow();
//	  alert(i);
    }
  }
//  End -->
function borra()
{  
//	alert("borra");	
if(confirm("Esta Seguro de Borrar Este Registro???"))
	{
	document.frm1.accion.value="borrar";
	document.frm1.submit();	
	}
}
function acepta()
{	
//	alert("acepta");
	
	if(validar_formulario()==false)
	{
		return;
	}
	document.frm1.accion.value="insertar";
	document.frm1.submit();	
}
function modifica()
{
//	alert("modifica");
	if(confirm("Esta Seguro de Modificar Este Registro???"))
	{

		if(validar_formulario()==false)
		{
			return;
		}
	
	document.frm1.accion.value="modificar";
	document.frm1.submit();
	}
}
function cancela()  // limpiar la pantalla para un nuevo registro
{
	//alert("cancela");
	validar_limpiar();
	document.frm1.accion.value="limpiar_campos";
	document.frm1.submit();	

}
function deshacer()  // limpiar la pantalla para un nuevo registro
{
	//alert("cancela");
	//validar_limpiar();
	if(confirm("Esta Seguro de Eliminar este Dato???"))
	{
		document.frm1.accion.value="deshacer";
		document.frm1.submit();	
	}

}
function validar_limpiar()
{
	for(i=0; i<document.forms[0].elements.length; i++)
	{	
		
		switch (document.forms[0].elements[i].type)
		{
				//********** Caso si es texto  o campo password

			case "text"|| "password":
				document.forms[0].elements[i].value="";				
				break;
			case "hidden":
				document.forms[0].elements[i].value="";
			//alert(document.forms[0].elements[i].name + ""+document.forms[0].elements[i].type);
				break;
			case "select-one":
				document.forms[0].elements[i].value=0;
			//alert(document.forms[0].elements[i].name + ""+document.forms[0].elements[i].type);
				break;
		}
		//document.forms[0].elements[i].value=="";

	} 
	//document.frm1.clear;
}
function b_imagen()
{
//	alert('hola');
	if(confirm("Esta Seguro de Eliminar La Foto de esta Persona???"))
	{
		document.frm1.accion.value="B_imagen";
		document.frm1.submit();
	}
}