/*
 * Validações em geral para os campos
 * @author Marison Souza Gomes
 * Copyright Maven IT Solutions 2006	
*/

var agente = window.navigator.userAgent.toLowerCase();
 	
function getFieldLength(field){
    if(!field) return 0;
	var val = field.value;
	val = val.replace(/^\s+/,"");
	val = val.replace(/\s+$/,"");
	field.value = val;
	return field.value.length;
}
function allowSpecific(e,strChars) {
	var key;
	var keychar;

	if (window.event) key = window.event.keyCode;
	else if (e)	key = e.which;
	else return true;

	keychar = String.fromCharCode(key);
	keychar = keychar.toLowerCase();
	if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
		return true;
	else return (strChars.indexOf(keychar) > -1)
}
function allowFilter(e){
	var key=0;
	if (window.event) key = window.event.keyCode;
	else if (e)	key = e.which;
	return key!= 46 && key!=8 && key!=32 && key!=9 && key!=0 && key!=39 && key!=37;
}

function allowRegExp(e,strRegExp) {
	var key,keychar;
	if (window.event) key = window.event.keyCode;
	else if (e)	key = e.which;
	else return true;

	var reg = new RegExp(strRegExp)
	keychar = String.fromCharCode(key);
	var matchedArr = keychar.match(reg)
	return (matchedArr != null);
	
}
function allowAlphaNumeric(e) {
    if(!allowFilter(e)) return true;    
	var strChars = 'abcdefghijklmnopqrstuvwxyz0123456789'
	if (allowAlphaNumeric.arguments.length == 2) strChars += allowAlphaNumeric.arguments[1];
	return allowSpecific(e,strChars)
}
function allowNumeric(e) {
	if(!allowFilter(e)) return true;
	var strChars = '0123456789';
	if (allowNumeric.arguments.length == 2) strChars += allowNumeric.arguments[1];
	return allowSpecific(e,strChars)
}
function allowZipcode(e,value) {
	if(!allowFilter(e)) return true;
	//restricts entry to numbers and a dash only in the 6th position
	if (value.length == 5) return allowNumeric(e,'-'); //allow numbers in the 6th position because field might be highlighted (from tabbing in).  Can't determine how to detect if highlight is on
	else return allowNumeric(e);
}
function allowCurrency(e) {		
		if(!allowFilter(e)) return true;
		return allowRegExp(e,'[0-9\.,]');
}
function allowDate(e) {
	if(!allowFilter(e)) return true;
	return allowRegExp(e,'[0-9\/]');
}
function allowPhoneNumber(e) {
	if(!allowFilter(e)) return true;
	return allowRegExp(e,'[0-9\/-]');
}

function allowAlpha(e) {
	if(!allowFilter(e)) return true;
	var strChars = 'abcdefghijklmnopqrstuvwxyz'
	if (allowAlpha.arguments.length == 2) strChars += allowAlpha.arguments[1];
	return allowSpecific(e,strChars)
}

function checkCurrency(theCur){
  return theCur && theCur.value.match(/^(\d{1,8})(\,\d{1,3})*$/g) || theCur.value.match(/^(\d{1,8})(\.\d{1,3})*$/g);
}

function validaCNPJ(field) {
			     var CNPJ=field.value;
                 erro = new String;
                 if (CNPJ.length < 14) erro += errorCNPJ_1;
                 
                 //substituir os caracteres que não são números
               if(document.layers && parseInt(navigator.appVersion) == 4){
               	    
                       x = CNPJ.substring(0,2);
                       x += CNPJ.substring(3,6);
                       x += CNPJ.substring(7,10);
                       x += CNPJ.substring(11,15);
                       x += CNPJ.substring(16,18);
                       CNPJ = x;
               } else {
                       CNPJ = CNPJ.replace(".","");
                       CNPJ = CNPJ.replace(".","");
                       CNPJ = CNPJ.replace("-","");
                       CNPJ = CNPJ.replace("/","");
               }
               var nonNumbers = /\D/;
               if (nonNumbers.test(CNPJ)) erro += errorCNPJ_2;
               var a = [];
               var b = new Number;
               var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
               for (i=0; i<12; i++){
                       a[i] = CNPJ.charAt(i);
                       b += a[i] * c[i+1];
 }
               if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
               b = 0;
               for (y=0; y<13; y++) {
                       b += (a[y] * c[y]);
               }
               if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
               if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
                       erro +=errorCNPJ_3;
               }
               if (erro.length > 0){
                       return erro;
               } else {
						return null;
               }
               return null;
       }

function checkOnlyAlphaNumeric(field){
	if(field && field.type!="hidden"){
		return field.value.match(/^[\w]+$/);
	}else {
		return true;
	}
}
function checkValidFieldNumeric(field,nullable) {
	if(nullable && nullable == true && getFieldLength(field)==0){
		return true;
	}
	if((field == null || !field)){
		return true;
	}
	var isValid=true;
	var fieldValue = trim(field.value);
	if (fieldValue != "") {
		isValid = !isNaN(fieldValue);
	}
	return isValid;
}

