// math.js
// 
// Fichero de funciones matemáticas en JavaScript
//
// isIntegerInRange( s, intMin, intMax )
//                   comprueba si el número s (en formato cadena), está entre los
//                   límites intMin-intMax.
//
// isInteger (s) 
//                   Comprueba que la cadena s, es un entero.
//
// isDigit (c)
//                   Comprueba que el carácter c es un número (0-9).
// 
//
//  ESTAS FUNCIONES NECESITAN TENER DECLARADO (o es recomendable), EL VALOR
//  defaultEmptyOK (valor lógico).
//
function isIntegerInRange (s, intMin, intMax)
    {  
      // isIntegerInRange (STRING s, INTEGER intMin, INTEGER intMax [, BOOLEAN emptyOK])
      // 
      // isIntegerInRange devuelve true si la cadena s es un entero
      // comprendido en el rango de los dos argumentos (inclusive).
      // 
	  // Utiliza la función: isInteger()
	  //                     isEmpty()
      
      if (isEmpty(s) ) 
         if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
         else return (isIntegerInRange.arguments[1] == true);
      // Se comprueba la cadena  
      // Catch non-integer strings to avoid creating a NaN below,
      // which isn't available on JavaScript 1.0 for Windows.
       
	  if (!isInteger(s, false)) return false;
        // Now, explicitly change the type to integer via parseInt
        // so that the comparison code below will work both on 
        // JavaScript 1.2 (which typechecks in equality comparisons)
        // and JavaScript 1.1 and before (which doesn't).
        var num = parseInt (s,10);

	return ((num >= intMin) && (num <= intMax));
    }


   function isInteger (s)

   // isInteger (STRING s [, BOOLEAN emptyOK])
   // 
   // Devuelve true si todos los caracteres de la cadena 
   //          son números.
   //
   // Solo acepta enteros sin signo. No acepta número de coma flotante,
   // notación exponencial, etc.
   //
   // No se usa parseInt porque podría aceptar una cadena con
   // carácteres no numéricos.
   //
   // Por defecto, devuelve defaultEmptyOK si la cadena está vacia.
   //
   // There is an optional second argument called emptyOK.
   // emptyOK is used to override for a single function call
   //      the default behavior which is specified globally by
   //      defaultEmptyOK.
   // If emptyOK is false (or any value other than true), 
   //      the function will return false if s is empty.
   // If emptyOK is true, the function will return true if s is empty.
   //
   // EXAMPLE FUNCTION CALL:     RESULT:
   // isInteger ("5")            true 
   // isInteger ("")             defaultEmptyOK
   // isInteger ("-5")           false
   // isInteger ("", true)       true
   // isInteger ("", false)      false
   // isInteger ("5", false)     true
   //
   // Utiliza la función isDigit()
   //                    isEmpty()

    {   var i;

      if (isEmpty(s) ) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);

      // Busca a través de los caracteres de la cadena 
      // uno a uno haste que encuentre un carácter NO-NUMERICO.
      // Si eso ocurre devuelve falso.

      for (i = 0; i < s.length; i++)
       {   
        // Check that current character is number.
        var c = s.charAt(i);

        if (!isDigit(c)) return false;
       }

       // Todos los caracteres son números.
    return true;
    }
	 
   function isDigit (c)
    {  
	  // Devuelve true si el carácter es un dígito
      // (0 .. 9).

	  return ((c >= "0") && (c <= "9"))
    } 

	function FormatNumberEspanol( cNumber , intDecimales )
	// Esta función nos devuelve formateada una cifra (enviada como carácter)
	// a formato español independientemente de como estén configurados los
	// regional settings del servidor o del cliente.
	//
	// Parámetros:
	//             cNumber : El número (char), a formatear.
	//             intDecimales: Número de decimales que deseamos que se devuelvan
	//
	{ 
	   var cNumberFormat = "";
	   var i = 1;
	   var cDigito = "";
	   var cLength = cNumber.length
	   var nPosDecimal = 0;
	   var cParteDecimal = "";
	   var cParteEntera  = "";
       var cParteDecFin = "";
	    
	   // Si sólo le envio el número sin especificar los decimales
	   // trunco estos últimos.
	   // intDecimales = 0
	   if (FormatNumberEspanol.arguments.length == 1) intDecimales = 0
	   
	   // Primero quito los no dígitos (excepto el punto decimal o la coma)
	   // y transformo el punto decimal en coma
	   //
	   for (i = 0; i < cNumber.length; i++)
      {   
        // Comprueba que son dígitos o punto decimal. 
        cDigito = cNumber.charAt(i); 
        if ( ( isDigit( cDigito ) ) || ( cDigito == "." )|| ( cDigito == "," ) )
		{
		if (cDigito == " ") cDigito = "";
		if (cDigito == ".") cDigito = ",";
		
		cNumberFormat += cDigito;
         }    
       }

	   // Busco la posición de la coma decimal
	   nPosDecimal = 0;
	   while (( nPosDecimal < cLength) && (cNumberFormat.charAt(nPosDecimal) != "," ))
        { nPosDecimal++
        }

       cParteDecimal = cNumberFormat.substring( nPosDecimal+1,cLength )
	   cParteEntera  = cNumberFormat.substring( 0,nPosDecimal)
       
	   
       
	   if ( intDecimales == 0 )
	   {
	     cParteDecFin = "";
		 
       }
       else
	   {
	    if ( cParteDecimal.length < intDecimales ) 
	    {
	     // Si la longitud de de la parte decimal es menor de la requerida
		 // relleno por la derecha con ceros lo restante.
		 // 
		 cParteDecFin = ","+cParteDecimal;
	     i = 0
		 for ( i = cParteDecimal.length; i < intDecimales; i++) cParteDecFin += "0";   
	    }
		// Si la parte decimal es igual o mayor de la solicitada devuelvo
		// el número de carácteres solicitados
		//
		else cParteDecFin = ","+cParteDecimal.substring( 0, intDecimales  );  
		 
	   }
	   cParteEntera = PonPuntoMiles( cParteEntera  );
	   
	   cNumberFormat = cParteEntera + cParteDecFin;
	   
	return cNumberFormat;
	}

	function PonPuntoMiles( cNumber  )
	{ 
	   var cNumberFormat = "";
	   var i = 1;
	   var nPos = 1;
	   
	   var cDigito = "";
	   var cLength = cNumber.length

	   // primero busco el delimitador decimal
	   for ( i = cLength -1 ; i >=  0; i--)
	     {
		   cDigito = cNumber.charAt(i);
		   if (( nPos == 3 ) && (i != 0))
		   {
		      cDigito = "."+cDigito;
			  nPos = 1;
		   }
		   else  nPos++;

		   
		   cNumberFormat = cDigito + cNumberFormat
		   
		 }
       
       
	   
	return cNumberFormat;
	}
	
	// Comprueba que si la cadena está vacia.
    function isEmpty(s)
    {   return ((s == null) || (s.length == 0))
    }