var TRIM_LEFT  = 0x0001;
var TRIM_RIGHT = 0x0002;
var TRIM_BOTH  = TRIM_LEFT | TRIM_RIGHT;

function setPointer(theRow, thePointerColor)
{
    if (thePointerColor == '' || typeof(theRow.style) == 'undefined') {
        return false;
    }
    if (typeof(document.getElementsByTagName) != 'undefined') {
        var theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        var theCells = theRow.cells;
    }
    else {
        return false;
    }

    var rowCellsCnt  = theCells.length;
    for (var c = 0; c < rowCellsCnt; c++) {
        theCells[c].style.backgroundColor = thePointerColor;
    }

    return true;
} 


function strTrim( varText, side )
	{

	var i = 0;
	var j = varText.length - 1;
	if( side & TRIM_LEFT )
  	  {
	    for( i = 0; i < varText.length; i++ )
		{
		 if( varText.substring( i, i+1 ) != " " && varText.substring( i, i+1 ) != "\t")
		   {
		     break;
		   }
		}
	}

      if( side & TRIM_RIGHT )
	 {
	   for( j = varText.length - 1; j >= 0; j-- )
	     {
		if( varText.substring( j, j+1 ) != " " && varText.substring( j, j+1 ) != "\t")
		  {
		   break;
		  }
	     }
	  }

      if( i <= j )
	 return( varText.substring( i, (j+1) ) );
      else
	 return("");
}



/*****************************************************************************************
'Descripcion:
'		Funcion para validar que el texto ingresado en un campo texto,
'		corresponda a una dirección válida de correo (e-mail)
'.........................................................................................
'Parametros:
'		Campo:		Control con el valor a validar
'		Mensaje:	Cadena con el nombre descriptivo del control, usada para mostrar
'					un mensaje personalizado.
'.........................................................................................
'Validaciones:
'		- Los caracteres que contiene la cuenta de correo deben estar dentro de la siguiente lista
'			"0123456789abcdefghijlkmnopqrstuvwxyz@.-_"
'		- El primer y último caracter no pueden ser alguno de los caracteres "@.-_"
'		- Los caracteres anterior y posterior a la arroba (@), no pueden ser "@.-_"
'		- La cadena NO puede contener más de una arroba (@)
'		- La cadena debe contener al menos UNA arroba (@)
'		- La cadena NO puede contener espacios vacíos (" ")
'		- Después del último punto, debe haber AL MENOS 2 caracteres
*****************************************************************************************/
function ValidarEmail(Campo, Mensaje)
	{
	var perfect = true;

	with (Campo)
		{
		// Validar que los caracteres que contiene la cuenta de correo
		// esten dentro de los caracteres de la siguiente lista
		var car_validos = "0123456789abcdefghijlkmnopqrstuvwxyzABCDEFGHIJKMNLOPQRSTUVWXYZ@.-_"
		var car_otros = "@.-_";

		for (var i=0; i < value.length; i++) {
			var ch = value.substring(i, i+1);
			if (car_validos.indexOf(ch) == -1) perfect = false;
		}

		apos = value.indexOf("@");
		lastpos = value.length-1;

		// Validar primer y ultimo caracter
		var car1 = value.substring(0, 1);
		var car2 = value.substring(lastpos, lastpos+1);
		if ((car_otros.indexOf(car1) != -1) || (car_otros.indexOf(car2) != -1)) perfect = false;

		// Validar anterior y siguiente caracter despues de "@"
		car1 = value.substring(apos-1, apos);
		car2= value.substring(apos+1, apos+2);
		if ((car_otros.indexOf(car1) != -1) || (car_otros.indexOf(car2) != -1)) perfect = false;

		// Buscar si existe otro simbolo "@" en el campo
		var subcadena = value.substring(apos + 1, 100);
		a2pos = subcadena.indexOf("@");
		spacepos = value.indexOf(" ");
		dotpos = value.lastIndexOf(".");

		posh=subcadena.indexOf(".");

		//if (apos < 1 || a2pos != -1 || dotpos - apos < 2 || lastpos - dotpos > 3 || lastpos - dotpos < 2 || spacepos != -1) {
		if (apos < 1 || a2pos != -1 || lastpos - dotpos < 2 || spacepos != -1||posh==-1) perfect = false;
		}

	if (!perfect) 
		{
		//alert('\nEl valor de ' + Mensaje + ' (E-Mail) es inválido.\n\nPor favor corrige la información.');
		alert(Mensaje);
		Campo.focus();
		return false;
		}

	return true;

	}
/**************************************************************************************/
function ValidarFecha(Anno, Mes, Dia, Dato) 
	{

	var intAnno = parseInt(Anno);
	var intMes = parseInt(Mes);
	var intDia = parseInt(Dia);

	// Validar que los valores no sean igual a cero
	if ((Anno == 0) || (Mes == 0) || (Dia == 0)) 
		{
		alert('Debes elegir los valores para el mes, el día y el año de ' + Dato);
		return false;
		}

	// Validar que, en un año NO bisiesto, el número de días del mes de Febrero no sea mayor que 28
	if (((intAnno % 4) != 0) && (intMes == 2) && (intDia > 28)) 
		{
		alert('El mes de Febrero no puede contener más de 28 días.\n\nPor favor, corrije la información de ' + Dato);
		return false;
		}

	// Validar que, en un año bisiesto, el número de días del mes de Febrero no sea mayor que 29
	if (((intAnno % 4) == 0) && (intMes == 2) && (intDia > 29)) 
		{
		alert('El mes de Febrero no puede contener más de 29 días.\n\n Por favor, corrije la información de ' + Dato);
		return false;
		}

	// Validar que el dia sea válido para el mes elegido, no mayor que 30
	if ( ((intMes == 4) || (intMes == 6) || (intMes == 9) || (intMes == 11)) && (intDia > 30) ) 
		{
		alert('El mes seleccionado sólo contiene 30 días.\n\nPor favor, corrije la información de ' + Dato);
		return false;
		}

	return true;
	}

