/*
 * Functions
 * Copyright 2005 Inter.net - http://www.br.inter.net
 * Desenvolvimento
 * @author: Carlos Abreu
 */
 
 
function checkForm(f,obl){
	this.form = f;
	this.oblig = obl
	this.setValidForm = null;
	this.init();
}

// Método inicial
checkForm.prototype.init = function(){
	this.ckAll();
}

// Método Principal, engine do componente
checkForm.prototype.ckAll = function(){
	var f =  this.form;
	
	for(i=0; i<f.length; i++){
		// Se não estiver setado os campos obrigatórios o parâmetro geral é setado (true,false)
		f[i].getAttribute("required") == null  ?  f[i].setAttribute("required",this.oblig) : f[i].getAttribute("required")  ;

		// Adaptação para funcionar em todos os navegadores
		var obl = null;
		f[i].getAttribute("required")=='true' || f[i].getAttribute("required")== true ? obl = true : obl = false ;

		// Verificação de campos obrigatórios
		this.ckObl(f[i],obl);
		// Validação do Form, é necessário esse controle em cada etapa da validação
		if(!this.getValidForm()) break;

		// Validações de Xtype´s
		if(f[i].value != ""){
			if(f[i].getAttribute("xtype") == "email"){
				this.ckEmail(f[i]);
			}
			if(f[i].getAttribute("xtype") == "number"){
				this.ckNumber(f[i]);
			}
			if(f[i].getAttribute("xtype") == "text"){
				this.ckText(f[i]);
			}			
			if(f[i].getAttribute("xtype") == "data"){
				this.ckData(f[i]);
			}
			if(f[i].getAttribute("xtype") == "cpf"){
				this.ckCPF(f[i]);
			}
			if(f[i].getAttribute("xtype") == "cnpj"){
				this.ckCNPJ(f[i]);
			}

		}
		
		// Validação do Form, é necessário esse controle em cada etapa da validação
		if(!this.getValidForm()) break;

	}
}


// Método que verifica campos obrigatórios
checkForm.prototype.ckObl = function(obj,obl){
	objValue = obj.value;
	warning = obj.getAttribute("warning") == null ? '' : obj.getAttribute("warning");
	if(objValue=="" && obl == true){
		if(warning==''){
			alert("Por favor preencha os campos obrigatórios corretamente");
		}else{
			alert(warning);
		}
		obj.focus();
		this.setValidForm = false;
	}else{
		this.setValidForm = true;
	}
}

// Método que verifica email
checkForm.prototype.ckEmail = function(obj){
	objValue = obj.value;
	if(objValue.match(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]{2,64}(\.[a-z0-9-]{2,64})*\.[a-z]{2,4}$/)){
		this.setValidForm = true;
	}else{
		alert("Por Favor digite um e-mail válido.");
		obj.focus();
		this.setValidForm = false;
	}
}

// Método que verifica a data informada ele usa o objeto dateFormat para validação
checkForm.prototype.ckData = function(obj){
	objValue = obj.value;
	data = new dateFormat(objValue);
	if(!data.getStatus()){
		alert("O campo data possui informações inválidas ou está no formato errado, ela deve estar no formato DD/MM/AAAA");
		obj.focus();
		this.setValidForm = false;
	}else{
		this.setValidForm = true;
	}
}


// Método que verifica campos que aceitem caracteres numéricos
checkForm.prototype.ckNumber = function(obj){
	objValue = obj.value;
	if(objValue.match(/^[0-9]+$/)){
		this.setValidForm = true;
	}else{
		alert("Por Favor preencha os campos que contenham números corretamente.");
		obj.focus();
		this.setValidForm = false;
	}
}

