//Esta función devuelvefecha y hora actuales
function GetTimeStamp() 
{
    // proposito: Devuelvo un timestap
    // parametros: GetTimeStamp < Fecha que espera SQL
    var datFecha = new Date();
    var strYear = datFecha.getYear();
    var strMonth = pad((datFecha.getMonth() + 1).toString(), 2, "right", "0");
    var strDate = pad(datFecha.getDate().toString(), 2, "right", "0");
    var strHours = pad(datFecha.getHours().toString(), 2, "righ","0");
    var strMinutes = pad(datFecha.getMinutes().toString(), 2, "right", "0");
    var strSeconds = pad(datFecha.getSeconds().toString(), 2, "right", "0");

    return (strYear + "-" + strMonth + "-" + strDate + " " + strHours + ":" + strMinutes + ":" + strSeconds);
}

function EnviarForm() 
{
//Seteo la fecha Actual en una variable de fecha de un formulario (de name=formAlta)
//y luego hago un submit sobre el formulario
    formAlta.fecha.value = GetTimeStamp();
    formAlta.submit();
}

function pad(string, number, align, fill) 
{
// Propósito: left padding of a string for a number of times (with fill)
// Parametros: string= string to pad
//			   number= quantity of positions to pad
//			   align= alignment of the string

    if (!fill) 
	{
       fill = " ";
    }
	while (string.length < number) 
	{
		if (align == "left") 
		{
			string += fill.substr(0,1);
		} 
		else 
		{
			string = fill.substr(0,1) + string;
		}
	}
	return string;
}

function EnviarFormB(id) 
{
//Setea el TimeStamp en variables de fecha y el id, y pasa los datos 
//de las variables del formulario a un array
//para luego abrir un showModalDialog, que es un tipo especial de ventana
    BajaForm.fecha.value = GetTimeStamp();
    BajaForm.fechaM.value = GetTimeStamp();
    BajaForm.id.value = id;
    arrDatos = new Array();
    arrDatos.push(BajaForm.fechaM.value);
    arrDatos.push(BajaForm.fecha.value);
    arrDatos.push(BajaForm.id.value);
    showModalDialog('./SMD.jsp',arrDatos,'dialogWidth: 30em; dialogHeight: 12em; help: 0; status: 0; resizable:0; center:1');      
}

function cerrar()
{
//Cierra una ventana
    window.close();
}

function trim(strText) //Saca los espacios a un String
{ 
    //Saca los espacios delante del string
    while (strText.substring(0,1) == ' ') 
        strText = strText.substring(1, strText.length);

    //Saca los espacios detras del string
    while (strText.substring(strText.length-1,strText.length) == ' ')
        strText = strText.substring(0, strText.length-1);

          return strText;
}

function toUp(strTexto) 
{
    //Recibe un string y devuelve el mismo string todo en mayúscula
    strTexto = strTexto.toUpperCase();
    strTexto = strTexto.replace(/Á/g,"A");
    strTexto = strTexto.replace(/É/g,"E");
    strTexto = strTexto.replace(/Í/g,"I");
    strTexto = strTexto.replace(/Ó/g,"O");
    strTexto = strTexto.replace(/Ú/g,"U");
    return strTexto;
}

function abreVentana(url,target,width,height) 
{
//Abre una ventana centrada, según los parámetros de url
//target, width (ancho de la ventana) y height (alto de la ventana)
    LeftPosition = (screen.width) ? (screen.width-width)/2 : 0;
    TopPosition = (screen.height) ? (screen.height-height)/2 : 0;
    //var woptions='toolbar=no,directories=no,menubar=no,location=no,resizable=yes,scrollbars=yes,status=no,width=' + width + ',height=' + height;
    var woptions='toolbar=no,directories=no,menubar=no,location=no,resizable=no,scrollbars=yes,status=no,width='+width+',height='+height+',top='+TopPosition+',left='+LeftPosition;
    var FLOAT=open(url,target,woptions);
    if(FLOAT.focus!=null) 
        FLOAT.focus();
}

function Chequear(campo)
{
//función que chequea si un campo es numérico
//según una máscara con la expresión regular
//y devuelve true o false según sea numérico o no
     var Mask;
    Mask = /^([0-9]{0,50})$/i;

    if (! Mask.test(campo)) 
       {
	campo = "";
	//campo.focus();
	return false;
      }
    return true;
}

function checkAmount(amount) {
    if(!checkDecimal(trim(amount)))
        return false;
    else {
        rep_amount = amount.replace(".","");
        if(!Chequear(trim(rep_amount))) {
            return false;
        }
        else if(amount <= 0)
            return false;
    }
    return true;
}

function checkDecimal(amount) {
    point = 0;
    for(i=0;i<amount.lenght;i++) {
        if(amount[i] == ".")
            point++;
    }
    if(point>1)
        return false;
    else
        return true;
}

