﻿var defaultBG = "#FFFFFF";
var alertBG = "#FFDFE1";

// Valida Formulários
function validaForm(frm) {
	var vErr = 0;
	

	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 < 1) {
				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) {
		alertaErro();
		return false;
	} else {
		return true;
	}
}

function alertaErro() {
	var oAlertBox = document.getElementById("alertBox");
	oAlertBox.innerHTML = "Os campos marcados com * são obrigatórios!";
	display(oAlertBox);
}

function back2default(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 = "#FFEFF0";
}

function inputOff(e) {
	var field = getEventTag(e);
	field.style.backgroundColor = "#FFFFFF";
}

function isCEP(campo){
    if(isEmpty(campo)){return true;}
    switch(campo){
        case '00000' :
        case '00000-000' :
        	return false;
    }
    if((campo.length >= 6 && campo.length <= 8) || campo.length < 5) return false;
    
    return true;
}

function isSite(campo){
    if(isEmpty(campo)){return true;}
	var filter  = /^(http(s?):\/\/)?(www.)?(\w|-)+(\.(\w|-)+)*((\.[a-zA-Z]{2,3})|\.(aero|coop|info|museum|name))+(\/)?$/;
	if (filter.test(campo)) return true;
	else return false;
}

function isCPFCNPJ(campo,pType){
	var ret = true;
    if(isEmpty(campo)){return false;}
    switch(campo){
        case '000.000.000-00' :
        case '111.111.111-11' :
        case '222.222.222-22' :
        case '333.333.333-33' :
        case '444.444.444-44' :
        case '555.555.555-55' :
        case '666.666.666-66' :
        case '777.777.777-77' :
        case '888.888.888-88' :
        case '999.999.999-99' :
        case '00.000.000/0000-00' :
            ret = false;
            break;
    }
    if(!ret)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 isDate(data){
	var iDia = parseFloat(data.substring(0,2));
	var iMes = parseFloat(data.substring(3,5));
	var iAno = parseFloat(data.substring(6,10));
	var iDiasMes = 31;
	
	if (iMes == 4 || iMes == 6 || iMes == 9 || iMes == 11)
		iDiasMes = 30;
	else if (iMes == 2) {
		if (iAno % 4 != 0)
			iDiasMes = 28;
		else
			iDiasMes = 29;
	}
	
	if (iAno < 2000 || iAno > 2100 || iMes == 0 || iMes > 12 || iDia == 0 || iDia > iDiasMes)
		return 0;
	else
		return 1;
}

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 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) {
	if(getKey(e)<48||getKey(e)>57) return false;
}

function charsOnly(e) {
	var campo;
	campo = getEventTag(e);
	if(getKey(e)>48||getKey(e)<57) return false;
	campo.value = campo.value.replace(/[^a-zA-Z\s]/g,"");
}

function autoTel(e) {
	input = getEventTag(e);

//	str = '';
//	for(r in e){
//	    str += r + '\n';
//	}
//	alert(str);
    
	
	if(getKey(e)<48||getKey(e)>57) return false;
	criamascara(input,'####-####',0);
}

//--------------------------
function mask(e, f, ig){
    //debugo(e);
    
    //debugz(e.keyCode);
    v_fun = f;
    v_key = String.fromCharCode(getKey(e));
    v_chr = getKey(e);
    v_obj = e.target||e.srcElement||document.getElementById(e.id);
    v_nu1 = v_obj.value.length;
    
    switch(getKey(e)){
        case 8:     // BACKSPACE
        case 46:    // DEL
            setTimeout("execMask()",1);
            return true;
            break;
        case 13:    // ENTER
        case 9:     // TAB
        case 35:    // END
        case 36:    // HOME
        case 37:    // LEFT
        case 38:    // UP
        case 39:    // RIGHT
        case 40:    // DOWN
        case 46:    // DEL
        case 116:   // F5
        case 0:     // NOT IDENTIFIED
            return true;
            break;
    }
    if(v_key.length==1){
        switch(f.toString().substr(9,3)){
            case 'num': if(!isNumeric(e, ig))return false; break;
            case 'chr': if(!isChar(e))return false; break;
        }
        setTimeout("execMask()",1);
    }return true;
}