// Método que verifica campos que aceitem apenas Texto
checkForm.prototype.ckText = function(obj){
	objValue = obj.value;
	if(objValue.match(/^(a-z|A-Z|)*[^#$%^&*()'0-9]*$/)){
		this.setValidForm = true;
	}else{
		alert("Por Favor preencha os campos que contenham apenas texto corretamente.");
		obj.focus();
		this.setValidForm = false;
	}
}

// Método que verifica o cpf informado
checkForm.prototype.ckCPF = function (obj) {
	var CPF = obj.value;
	var flag = true;
    if (CPF.length != 11 || CPF == "00000000000" || CPF == "11111111111" ||
        CPF == "22222222222" || CPF == "33333333333" || CPF == "44444444444" ||
        CPF == "55555555555" || CPF == "66666666666" || CPF == "77777777777" ||
        CPF == "88888888888" || CPF == "99999999999")
		flag = false;
		this.setValidForm = false;
    soma = 0;
    for (i=0; i < 9; i ++)
        soma += parseInt(CPF.charAt(i)) * (10 - i);
    resto = 11 - (soma % 11);
    if (resto == 10 || resto == 11)
        resto = 0;
    if (resto != parseInt(CPF.charAt(9)))
		flag = false;
		this.setValidForm = false;
    soma = 0;
    for (i = 0; i < 10; i ++)
        soma += parseInt(CPF.charAt(i)) * (11 - i);
    resto = 11 - (soma % 11);
    if (resto == 10 || resto == 11)
        resto = 0;
    if (resto != parseInt(CPF.charAt(10))){
		flag = false;
		this.setValidForm = false;
	}
	if(!flag){
		alert("Digite um CPF válido.");
		obj.focus();
        this.setValidForm = false;
		return false;
	}else{
		this.setValidForm = true;
	}
}

// Método que verifica CNPJ válido
checkForm.prototype.ckCNPJ = function(obj){
	var parameter = obj.value;
	strNum='';
	l = parameter.length;
	for (i = 0; i < l; i++) {
		caracter = parameter.substring(i,i+1)
		if ((caracter >= '0') && (caracter <= '9')) strNum = strNum + caracter;
	}
	strMul = '6543298765432'
	iValido = 1
	if(strNum.length != 14){
	  this.setValidForm = false;
	}
	iSoma = 0
	strNum_base = strNum.substring(0,12)
	iLenNum_base = strNum_base.length - 1
	iLenMul = strMul.length - 1
	for(i=0;i<12;i++){
		iSoma = iSoma + parseInt(strNum_base.substring((iLenNum_base-i),(iLenNum_base-i)+1),10) * parseInt(strMul.substring((iLenMul-i),(iLenMul-i)+1),10)
	}
	iSoma = 11 - (iSoma - Math.floor(iSoma/11) * 11)
	if(iSoma == 11 || iSoma == 10){
		iSoma = 0
	}
	strNum_base = strNum_base + iSoma
	iSoma = 0
	iLenNum_base = strNum_base.length - 1
	for(i=0;i<13;i++){
		iSoma = iSoma + parseInt(strNum_base.substring((iLenNum_base-i),(iLenNum_base-i)+1),10) * parseInt(strMul.substring((iLenMul-i),(iLenMul-i)+1),10)
	}
	iSoma = 11 - (iSoma - Math.floor(iSoma/11) * 11)
	if(iSoma == 11 || iSoma == 10){
		iSoma = 0
	}
	strNum_base = strNum_base + iSoma
	if(strNum != strNum_base){
		alert("CNPJ inválido, favor preencher novamente.");
		obj.focus();
		this.setValidForm = false;
		return false;
	}else{
		this.setValidForm = true;
		return true;
	}
	return false;
}


// Método que retorna se o formulário é válido
checkForm.prototype.getValidForm = function(){
	return this.setValidForm;
}

// Função de verificar data no formato DD/MM/AAAA
function dateFormat(obj){
	this.$obj = obj
	this.$dia = null;
	this.$mes = null;
	this.$ano = null;
}

dateFormat.prototype.getStatus = function(){
	if(this.dia(this.$obj)){
		if(this.mes(this.$obj)){
			if(this.ano(this.$obj)){
				var flag = null;
				// Checa data válida
				this.ckData(this.$ano,this.$mes,this.$dia) ? flag =  true : flag = false;
				if(flag) return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}else{
		return false;
	}
}

dateFormat.prototype.ckData = function(intYear,intMonth,intDay){
	 intMonth--;
	 Data = new Date();
	 Data.setYear(intYear);
	 Data.setMonth(intMonth);
	 Data.setDate(intDay);
	 if ((Data.getDate() == intDay) && (Data.getMonth() == intMonth) && (Data.getFullYear() == intYear)) return true;
	 return false;
}
	
dateFormat.prototype.dia = function(obj){
	var pos = obj.indexOf("/");
	// Seta dia
	this.$dia = obj.substring(0,pos);
	if(pos == 2){
		return true;
	}else if(pos == -1){
		return false;
	}
}

dateFormat.prototype.mes = function(obj){
	var pos_start = obj.indexOf("/")+1;
	var pos_end = obj.lastIndexOf("/");
	var cont = obj.substring(pos_start,pos_end);
	// Seta mês
	this.$mes = cont;
	if(cont.length == 2){
		return true;
	}else{
		return false;
	}
}

dateFormat.prototype.ano = function(obj){
	var pos_start = obj.lastIndexOf("/")+1;
	var pos_end = obj.length;
	var cont = obj.substring(pos_start,pos_end);
	// Seta Ano
	this.$ano = cont;
	if(cont.length == 4){
		return true;
	}else{
		return false;
	}
}


// Função que carrega componente de validação de formulários
function ckForm(f,obl){
	f = new checkForm(f,obl);
	f.getValidForm() ? flag = true : flag = false;
	if(!flag) return false;
}