function getRange(){
	var range = null;
	if (window.getSelection)	
		range = window.getSelection();	
	else if (document.getSelection)	
		range = document.getSelection();	
	else if (document.selection)	
		range = document.selection.createRange();

	return range;
}

function getSel()
{
	var txt = '';
	var foundIn = '';
	if (window.getSelection)	
		txt = window.getSelection();	
	else if (document.getSelection)	
		txt = document.getSelection();	
	else if (document.selection)	
		txt = document.selection.createRange().text;	
	else return;
	return txt;
}

/*--------------------------------------------------------------------------------
 Type Specific Formatting
 These functions are called after validations
--------------------------------------------------------------------------------*/

function validaEmail(campo) {
	if (campo && (campo.value == "" || campo.value.length<=0)) {
	 return true;
	} else {
		prim = campo.value.indexOf("@")
		if(
		  (campo.value.indexOf("..") > 0)
		||(campo.value.indexOf(")") > 0)
		||(campo.value.indexOf("(") > 0)
		||(campo.value.indexOf("]") > 0)
		||(campo.value.indexOf("[") > 0)
		||(campo.value.indexOf("/") > 0)
		||(campo.value.indexOf(".com.br.") > 0)
		||(campo.value.indexOf("@.") > 0)
		||(campo.value.indexOf(".@") > 0)
		||(campo.value.indexOf("hotmeil.com") > 0)
		||(campo.value.indexOf("zipmeil.com") > 0)
		||(campo.value.indexOf(" ") != -1)
		||(campo.value.indexOf(".") < 1)
		||(campo.value.indexOf("@",prim + 1) != -1)
		||(prim<2)
			) {
			return false;
		}
	}
		return true;
}

function currencyFormat(fld, milSep, decSep, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event&&agente.indexOf('msie')==-1) ? e.which : e.keyCode;
	if(whichCode == undefined) whichCode = e.keyCode;
	
	if (!allowFilter(e)) return true;  // valid type
		key = String.fromCharCode(whichCode);  // Get key value from key code
	if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
	if(fld.value.length>=10) return false;
	
		if(agente.indexOf('msie')!=-1){
			range=getRange();
			if(range){
			try{
				range.execCommand("Cut");
				}catch(e){}
			}
		}
		len = fld.value.length;	
	
	for(i = 0; i < len; i++)
		if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
		aux = '';
	for(; i < len; i++)
		if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
		aux += key;
		len = aux.length;

	if (len == 0) fld.value = '';
	if (len == 1) fld.value = '0'+ decSep + '0' + aux;
	if (len == 2) fld.value = '0'+ decSep + aux;
	if (len > 2) {
		aux2 = '';
		for (j = 0, i = len - 3; i >= 0; i--) {
			if (j == 3) {
				aux2 += milSep;
				j = 0;
			}
		aux2 += aux.charAt(i);
		j++;
		}
	fld.value = '';
	len2 = aux2.length;
	for (i = len2 - 1; i >= 0; i--)
		fld.value += aux2.charAt(i);
		fld.value += decSep + aux.substr(len - 2, len);
	}
	return false;
}

function FmascTempoReal(ConteudoCampo)
{
var whichCode = (window.Event&&agente.indexOf('msie')==-1) ? window.Event.which : window.Event.keyCode;
if(whichCode == undefined) whichCode = window.Event.keyCode;	
if (((whichCode) > 47) && ((whichCode) < 58))
{
   NumDig = ConteudoCampo.value;
   TamDig = NumDig.length;
   Contador = 0;
   if (TamDig > 1)
      {numer = "";
      for (i = TamDig; (i >= 0); i--){
          if ((parseInt(NumDig.substr(i,1))>=0) && (parseInt(NumDig.substr(i, 1))<=9))
            {
             Contador++;
             if ((Contador == 2) && ((TamDig -i) < 4))
              {numer = ","+numer;
               Contador = 0;
               }
             else if (Contador == 3)
              {numer = "."+numer;
               Contador = 0;
              }
             numer = NumDig.substr(i, 1)+numer;
            }
           }
      ConteudoCampo.value = numer;
      };
   return(true)}
   else return(false)
}

