//**********************************************************************
//  Biblioteca de funções do sistema BOXNET
//**********************************************************************
//  Funções disponíveis :
//
//  isEmail (STRING s [, BOOLEAN emptyOK])
//  isInteger (STRING s [, BOOLEAN emptyOK])
//	verifica_checks(obj_check, qtde_checks)
//	isEmpty(s)
//	isDigit (c)			Check whether character c is a digit 
//	isWhitespace (s)	Check whether string s is empty or whitespace.
//	stripWhitespace (s)                 Removes all whitespace characters from s.
//	stripCharsInBag (s, bag)            Removes all characters in string bag from string s.
//	pesquisar()			Pesquisa palavra em uma págin html e mostra o resultado destacado
//
//  ChecaCGC()          Verifica se o argumento é um CGC válido
//  CPF()               funcoes para verificacao de CPF 
//**********************************************************************
//
// VARIABLE DECLARATIONS

var digits = "0123456789";
var defaultEmptyOK = false

// whitespace characters
var whitespace = " \t\n\r";



////////////////////////////////////////////////////////////////////////
// Attempting to make this library run on Navigator 2.0,
// so I'm supplying this array creation routine as per
// JavaScript 1.0 documentation.  If you're using 
// Navigator 3.0 or later, you don't need to do this;
// you can use the Array constructor instead.

function makeArray(n) {
//*** BUG: If I put this line in, I get two error messages:
//(1) Window.length can't be set by assignment
//(2) daysInMonth has no property indexed by 4
//If I leave it out, the code works fine.
//   this.length = n;
   for (var i = 1; i <= n; i++) {
      this[i] = 0
   } 
   return this
}



var daysInMonth = makeArray(12);
daysInMonth[1] = 31;
daysInMonth[2] = 29;   // must programmatically check this
daysInMonth[3] = 31;
daysInMonth[4] = 30;
daysInMonth[5] = 31;
daysInMonth[6] = 30;
daysInMonth[7] = 31;
daysInMonth[8] = 31;
daysInMonth[9] = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;


/////////////////////////////////////////////////////////////////////////
// Check whether string s is empty.

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}
/////////////////////////////////////////////////////////////////////////
//
// Returns true if character c is a digit 
// (0 .. 9).

function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}
/////////////////////////////////////////////////////////////////////////
// Removes all characters which appear in string bag from string s.

function stripCharsInBag (s, bag)

{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}
/////////////////////////////////////////////////////////////////////////
// Returns true if string s is empty or 
// whitespace characters only.

function isWhitespace (s)

{   var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}
/////////////////////////////////////////////////////////////////////////
// Removes all whitespace characters from s.
// Global variable whitespace (see above)
// defines which characters are considered whitespace.

function stripWhitespace (s)

{   return stripCharsInBag (s, whitespace)
}
/////////////////////////////////////////////////////////////////////////
//
// isEmail (STRING s [, BOOLEAN emptyOK])
// 
// Email address must be of form a@b.c -- in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isEmail (s)
{   if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
   
    // is s whitespace?
    if (isWhitespace(s)) return false;
    
    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var slength = s.length;
   
    // look for @
    while ((i < slength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= slength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < slength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= slength - 1) || (s.charAt(i) != ".")) return false;
    else return true;

}
/////////////////////////////////////////////////////////////////////////
//
// isInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if all characters in string s are numbers.
//
// Accepts non-signed integers only. Does not accept floating 
// point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.
//
// By default, returns defaultEmptyOK if s is empty.
// 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
/////////////////////////////////////////////////////////////////////////

function isInteger (s)

{   var i;

    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);

        if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
}
/////////////////////////////////////////////////////////////////////////

function verifica_checks_user(obj_check, qtde_checks)
{
	var int_checks = parseInt(qtde_checks);
	var int_total = 0;
	
	for (i=0; i<int_checks; i++)
	{
		if (obj_check[i].checked==true)
		{
			int_total = int_total + 1;
		}
	}
	if (int_total==0)
	{	
		alert('Você deve marcar ao menos\num usuário !!!')
		return false
	}				

	return true
}