Array.prototype.find = function(searchStr){
	var returnArray = false;
	for(i=0;i<this.length;i++){
		if(typeof(searchStr)=='function'){
			if(searchStr.test(this[i])){
				if(!returnArray)returnArray=[];
				returnArray.push(i);
			}
		}else{
			if(this[i]===searchStr){
				if(!returnArray)returnArray=[];
				returnArray.push(i);
			}
		}
	}
	return returnArray;
}

function isNumeric(e, ig){
    if(ig){
        ig = ig.split(',');
        for(i=0;i<ig.length;i++)ig[i] = Number(ig[i]);
    }
    if(!((getKey(e) > 47 && getKey(e) < 58) || (getKey(e) > 95 && getKey(e) < 106 )) && !(ig ? (ig.find(getKey(e)).toString() != 'false') : true))return false;return true;
}

function execMask(){
    v_dif = v_obj.value.length - v_fun(v_obj.value).length;
    v_pos = getCaretPosition(v_obj);
    v_obj.value = v_fun(v_obj.value);
    v_nu2 = v_obj.value.length;
    if(v_chr < 36 || v_chr > 40)
        //setCaretTo(v_pos + ' : ' + (v_pos - ((v_nu2 - v_nu1) > 0 ? v_dif : 0)));
        setCaretTo(v_obj, v_pos - (v_dif));
}


function numNumeroInteiro(v){
    v = v.replace(/\D/g,'');
    return v;
}

function numTelefone(v){
    v = v.replace(/\D/g,'');                //Remove tudo o que não é dígito
    v = v.replace(/(\d)(\d{4})$/,'$1-$2');   //Coloca hífen antes dos 4 ultimos digitos
    return v;
}

function numHora(v){
    v = v.replace(/\D/g,'');                //Remove tudo o que não é dígito
    v = v.replace(/(\d)(\d{2})$/,'$1:$2');   //Coloca : antes dos 2 ultimos digitos
    return v;
}

function numNumeroReal(v){
    //v = v.replace(/^(?(\d)\D|[^,])$/g,'');
    v = v.replace(/^[,]$/g,'');
    v = v.replace(/(\d*(,{1})\d*),/g,'$1');
    gvValidator(v_obj);
    v_obj.onblur = function(){gvValidator(v_obj)};
    	
    return v;
}

function numData(v){
    v = v.replace(/\D/g,'');
    v = v.replace(/^(\d{2})(\d)/g,'$1/$2');
    v = v.replace(/^(.{5})(\d)/g,'$1/$2');
    v = v.replace(/^([4-9])/g,'');
    v = v.replace(/^3([2-9])/g,'3');
    v = v.replace(/^(\d{2}\/)([2-9])/g,'$1');
    v = v.replace(/^(\d{2}\/1)([3-9])/g,'$1');
    v = v.replace(/^(\d{2}\/\d{2}\/)([0])/g,'$1');
    v = v.replace(/^(\d{2}\/\d{2}\/[1])([0-8])/g,'$1');
    v = v.replace(/^(\d{2}\/\d{2}\/\d{4}\s)([3-9])/g,'$1');
    v = v.replace(/^(\d{2}\/\d{2}\/\d{4}\s2)([4-9])/g,'$1');
    v = v.replace(/^(\d{2}\/\d{2}\/\d{4}\s\d{2}:)([6-9])/g,'$1');
    return v;
}