function FtrataBackSpace(dado)
{
   NumDig = dado.value;
   TamDig = NumDig.length;
   TamDig--;
   Contador = 0;
var whichCode = (window.Event&&agente.indexOf('msie')==-1) ? window.Event.which : window.Event.keyCode;
if(whichCode == undefined) whichCode = window.Event.keyCode;	
   
   if ((TamDig >= 0) && (whichCode == 8))
    { numer = "";
      for (i = TamDig; (i >= 0); i--){
          if ((parseInt(NumDig.substr(i,1))>=0) && (parseInt(NumDig.substr(i, 1))<=9))
            {
             Contador++;
             if ((Contador == 4) && ((TamDig -i) < 5))
              {numer = ","+numer;
               Contador = 0;
               }
             else if ((Contador == 3) && ((numer.length) > 4))
              {numer = "."+numer;
               Contador = 0;
              }

             numer = NumDig.substr(i, 1)+numer;

            }
			}
			if (numer == "001")
			    numer="";
			if ((numer.length) == 3 )
			    numer= "0," + numer;

		dado.value = numer;
      };
}


function FNumber(campo){	
	var numero=campo.value;
	if(numero==null||numero==""||numero.length==0) return true;
	numero=numero.replace(',','.');
	var cont=0;
	numero=numero.toString();
	for(var i=0;i<numero.length;i++) {
		if(numero.charAt(i)=='.') { cont++; }
	}
	if(cont>=2) {
		cont=0;
	var temp=numero;
	for(var i=numero.length;i>=0;i--) {
		if(numero.charAt(i)=='.') {
			if(cont==0)  {
				cont++;
			}
			else  {
				temp=temp.substring(0,i)+temp.substring(i+1,temp.length);
			}
		}
	}
	numero=temp;

	}

	numero = parseFloat(numero);
	var nInt, nDec, i, sInt, sDec, vInt, vDec
	nInt = parseInt(numero, 10);
	nDec = parseInt((numero*1000 - nInt*1000), 10);
	sInt = nInt.toString();
	sDec = nDec.toString();
	vInt = '';
	// Inicio Calcula Arredondamento
	for (i = sDec.length; i < 3; i++)
	{
		sDec = '0' + sDec;
	}
	if (sDec.length == 3)
	{
		if (parseInt(sDec.substring(2, 3), 10) > 5)
		{
			nDec = parseInt(sDec.substring(0, 2), 10) + 1;
		}
		else if (parseInt(sDec.substring(2, 3), 10) == 5)
		{
			if (parseInt(sDec.substring(1, 2), 10)%2 != 0) //Ímpar
			{
				nDec = parseInt(sDec.substring(0, 2), 10) + 1;
			}
			else
			{
				nDec = parseInt(sDec.substring(0, 2), 10);
			}
		}
		else
		{
			nDec = parseInt(sDec.substring(0, 2), 10);
		}
		sDec = nDec.toString();
	}
	if (sDec == 100)
	{
		sDec = '00';
		sInt = (parseInt(sInt, 10) + 1).toString();
	}

	for (i = sDec.length; i < 2; i++)
	{
		sDec = '0' + sDec;
	}
	for (i = sInt.length-1; i >= 0; i--)
	{
		vInt = sInt.charAt(i) + vInt;
		if (((sInt.length)-i)%3 == 0 && i != sInt.lenght-1 && i != 0)
		{
			vInt = '.' + vInt;
		}
	}
	campo.value=(vInt + ',' + sDec);
}
function validaEmail(campo,name) {
	if (campo.value == "") {
	 return true;
	} else {
		prim = campo.value.indexOf("@")
		if(
		  (campo.value.indexOf("..") > 0)
		||(campo.value.indexOf(")") > 0)
		||(campo.value.indexOf("(") > 0)
		||(campo.value.indexOf("]") > 0)
		||(campo.value.indexOf("[") > 0)
		||(campo.value.indexOf("/") > 0)
		||(campo.value.indexOf(".com.br.") > 0)
		||(campo.value.indexOf("@.") > 0)
		||(campo.value.indexOf(".@") > 0)
		||(campo.value.indexOf("hotmeil.com") > 0)
		||(campo.value.indexOf("zipmeil.com") > 0)
		||(campo.value.indexOf(" ") != -1)
		||(campo.value.indexOf(".") < 1)
		||(campo.value.indexOf("@",prim + 1) != -1)
		||(prim<2)
			) {
			return false;
		}
		}
		return true;
}



function formataParaEnviar(campo){
	if(campo){
		while(campo.value.indexOf('.')!=-1){
			campo.value=campo.value.replace('.','');
		}
		while(campo.value.indexOf(',')!=-1){
			campo.value=campo.value.replace(',','.');
		}		
	}return false;
}

function checkValorMonetario(field,nullable){
	if((field == null||field.value.length==0)){
		return nullable;
	}
	if(isNaN(field.value.replace('.','').replace(',',''))){
		return false;
	}else{
		return true;
	}
}

function SoNumero(e)
{
	if (document.all) // Internet Explorer
		var tecla = event.keyCode;
	else if(document.layers) // Nestcape
		var tecla = e.which;
		if (tecla > 47 && tecla < 58) // numeros de 0 a 9
			return true;
		else
			{
				if (tecla != 8) // backspace
					event.keyCode = 0;
					//return false;
				else
					return true;
			}
}
