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 = "0123456789abcdefghijlkmnopqrstuvwxyzABCDEFGHIJKMNOPQRSTUVWXYZ@.-_"
		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.');
		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); 
}





// Funciones para la encuesta
function MM_openBrWindow(theURL,winName,features, myWidth, myHeight, isCenter) 
{
	if(window.screen)if(isCenter)if(isCenter=="true")
	{
		var myLeft = (screen.width-myWidth)/2;
		var myTop = (screen.height-myHeight)/2;
		features+=(features!='')?',':'';
		features+=',left='+myLeft+',top='+myTop;
	}
	window.open(theURL,'bienvenida','width='+myWidth+',height='+myHeight);
	
}

function FormatCurrency(objNum)
   {
        var num = objNum.value.replace('$','');
        var ent, dec, dot;
        if (num != '' && num != objNum.oldvalue)
        {
             num = MoneyToNumber(num);
             if (!isNaN(num))
             {
                  var ev = (navigator.appName.indexOf('Netscape') != -1)?Event:event;
            ent = num.split('.')[0];
            dec = num.split('.')[1];
            if (dec || ev.keyCode == 190)
            {
                 dot = '.';
                 if (dec.toString().length > 2) dec = dec.toString().substr(0,2);
            }
            else
            {
                 dec = '';
              dot = '';
            }
                  objNum.value = AddCommas(ent) + dot + dec;
                  objNum.oldvalue = objNum.value;
             }
          objNum.value =  objNum.oldvalue;
        }
   }
 
    function MoneyToNumber(num)
   {
        return (num.replace(/,/g, ''));
 
   }
 
    function AddCommas(num)
   {
        numArr=new String(num).split('').reverse();
        for (i=3;i<numArr.length;i+=3)
        {
             numArr[i]+=',';
        }
        return numArr.reverse().join('');
   }
 
  function number_onblur(objNum)
  {
       var num = objNum.oldvalue;
    if (num.charAt(num.toString().length-1) == '.') num = num.replace('.','');
    objNum.value = "$" + num;
  }
 




function validarcontactos()
{  
	var Control;
	var Dato;
	Control = document.frmcontactos.tblcont_nombre;
	Dato = strTrim(Control.value,TRIM_BOTH);
	if(Dato.length == 0)
	{
		alert("Ingrese el nombre");
		Control.focus();
		return false;
	}
	
	Control = document.frmcontactos.tblcont_apellido;
	Dato = strTrim(Control.value,TRIM_BOTH);
	if(Dato.length == 0)
	{
		alert("Ingrese el nombre");
		Control.focus();
		return false;
	}
	
	Control = document.frmcontactos.tblcont_email;
	Dato = strTrim(Control.value,TRIM_BOTH);
	if(Dato.length == 0)
	{
		alert("Ingrese el email");
		Control.focus();
		return false;
	}
	
	if(!ValidarEmail(Control, "")){
		alert("Ingrese el email");
		Control.focus();
		return false;
		
	}
	Control = document.frmcontactos.tblcont_comentario;
	Dato = strTrim(Control.value,TRIM_BOTH);
	if(Dato.length == 0)
	{
		alert("Ingrese el comentario");
		Control.focus();
		return false;
	}
	
	document.frmcontactos.submit();
	return true;
}


function mostrarImagen(valor, x, y)
{
	enlace = '../imagenes/'+valor;
	MM_openBrWindow(enlace,'Equitana','scrollbars=no', x, y,'true');
}

function formatNumber(num,prefix){
    prefix = prefix || '';
    num += '';
    var splitStr = num.split('.');
    var splitLeft = splitStr[0];
    var splitRight = splitStr.length > 1 ? '.' + splitStr[1] : '';
    var regx = /(\d+)(\d{3})/;
    while (regx.test(splitLeft)) {
    splitLeft = splitLeft.replace(regx, '$1' + ',' + '$2');
    }
    return prefix + splitLeft + splitRight;
    }

function unformatNumber(num) {
    return num.replace(/([^0-9\.\-])/g,'')*1;
    } 
// Fin de las funciones
