var defaultBG = "#f5cf5f";
var alertBG = "#f1ccbc";

// Valida Formulários
function validaForm(frm) {
	var vErr = 0;
	var oAlertBox = document.getElementById("alertBox");

	for(var i=0;i<frm.elements.length;i++) {
		var elm = frm.elements[i];
		var vPula = 0;

		if(elm.parentNode && elm.parentNode.style && elm.parentNode.style.display == 'none') vPula = 1;

		if(elm.name.substr(0,2) != "r_" || vPula == 1) continue;
		addEvent(elm,"keyup",back2defalut,1);

		if(elm.type == "text" || elm.type == "textarea" || elm.type == "password" || elm.type == "hidden") {
			if(elm.value.length < 2) {
				elm.style.background = alertBG;
				vErr = 1;
			} else if(elm.name.indexOf("email") != -1 && !checkMail(elm.value)) {
				elm.style.background = alertBG;
				vErr = 1;
			} else if(elm.name.indexOf("cnpj") != -1 && !isCPFCNPJ(elm.value,2)) {
				elm.style.background = alertBG;
				vErr = 1;
			} else if(elm.name.indexOf("cpf") != -1  && !isCPFCNPJ(elm.value,1)) {
				elm.style.background = alertBG;
				vErr = 1;
			}
		}

		if(elm.type == "select-one") {
			if(!elm.options[elm.selectedIndex].value) {
				elm.style.background = alertBG;
				vErr = 1;
			}
		}
	}

	if(vErr) {
		oAlertBox.innerHTML = "Os campos marcados com * são obrigatórios!";
		display(oAlertBox);
		return false;
	} else {
		return true;
	}
}

function back2defalut(e) {
	var elm;
	if(e.srcElement) elm = e.srcElement; else if(e.target) elm = e.target;
	if(elm.value.length > 1) elm.style.background = defaultBG;
}

function remover(e) {
	var field = getEventTag(e);

	var msg = "Confirma a remoção deste(a) "+field.form.name+"?";
	if(confirm(msg)) {
		field.form.acao.value = "R";
		field.form.submit();
	}
}

function adicionaRemocao() {
	var btns = document.getElementsByTagName("input");

	for(i in btns) {
		if(btns[i].value == "Remover")
			addEvent(btns[i],"click",remover,1);
	}
}

function coloreInputs() {
	var inputs = document.getElementsByTagName("input");

	for(i in inputs) {
		if(inputs[i].type == "text" || inputs[i].type == "textarea" || inputs[i].type == "password") {
			addEvent(inputs[i],"focus",inputOn,1);
			addEvent(inputs[i],"blur",inputOff,1);
		}
	}
}

function inputOn(e) {
	var field = getEventTag(e);
	field.style.backgroundColor = "#dcaf25";
}

function inputOff(e) {
	var field = getEventTag(e);
	field.style.backgroundColor = "#f5cf5f";
}

function isCPFCNPJ(campo,pType){
   if( isEmpty( campo ) ){return false;}

   var campo_filtrado = "", valor_1 = " ", valor_2 = " ", ch = "";
   var valido = false;

   for (i = 0; i < campo.length; i++){
      ch = campo.substring(i, i + 1);
      if (ch >= "0" && ch <= "9"){
         campo_filtrado = campo_filtrado.toString() + ch.toString()
         valor_1 = valor_2;
         valor_2 = ch;
      }
      if ((valor_1 != " ") && (!valido)) valido = !(valor_1 == valor_2);
   }
   if (!valido) campo_filtrado = "12345678912";

   if (campo_filtrado.length < 11){
      for (i = 1; i <= (11 - campo_filtrado.length); i++){campo_filtrado = "0" + campo_filtrado;}
   }

   if(pType <= 1){
      if ( ( campo_filtrado.substring(9,11) == checkCPF( campo_filtrado.substring(0,9) ) ) && ( campo_filtrado.substring(11,12)=="") ){return true;}
   }

   if((pType == 2) || (pType == 0)){
      if (campo_filtrado.length >= 14){
         if ( campo_filtrado.substring(12,14) == checkCNPJ( campo_filtrado.substring(0,12) ) ){ return true;}
      }
   }

   return false;
}

