// José Guidini / ABC Interactive

/******************************************
/* Validação dos campos
/*****************************************/

// Testa um grupo de CheckBox ou RadioButton
testaCheckbox = function(objChk){
	for (j=0; objChk[j]; j++)
		if (objChk[j].checked)
			return true;
	return false;
};

// Testa um e-mail
testaEmail = function(strEmail){
	var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // e-mail inválido
	var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // e-mail válido
	return (!reg1.test(strEmail) && reg2.test(strEmail));
};

// Testa um CPF
testaCPF = function(strCPF){
    var c = strCPF;
    if((c = c.replace(/[^\d]/g,"").split("")).length != 11) return false;
    if(new RegExp("^" + c[0] + "{11}$").test(c.join(""))) return false;
    for(var s = 10, n = 0, i = 0; s >= 2; n += c[i++] * s--);
    if(c[9] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
    for(var s = 11, n = 0, i = 0; s >= 2; n += c[i++] * s--);
    if(c[10] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
    return true;
};

// Testa um CNPJ
testaCNPJ = function(strCNPJ){
    var b = [6,5,4,3,2,9,8,7,6,5,4,3,2], c = strCNPJ;
    if((c = c.replace(/[^\d]/g,"").split("")).length != 14) return false;
    for(var i = 0, n = 0; i < 12; n += c[i] * b[++i]);
    if(c[12] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
    for(var i = 0, n = 0; i <= 12; n += c[i] * b[i++]);
    if(c[13] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
    return true;
};

// Testa uma Data
verifica_data = function(strData){
    var reg1 = /[0-9]{2}\/[0-9]{2}\/[0-9]{4}/;
    if (!reg1.test(strData))
      return false;
    var data = strData.split("/");
    y = data[2], m = data[1], d = data[0];
    if(typeof y == "string" && m instanceof RegExp && d){
      if(!m.test(y)) return 1;
        y = RegExp["$" + d.y], m = RegExp["$" + d.m], d = RegExp["$" + d.d];
      }
      d = Math.abs(d) || 0, m = Math.abs(m) || 0, y = Math.abs(y) || 0;
    return arguments.length != 3 ? 1 : d < 1 || d > 31 ? 2 : m < 1 || m > 12 ? 3 : /4|6|9|11/.test(m) && d == 31 ? 4
    : m == 2 && (d > ((y = !(y % 4) && (y % 1e2) || !(y % 4e2)) ? 29 : 28)) ? 5 + !!y : 0;
};

//verifica se uma data e uma data valida ex: verifica_data('01/01/2008'); return boolen
function testaData(data){ 

	if (verifica_data(data)){
		var dia = data.substr(0,2); 
		var mes = data.substr(3,2); 
		var ano = data.substr(6,4); 
	
		
		situacao = ""; 
		// verifica o dia valido para cada mes 
		if ((dia < '01') || (dia < '01' || dia > '30') && (mes == '04' || mes == '06' || mes == '09' || mes == '11') || dia > '31') { 
			situacao = "falsa"; 
			return false;
		} 
		// verifica se o mes e valido 
		if (mes < 01 || mes > 12 ) { 
			situacao = "falsa"; 
			return false;
		} 
	
		// verifica se e ano bissexto 
		if (mes == 2 && ( dia < 01 || dia > 29 || ( dia > 28 && (parseInt(ano / 4) != ano / 4)))) { 
			situacao = "falsa"; 
			return false;
		} 
		
		if (situacao == "falsa") { 
			return false;
		}
		return true;
	}else{
		return false;
	}
}

// Testa um cep
testaCEP = function(strCep){
    var reg1 = /[0-9]{5}\-[0-9]{3}/;
    return (reg1.test(strCep))
};

// Testa um Telefone
testaFone = function(strFone){
    var reg1 = /\([0-9]{2}\)\ [0-9]{4}\-[0-9]{4}/;
    return (reg1.test(strFone))
};

// Testa uma hora
testaHora = function(horario) {
	if (horario.indexOf(".") == -1)
		if (horario.indexOf(":") != -1){
			div    = horario.indexOf(":");
			tam    = horario.length;
			hora   = horario.substring(0,div);
			minuto = horario.substring(div+1,tam);
			msg    = "";
			if ((!isNaN(hora))&&(!isNaN(minuto))){
				if ((minuto>=60)||(minuto<0))
					return false;
				if ((hora>24)||(hora<0))
					return false;
				return true;
			}
		}
	return false;
};

// Testa um link
testaLink = function(strLink) {
   var reg1 = /http?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?/;
   return reg1.test(strLink);
};

// Testa se um valor é seguro 
testaSeguro = function(strSeguro){
	var reg1 = /\W/;
	return (strSeguro.search(reg1)==-1);
};

/******************************************
/* Mascara para os campos
/*****************************************/

// Adiciona um evento a uma função/campo
addEvent = function(o, e, f, s){
    var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
    r[r.length] = [f, s || o], o[e] = function(e){
        try{
            (e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
            e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
            e.target || (e.target = e.srcElement || null);
            e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
        }catch(f){}
        for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
        return e = null, !!d;
    }
};

// Remove um evento de uma função/campo
removeEvent = function(o, e, f, s){
    for(var i = (e = o["_on" + e] || []).length; i;)
        if(e[--i] && e[i][0] == f && (s || o) == e[i][1])
            return delete e[i];
    return false;
};

// Formata um VALOR
FormataValor = function(o, n, dig, dec) {
  o.c = !isNaN(n) ? Math.abs(n) : 2;
  o.dec = dec || ",", o.dig = dig || ".";
  addEvent(o, "keypress", function(e){
      if(e.key > 47 && e.key < 58){
          var o, s = ((o = this).value.replace(/^0+/g, "") + String.fromCharCode(e.key)).replace(/\D/g, ""), l, n;
          (l = s.length) <= (n = o.c) && (s = new Array(n - l + 2).join("0") + s);
          for(var i = (l = (s = s.split("")).length) - n; (i -= 3) > 0; s[i - 1] += o.dig);
          n && n < l && (s[l - ++n] += o.dec);
          o.value = s.join("");
      }
      e.key > 30 && e.preventDefault();
  });
};

/******************************************
/* Funções para Listagem de Valores
/*****************************************/
function ordenar(c){
	p = location.href;
	t = p.substr(0,p.lastIndexOf('?'));
	location.href=t+'?o='+c;
}

function paginar(c){
	p = location.href;
	t = p.substr(0,p.lastIndexOf('?'));
	location.href=t+'?p='+c;
}

// Auto tabulação
autoTab = function(){
    var c = 0, lastKey = function(e){c = e.key;}, next = function(e){
        var i, j, f = (e = e.target).form.elements, l = e.value.length, m = e.maxLength;
        if(c && m > -1 && l >= m){
            for(i = l = f.length; f[--i] != e;);
            for(j = i; (j = (j + 1) % l) != i && (!f[j].type || f[j].disabled || f[j].readOnly || f[j].type.toLowerCase() == "hidden" || f[j].style.display == "none"););
            try {j != i && f[j].focus();}catch(e){ /*nada*/ }
        }
    };
    for(var f, i = (f = document.forms).length; i; addEvent(f[--i], "keyup", next), addEvent(f[i], "keypress", lastKey));
};

function html_entity_decode(str) {
  
  var ta=document.createElement("textarea");
  ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
  return ta.value;
  
}

function trim(str){return str.replace(/^\s+|\s+$/g,"");}