/////////////////////////////////////////////////////////////////////////

function verifica_checks_setor(obj_check, qtde_checks){

	var int_checks = parseInt(qtde_checks) ;
	var int_total = 0;
	for (i=0; i<int_checks; i++)
	{
		if (obj_check[i].checked==true)
		{
			int_total = int_total + 1;
		}
	}
	if (int_total==0)
	{	
		alert('Você deve marcar ao menos\numa opção de Setor !!!')
		return false
	}				
	

	return true
}


/////////////////////////////////////////////////////////////////////////

function verifica_checks_empresa(obj_check, qtde_checks){

	var int_checks = parseInt(qtde_checks) ;
	var int_total = 0;
	for (i=0; i<int_checks; i++)
	{
		if (obj_check[i].checked==true)
		{
			int_total = int_total + 1;
		}
	}
	if (int_total==0)
	{	
		alert('Você deve marcar ao menos\numa opção de Empresa !!!')
		return false
	}				
	

	return true
}

/////////////////////////////////////////////////////////////////////////

function verifica_checks_veiculo(obj_check, qtde_checks){

	var int_checks = parseInt(qtde_checks) ;
	var int_total = 0;
	for (i=0; i<int_checks; i++)
	{
		if (obj_check[i].checked==true)
		{
			int_total = int_total + 1;
		}
	}
	if (int_total==0)
	{	
		alert('Você deve marcar ao menos\numa opção de Veículo !!!')
		return false
	}				
	

	return true
}

///////////////////////////////////////////////////////////////////////////////////////////////////////

// isSignedInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if all characters are numbers; 
// first character is allowed to be + or - as well.
//
// Does not accept floating point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// EXAMPLE FUNCTION CALL:          RESULT:
// isSignedInteger ("5")           true 
// isSignedInteger ("")            defaultEmptyOK
// isSignedInteger ("-5")          true
// isSignedInteger ("+5")          true
// isSignedInteger ("", false)     false
// isSignedInteger ("", true)      true

function isSignedInteger (s)

{   if (isEmpty(s)) 
       if (isSignedInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedInteger.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if (isSignedInteger.arguments.length > 1)
            secondArg = isSignedInteger.arguments[1];

        // skip leading + or -
        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;    
        return (isInteger(s.substring(startPos, s.length), secondArg))
    }
}
///////////////////////////////////////////////////////////////////////////////////////////////////////

// isNonnegativeInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is an integer >= 0.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isNonnegativeInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isNonnegativeInteger.arguments.length > 1)
        secondArg = isNonnegativeInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a number >= 0

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) >= 0) ) );
}

////////////////////////////////////////////////////////////////////////////////////////////////////////

// isIntegerInRange (STRING s, INTEGER a, INTEGER b [, BOOLEAN emptyOK])
// 
// isIntegerInRange returns true if string s is an integer 
// within the range of integer arguments a and b, inclusive.
// 
// For explanation of optional argument emptyOK,
// see comments of function isInteger.


function isIntegerInRange (s, a, b)
{   if (isEmpty(s)) 
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);

    // 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); //Problemas ao avaliar 08 e 09....
    var num = eval (s);
    return ((num >= a) && (num <= b));
}


///////////////////////////////////////////////////////////////////////////////////////////////////////