function checkCNPJ(vCNPJ){
   var mControle = "";
   var aTabCNPJ = new Array(5,4,3,2,9,8,7,6,5,4,3,2);
   for (i = 1 ; i <= 2 ; i++){
      mSoma = 0;
      for (j = 0 ; j < vCNPJ.length ; j++)
         mSoma = mSoma + (vCNPJ.substring(j,j+1) * aTabCNPJ[j]);
      if (i == 2 ) mSoma = mSoma + ( 2 * mDigito );
      mDigito = ( mSoma * 10 ) % 11;
      if (mDigito == 10 ) mDigito = 0;
      mControle1 = mControle ;
      mControle = mDigito;
      aTabCNPJ = new Array(6,5,4,3,2,9,8,7,6,5,4,3);
   }
   return( (mControle1 * 10) + mControle );
}

function checkCPF(vCPF){
   var mControle = ""
   var mContIni = 2, mContFim = 10, mDigito = 0;
   for (j = 1 ; j <= 2 ; j++){
      mSoma = 0;
      for (i = mContIni ; i <= mContFim ; i++)
         mSoma = mSoma + (vCPF.substring((i-j-1),(i-j)) * (mContFim + 1 + j - i));
      if (j == 2 ) mSoma = mSoma + ( 2 * mDigito );
      mDigito = ( mSoma * 10 ) % 11;
      if (mDigito == 10) mDigito = 0;
      mControle1 = mControle;
      mControle = mDigito;
      mContIni = 3;
      mContFim = 11;
   }
   return( (mControle1 * 10) + mControle );
}

function autoCNPJ(e) {
	input = getEventTag(e);
	criamascara(input,'##.###.###/####-##',0);
}

function autoCPF(e) {
	input = getEventTag(e);
	criamascara(input,'###.###.###/##',0);
}

function checkMail(mail) {
	var x = mail;
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(x)) return true;
	else return false;
}

function isEmpty(campo) {
	if(campo.value == "" || campo.value == "undefined")
		return true;
	else
		return false;
}

function autoTel(e) {
	input = getEventTag(e);
	criamascara(input,'(##) ####-####',0);
}

function autoDt(e) {
	input = getEventTag(e);
	criamascara(input,'##/##/####',0);
}


function criamascara(_RefObjeto, _Modelo, num){
	var valorAtual = _RefObjeto.value;
	var valorNumerico = '';
	var nIndexModelo = 0;
	var nIndexString = 0;
	var valorFinal = '';
	var adicionarValor = true;

	if (num!=undefined && num!=0){num=1;}else{num=0;}
	for (i=0;i<_Modelo.length;i++){
		if (_Modelo.substr(i,1) != '#'){
		valorAtual = valorAtual.replace(_Modelo.substr(i,1),'');
		}
	}

	for (i=0;i<valorAtual.length;i++){
		if(num==0){
			if (!isNaN(parseFloat(valorAtual.substr(i,1)))){
				valorNumerico = valorNumerico + valorAtual.substr(i,1);
			}
		} else {
			valorNumerico = valorNumerico + valorAtual.substr(i,1);
		}
	}

	for (i=0;i<_Modelo.length;i++){
		if (_Modelo.substr(i,1) == '#'){
			if (valorNumerico.substr(nIndexModelo,1) != ''){
				valorFinal = valorFinal + valorNumerico.substr(nIndexModelo,1);
				nIndexModelo++;nIndexString++;
			} else {
				adicionarValor = false;
			}
		} else {
			if (adicionarValor && valorNumerico.substr(nIndexModelo,1) != ''){
				valorFinal = valorFinal + _Modelo.substr(nIndexString,1)
				nIndexString++;
			}
		}
	}

	_RefObjeto.value = valorFinal
}

function numbersOnly(e) {
	var campo;
	campo = getEventTag(e);
	campo.value = campo.value.replace(/[^0-9]/g,"");
}

function numbersOnlyPerc(e) {
	var campo;
	campo = getEventTag(e);
	campo.value = campo.value.replace(/[^0-9\,]/g,"");
}


function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13) return true;
	if ((whichCode==null) || (whichCode==0) || (whichCode==8) ||
		(whichCode==9) || (whichCode==13) || (whichCode==27) )
		return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}