function ValidarFecha(strAno, strMes, strDia) 
{
// Función que valida que una fecha ingresada sea correcta
    var Error = "";
    if (strAno < 1900) 
    { 
	Error = "Error1"; 
    }
    else 
    {
        if (parseInt(strMes) > 12) 
	{ 
            Error = "Error2"; 
	}
        else 
	{
            if (parseInt(strDia) > 31 || (parseInt(strDia) > 29 && parseInt(strMes) == 2) || 
               (parseInt(strDia) == 31 && (parseInt(strMes) == 4 || parseInt(strMes) == 6 || parseInt(strMes) == 9 ||
                parseInt(strMes) == 11))) 
            { 
		Error = "Error3"; 
            }
            else 
            { 
                if (parseInt(strAno)%4 != 0 && parseInt(strMes) == 2 && parseInt(strDia) == 29) 
		{ 
                    Error = "Error4"; 
		}
                else 
		{ 
                    Error = ""; 
		}
            }
        }
    }
    return Error;
}

function validateDate(date)
{
    if(date.length!=10)
        return false;
    dia = date.substring(0,2);
    mes = date.substring(3,5);
    anio = date.substring(6,10);
    if(!Chequear(dia) || !Chequear(mes) || !Chequear(anio))
        return false;
    else
    {
        if(date.substring(2,3)!='/' || date.substring(5,6)!='/')
            return false;
        else
        {
            if(!verifyDate(anio, mes, dia))
                return false;
        }
    }
    return true;
}

function verifyDate(strAno, strMes, strDia) 
{
// Función que valida que una fecha ingresada sea correcta
    if (strAno < 1900) 
    { 
	return false; 
    }
    else 
    {
        if (parseInt(strMes) > 12) 
	{ 
            return false; 
	}
        else 
	{
            if (parseInt(strDia) > 31 || (parseInt(strDia) > 29 && parseInt(strMes) == 2) || 
               (parseInt(strDia) == 31 && (parseInt(strMes) == 4 || parseInt(strMes) == 6 || parseInt(strMes) == 9 ||
                parseInt(strMes) == 11))) 
            { 
		return false; 
            }
            else 
            { 
                if (parseInt(strAno)%4 != 0 && parseInt(strMes) == 2 && parseInt(strDia) == 29) 
        	{ 
                    return false; 
		}
            }
        }
    }
    return true;
}

function MayorActual(strAno, strMes, strDia) 
{
    //Controla si la fecha pasada es mayor al la fecha en el momento
    var Error = "";
    var datFecha = new Date();
    var strYear = datFecha.getYear();
    var strMonth = pad((datFecha.getMonth() + 1).toString(), 2, "right", "0");
    var strDate = pad(datFecha.getDate().toString(), 2, "right", "0");
    var FechaActual = strYear + "" + strMonth + "" + strDate;
    var FechaPasada = strAno + "" + strMes + "" + strDia;

    if(FechaActual < FechaPasada) 
	{
        Error = "Error";
    }
    return Error;
}

function compareDates(inicialDate, finalDate) 
{
    diaI = inicialDate.substring(0,2);
    mesI = inicialDate.substring(3,5);
    anioI = inicialDate.substring(6,10);

    diaF = finalDate.substring(0,2);
    mesF = finalDate.substring(3,5);
    anioF = finalDate.substring(6,10);

    fechaI = anioI*10000 + mesI*100 + anioI;
    fechaF = anioF*10000 + mesF*100 + anioF;

    if(fechaF < fechaI)
        return false;
    else
        return true;
}

function PasarFocus(cantidad, maximo, siguiente) 
{
//Pasa el foco alsiguente campo de input cuando se completa
//la longitud máxima
    if (cantidad == maximo) 
	{
        document.all[siguiente].focus();
    }
}

function CuentaLetras(nombre,formulario,div_cuenta,caracteres)
{
    /* nombre = nombre del TEXTAREA */
    /* formulario = valor del largo del textarea */
    /* div_cuenta = nombre del DIV que decrementa */
    /* caracteres = caracteres para controlar y decrementar del div */

    if ((formulario.length) <= caracteres)
	{
        document.all[div_cuenta].innerText = caracteres - formulario.length; //decremento el valor del Div
    }
	else
	{
        window.alert("No puede ingresar mas de " + caracteres + " Caracteres"); //Alerta para el control del textarea
        document.all[nombre].value = formulario.substring(0,caracteres); //controlo que no se pase del valor el textarea
    }
}

function SoloString(s_valor) 
{
// Funcion que evalua si el valor pasado es una cadena de caracteres, que no contenga ningun valor numérico
// Devuelve 0 si no tiene numeros, sino la cantidad de numeros encontrados.
    i_error = 0;
    for(i=0; i<s_valor.length; i++) 
	{
        if(isFinite(s_valor.charAt(i))) 
		{
            i_error++;
        }
    }
    return i_error;
}

function ValidaEmail(Email) 
{
//Valida que una dirección de email ingresada sea correcta
  var strMail = Email;
  var strNom = "";
  var strDom = "";
  if (strMail.indexOf("@") == -1) 
  {
    return false;
  }
  else 
  {
    strNom = strMail.split("@");
    if (strNom[0] == "") 
	{
        return false;
    }
	else
	{
        strDom = strNom[1].split(".");
        if (strDom[0] == "") 
		{
            return false;
        }
		else
		{
            if (strDom[1] == "") 
			{
                return false;
            }
			else
			{
            	return true;
            }
        }
    }
  }
}