function numDataHora(v){
    v = v.replace(/\D/g,'');
    v = v.replace(/^(\d{2})(\d)/g,'$1/$2');
    v = v.replace(/^(.{5})(\d)/g,'$1/$2');
    v = v.replace(/^(.{10})(\d)/g,'$1 $2');
    v = v.replace(/^(.{13})(\d)/g,'$1:$2');
    v = v.replace(/^([4-9])/g,'');
    v = v.replace(/^3([2-9])/g,'3');
    v = v.replace(/^(\d{2}\/)([2-9])/g,'$1');
    v = v.replace(/^(\d{2}\/1)([3-9])/g,'$1');
    v = v.replace(/^(\d{2}\/\d{2}\/)([0])/g,'$1');
    v = v.replace(/^(\d{2}\/\d{2}\/[1])([0-8])/g,'$1');
    v = v.replace(/^(\d{2}\/\d{2}\/\d{4}\s)([3-9])/g,'$1');
    v = v.replace(/^(\d{2}\/\d{2}\/\d{4}\s2)([4-9])/g,'$1');
    v = v.replace(/^(\d{2}\/\d{2}\/\d{4}\s\d{2}:)([6-9])/g,'$1');

    return v;
}

function numCPF(v){
    v = v.replace(/\D/g,'');
    v = v.replace(/^(.{3})(\d)/g,'$1.$2');
    v = v.replace(/^(.{7})(\d)/g,'$1.$2');
    v = v.replace(/^(.{11})(\d)/g,'$1-$2');
    gvValidator(v_obj);
    v_obj.onblur = function(){gvValidator(v_obj)};
    return v;
}

function numCNPJ(v){
    v = v.replace(/\D/g,'');
    v = v.replace(/^(.{2})(\d)/g,'$1.$2');
    v = v.replace(/^(.{6})(\d)/g,'$1.$2');
    v = v.replace(/^(.{10})(\d)/g,'$1/$2');
    v = v.replace(/^(.{15})(\d)/g,'$1-$2');
    gvValidator(v_obj);
    v_obj.onblur = function(){gvValidator(v_obj)};
    return v;
}

function numCEP(v){
    v = v.replace(/\D/g,'');
    v = v.replace(/^(.{5})(\d)/g,'$1-$2');
    setTimeout('gvValidator(v_obj)',100);
    v_obj.onblur = function(){gvValidator(v_obj)};
    return v;
}

function setCaretTo(obj, pos){
    if(obj.createTextRange){
        var range = obj.createTextRange();
        range.move("character", pos);
        range.select();
    }else if(obj.selectionStart){
        obj.focus();obj.setSelectionRange(pos, pos);
    }
}

function getCaretPosition(obj){
    var cursorPos = -1;
    if(document.selection && document.selection.createRange){
        var range = document.selection.createRange().duplicate();
        if(range.parentElement() == obj){
            range.moveStart('textedit', -1);
            cursorPos = range.text.length;
        }
    }else if(obj.selectionEnd){
        cursorPos = obj.selectionEnd;
    }
    return cursorPos;
}

function gvValidator(obj) {
    Page_InvalidControlToBeFocused = null;
    var vals;
    if (typeof(obj.Validators) != "undefined") {
        vals = obj.Validators;
    }
    else {
        if (obj.tagName.toLowerCase() == "label") {
            obj = document.getElementById(obj.htmlFor);
            vals = obj.Validators;
        }
    }
    var i;
    for (i = 0; i < vals.length; i++) {
        gvValidatorValidate(vals[i], null, obj);
    }
    ValidatorUpdateIsValid();
}

function gvValidatorValidate(val, validationGroup, obj) {
    val.isvalid = true;
    if ((typeof(val.enabled) == "undefined" || val.enabled != false) && IsValidationGroupMatch(val, validationGroup)) {
        if (typeof(val.evaluationfunction) == "function") {
            val.isvalid = val.evaluationfunction(val);
            if (!val.isvalid && Page_InvalidControlToBeFocused == null &&
                typeof(val.focusOnError) == "string" && val.focusOnError == "t") {
                gvValidatorSetFocus(val, obj);
            }
        }
    }
    ValidatorUpdateDisplay(val);
}