/******************************************************************************************
'Fecha : Mayo 28/2001
'.........................................................................................
'Descripcion:
'		Verifica que una cadena contenga únicamente caracteres numéricos.
'		Retorna "true" ó "false" según sea el caso
'.........................................................................................
'Parametros:
'		- str : Cadena que se quiere evaluar
'.........................................................................................
'Validaciones: 
'		- Ninguno de los caracteres que componen la cadena debe ser diferente de los
'		  caracteres de la lista "0123456789"
*****************************************************************************************/
function isNumeric(str)
	{
	for (var i=0; i < str.length; i++) 
		{
		var ch = str.substring(i, i+1);
		if(ch < "0" || ch > "9") 
			{
			return false;
			}
		}
		return true;
	}



function EjecutarScript(Script)
{ 
  window.location = Script;
}



function VentanaConfirmacion(Mensaje)
{
  if(confirm(Mensaje)==false)
	 return false;
  return true;
}

function EliminarVentana(Mensaje,Script)
{
  if(confirm(Mensaje))
	  if(confirm("Esta seguro que desea eliminar el registro"))
	     EjecutarScript(Script); 
}


function handleResponse() 
{
    if(http.readyState == 4)
	{
        var response = http.responseText;
        var update = new Array();

        if(response.indexOf('|' != -1)) 
		{
            update = response.split('|');
			mostrarError(http.responseText);
        }
    }
}


function VReg(valor,tipoV,opc1) 
{	
	Vlr = valor;
	Vopc1 = opc1;
	
	http.open('get', 'validarDato.php?valor='+Vlr+'&tpVl='+tipoV+'&Obj='+Vopc1);
	http.onreadystatechange = handleResponse;
	http.send(null);
	
}

function validaCampoEmail(objec){
	if (!validaCampo(objec))
		return false;
	else
		if(!ValidarEmail(objec,"Direccion de correo mal ingresada")){	
			document.getElementById(objec.name).style.backgroundColor="#e3b6be";
			objec.focus();
			return false;   
		}
	
	document.getElementById(objec.name).style.backgroundColor="#FFFFFF";
	return true;
}

function validaCampo(objec){
	Dato = strTrim(objec.value,TRIM_BOTH);
	if (Dato.length == 0)
	{
		alert("Ingrese "+objec.name.substring(2, objec.name.length));
		//document.getElementById(objec.name).className="texterror";
		document.getElementById(objec.name).style.backgroundColor="#e3b6be";
		objec.focus();
		return false;
	}
	document.getElementById(objec.name).style.backgroundColor="#FFFFFF";
	return true;
}

function validarForma(forma){
	for (var i=0; i<forma.elements.length; i++)
	{
		if (forma.elements[i].name.substring(0,2) == 'O_')
		{
			if (!validaCampo(forma.elements[i]))
			{
				return false
			}
		}
		else if (forma.elements[i].name.substring(0,2) == 'E_')
		{
			if (!validaCampoEmail(forma.elements[i]))
			{
				return false
			}
		}
	}
	return true;
}

function cargarContenido(forma,url){
	//alert("url "+url+" "+forma.name);
	//return false;
	var valPost="";
	var contenedor;
	contenedor = document.getElementById('msgrespuesta');
	for (var i=0; i<forma.elements.length; i++)
	{
		valPost +=forma.elements[i].name+"="+forma.elements[i].value+"&";
	//t2 = forma.elements[1].value;
	}
	ajax=nuevoAjax();
	ajax.open("POST", url,true);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			contenedor.style.top=topScroll();
			contenedor.style.display='block';
			contenedor.innerHTML = ajax.responseText;
	 	}
	}
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	//ajax.send("t1="+t1+"&t2="+t2)
	ajax.send(valPost+"forma="+forma.name)
}

function nuevoAjax(){
	var xmlhttp=false;
 	try {
 		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 	} catch (e) {
 		try {
 			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 		} catch (E) {
 			xmlhttp = false;
 		}
  	}

	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
 		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}

function ocultarMensaje(id){
	id.style.display='none';
}

function topScroll(){
	return document.body.scrollTop+10+'px';
}

function sendForma(forma, url){
		if (validarForma(forma))
			cargarContenido(forma,url);
}


function PrintContent(ctrl)
{
	//alert(ctrl);
	var DocumentContainer = ctrl;
	//alert(DocumentContainer);
	var WindowObject = window.open('', "TrackHistoryData", 
						  "width=420,height=225,top=250,left=345,toolbars=no,scrollbars=no,status=no,resizable=no");
	//alert(ctrl);
	//alert(DocumentContainer);
	WindowObject.document.write(DocumentContainer.innerHTML);
	//alert(ctrl);
	WindowObject.document.close();
	WindowObject.focus();
	WindowObject.print();
	WindowObject.close();
}