// isYear (STRING s [, BOOLEAN emptyOK])
// 
// isYear returns true if string s is a valid 
// Year number.  Must be 2 or 4 digits only.
// 
// For Year 2000 compliance, you are advised
// to use 4-digit year numbers everywhere.
//
// And yes, this function is not Year 10000 compliant, but 
// because I am giving you 8003 years of advance notice,
// I don't feel very guilty about this ...
//
// For B.C. compliance, write your own function. ;->
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isYear (s)
{   if (isEmpty(s)) 
       if (isYear.arguments.length == 1) return defaultEmptyOK;
       else return (isYear.arguments[1] == true);
    if (!isNonnegativeInteger(s)) return false;
    return ((s.length == 2) || (s.length == 4));
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// isMonth (STRING s [, BOOLEAN emptyOK])
// 
// isMonth returns true if string s is a valid 
// month number between 1 and 12.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isMonth (s)
{   if (isEmpty(s)) 
       if (isMonth.arguments.length == 1) return defaultEmptyOK;
       else return (isMonth.arguments[1] == true);
    return isIntegerInRange (s, 1, 12);
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

// isDay (STRING s [, BOOLEAN emptyOK])
// 
// isDay returns true if string s is a valid 
// day number between 1 and 31.
// 
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isDay (s)
{   if (isEmpty(s)) 
       if (isDay.arguments.length == 1) return defaultEmptyOK;
       else return (isDay.arguments[1] == true);   
    return isIntegerInRange (s, 1, 31);
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// daysInFebruary (INTEGER year)
// 
// Given integer argument year,
// returns number of days in February of that year.

function daysInFebruary (year)
{   // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (  ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
}


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function isDate (year, month, day)
{   // catch invalid years (not 2- or 4-digit) and invalid months and days.
    if (! (isYear(year, false) && isMonth(month, false) && isDay(day, false))) return false;

    // Explicitly change type to integer to make code work in both
    // JavaScript 1.1 and JavaScript 1.2.
    var intYear = parseInt(year);
    var intMonth = parseInt(month);
    var intDay = parseInt(day);

    // catch invalid days, except for February
    if (intDay > daysInMonth[intMonth]) return false; 

    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function datatest(dataent)
{
	var dia = dataent.substring(0,2);
	var mes = dataent.substring(3,5);
	var ano = dataent.substring(6,10);
	var barra_1 = dataent.substring(2,3);
	var barra_2 = dataent.substring(5,6);

	return (isDate(ano, mes, dia) && (barra_1=="/") && (barra_2=="/"));
	
}

function inverte_data(data1)
{
	var d1	= data1.substring(0,2);
	var m1	= data1.substring(3,5);
	var a1  = data1.substring(6,10);
	var dt1 = a1 + m1 + d1;

	return (dt1);
	
}
/////////////////////////////////////////////////////////////////////////

function tipo_navegador()
{
<!--// hide from older browsers
bName = navigator.appName;
bVer = parseInt(navigator.appVersion);

// Determine which browser is being used.
if (bName == "Netscape" && bVer >= 4) br = "n4";
else if (bName == "Netscape" && bVer == 3) br = "n3";
else if (bName == "Microsoft Internet Explorer" && bVer == 3) br = "e3";
else if (bName == "Microsoft Internet Explorer" && bVer == 4) br = "e4";
else if (bName == "Microsoft Internet Explorer" && bVer == 5) br = "e5";
else br = "n3";
        
if (br == "n4" && navigator.mimeTypes["application/x-shockwave-flash"]) 
        br = "n4f" 
        
else if (br == "n3" && navigator.mimeTypes["application/x-shockwave-flash"])
        br = "n3f";
        
return (br);
}
//--> 


function formataNumero(Numero, CasasDecimais) {
	
	var Valor = new String(Numero);
	var r = new RegExp("d", "gi");
	var Multiplo = new String("1000000000000000000000");
	var multiplicador = Multiplo.substr(0, CasasDecimais + 1);

	multiplicador = multiplicador.valueOf();
	Valor = Valor.replace(",", ".");

	if (isNaN(Valor.valueOf())) {
		Valor = new String("0.00000000000000000")
		}

	Valor = Valor.valueOf() * multiplicador;
	Valor = Math.round(Valor.valueOf());
	Valor = Valor.valueOf() / multiplicador;
	Valor = Valor.toString();
	Valor = Valor.replace(".", "d");
	
	var retorno = Valor.search(r);
	
	if (retorno != -1) {
		Valor = Valor + "00000000000000000"
	}
	else {
		Valor = Valor + "d00000000000000000" 
	}
	
	var retorno = Valor.search(r);

	Valor = Valor.substr(0, retorno + CasasDecimais + 1);
	Valor = Valor.replace("d", ",");

	return(Valor);
}		

///////////////////////////////////////////////////////////////////////////
//Verifica se o argumento é um CGC válido
function ChecaCGC (CGC) {

		//ParametroCKCGC
		//CKCGC = '45445210000121'
		//var CKCGC = CGC1 + CGC2 +CGC3
		//var CGC = CKCGC;
		var NewCGC = "";
		//Verifica tamanho do CGC
		if (CGC.length!=14) {
		return false;
		}
	
	//Calcula os dígitos verificadores
	//Guarda os 12 primeiros digitos
	var DVCGC = CGC.substring(0,12);
	//calcula o primeiro digito verificador
	var s1 = 0;
	for (i=1;i<=4;i++) s1 = s1 + (ValChar(DVCGC.charAt(i-1))*(6-i));
	for (i=5;i<=12;i++) s1 = s1 + (ValChar(DVCGC.charAt(i-1))*(14-i));
	r1 = s1 % 11;
	if (r1<2) dv1=0;
	else dv1 = 11 - r1;
	//calcula o segundo digito verificador
	var s2 = dv1*2;
	for (i=1;i<=5;i++) s2 = s2 + (ValChar(DVCGC.charAt(i-1))*(7-i));
	for (i=6;i<=12;i++) s2 = s2 + (ValChar(DVCGC.charAt(i-1))*(15-i));
	r2 = s2 % 11;
	if (r2<2) dv2=0;
	else dv2 = 11 - r2;
	//junta os digitos verificadores
	var DV = "";
	DV = DV + dv1 + dv2;
	//guarda os digitos verificadores do CGC digitado (últimas duas posições no string)
	var NewDV = CGC.substring(12,14)
	if (NewDV==DV) { //se o DV calculado for igual ao digitado, retorna true
		return true
	}
	else {
		return false
	}
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// funcoes para verificacao de CPF 

function CPF(a) {
	
	var numero = "";
	var multipli = 0;
	var soma = 0;
	var cont = 1;
	var cont1 = 10;

	for(cont=0;cont<9;cont++) {
        numero = a.charAt(cont);
        multipli = numero * cont1;
        soma = soma + multipli;
        cont1 = cont1 - 1;
        numero = "";
	}

	soma = soma % 11;
	soma = 11 - soma;
	numero = a.charAt(10);

	if(soma > 9 ) {
		if(numero != 0) {
			return (false);
		}
	}
	else {
		if(soma != numero) {
			return (false);
		}
	}

	multipli = 0;
	soma = 0;
	cont = 1;
	cont1 = 11;

	for(cont=0;cont<11;cont++) {
		numero = a.charAt(cont);
		if(numero != "-") {
			multipli = numero * cont1;
			soma = soma + multipli;
			cont1 = cont1 - 1;
		}
        numero = "";
	}

	soma = soma % 11;
	soma = 11 - soma;
	numero = a.charAt(11);

	if(soma > 9 ) {
		if(numero != 0) {
			return (false);
		}
	}
	else {
		if(soma != numero) {
			return (false);
		}
	}
	return (true);
}

function ValChar(ch) {

	if (ch=="0") return 0
	else if (ch=="1") return 1
	else if (ch=="2") return 2
	else if (ch=="3") return 3
	else if (ch=="4") return 4
	else if (ch=="5") return 5
	else if (ch=="6") return 6
	else if (ch=="7") return 7
	else if (ch=="8") return 8
	else if (ch=="9") return 9
	else return 10
}