function gvValidatorSetFocus(val, obj){
    var ctrl;
    if (typeof(val.controlhookup) == "string") {
        if ((typeof(obj) != "undefined") && (obj != null) &&
            (typeof(obj.id) == "string") &&
            (obj.id == val.controlhookup)) {
            ctrl = obj;
        }
    }
    if ((typeof(ctrl) == "undefined") || (ctrl == null)) {
        ctrl = document.getElementById(val.controltovalidate);
    }
    if ((typeof(ctrl) != "undefined") && (ctrl != null) &&
        (ctrl.tagName.toLowerCase() != "table") && 
        ((ctrl.tagName.toLowerCase() != "input") || (ctrl.type.toLowerCase() != "hidden")) &&
        (typeof(ctrl.disabled) == "undefined" || ctrl.disabled == null || ctrl.disabled == false) &&
        (typeof(ctrl.visible) == "undefined" || ctrl.visible == null || ctrl.visible != false) &&
        (IsInVisibleContainer(ctrl))) {
        if (ctrl.tagName.toLowerCase() == "table" &&
            (typeof(__nonMSDOMBrowser) == "undefined" || __nonMSDOMBrowser)) {
            var inputElements = ctrl.getElementsByTagName("input");
            var lastInputElement  = inputElements[inputElements.length -1];
            if (lastInputElement != null) {
                ctrl = lastInputElement;
            }
        }
        if (typeof(ctrl.focus) != "undefined" && ctrl.focus != null) {
            ctrl.focus();
            Page_InvalidControlToBeFocused = ctrl;
        }
    }
}

function getEventTag(e) {
	if(e.srcElement) elm = e.srcElement; else if(e.target) elm = e.target;
	return elm;
}

//--------------------------

function autoDDDTel(e) {
	input = getEventTag(e);

	if(getKey(e)<48||getKey(e)>57) return false;
    criamascara(input,'(##) ####-####',0);
}

function autoDt(e) {
	input = getEventTag(e);
	if(getKey(e)<48||getKey(e)>57) return false;
	criamascara(input,'##/##/####',0);
}

function autoCNPJ(e) {
	input = getEventTag(e);
	if(getKey(e)<48||getKey(e)>57) return false;
	criamascara(input,'##.###.###/####-##',0);
}

function autoCPF(e) {
	input = getEventTag(e);
	if(getKey(e)<48||getKey(e)>57) return false;
	criamascara(input,'###.###.###-##',0);
}

function autoCEP(e) {
	input = getEventTag(e);
	if(getKey(e)<48||getKey(e)>57) return false;
	criamascara(input,'#####-###',0);
}

function autoTime(e) {
	input = getEventTag(e);
	if(getKey(e)<48||getKey(e)>57) return false;
	criamascara(input,'##:##',0);
}

function numbersOnlyPerc(e) {
	var campo;
	campo = getEventTag(e);
	campo.value = campo.value.replace(/[^0-9\,]/g,"");
}

function cancelEvent(e) {
	e.key = getKey(e);
	de(e.key);
	e.cancel = true;
    e.cancelBubble = true;
    if(e.stopPropagation) e.stopPropagation();
}

function getKey(e){
	return (e.keyCode + 1 || e.which + 1) - 1 || 0;
}

function autoCurrency(e) {
	var milSep = '.';
	var decSep = ',';
	var maxLength = 13;
	var fld = getEventTag(e);
	var sep = i = j = len = len2 = 0;
	var key = aux = aux2 = '';
	var strCheck = '0123456789';
	var whichCode = (window.Event) ? e.which : e.keyCode;

	if(fld.value.length < maxLength){
	    if (whichCode == 13) return true;  // Enter
	    if (whichCode == 8) return true;  // Delete
	    key = String.fromCharCode(whichCode);  // Get key value from key code
	    if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
	    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;
}


