// .warning_class						{ background: url('/js/4/autoform/booble.gif') top left no-repeat; color: #ffffff; z-index: 500; font-weight:bold; line-height:20px;height:25px; min-width:200px; padding-left:4px; text-align:left }

var CAutoform = Class.create();
CAutoform.prototype = {
	options: null,
	parent: null,
	warningOffsetX: 0,
	warningOffsetY: 0,
	warningClass: '',
	warningTitle: 'Atenção',
	initialize: function(myParent,options,warningClass,warningHeight,warningTitle) {
		this.parent = myParent;
		this.parent.position = "relative";
		if (options) this.options = options;
		if (warningClass) this.warningClass = warningClass;
		if (warningHeight && warningHeight>0) this.warningOffsetY = warningHeight;
		if (warningTitle) this.warningTitle = warningTitle;
		Event.observe(window,'load',this.start.bind(this));
	},
	getElement: function(e,getParent) {
		e = eval('this.parent.' + e);
		if (!getParent && e.length && e.type != 'select-one') return e[0];
		return e;
	},
	isCheckboxArray: function(e) {
		e = eval('this.parent.' + e);
		return (e.length && e.type != 'select-one');
	},
	start: function() {
		this.parent = document.getElementsByName(this.parent)[0];
		this.parent.onsubmit = this.onsubmit.bind(this);
		total = this.options.mandatory?this.options.mandatory.length:0;
		totalT = this.options.translation?this.options.translation.length:0;
		totalD = this.options.defaults?this.options.defaults.length:0;
		for(c=0;c<total;c++) {
			trad = (total == totalT)?this.options.translation[c]:this.options.mandatory[c];
			this.createWarningDiv(this.getElement(this.options.mandatory[c]),'af_'+this.options.mandatory[c],trad);
			if (total == totalD) this.getElement(this.options.mandatory[c]).value = this.options.defaults[c];
		}
	},
	onsubmit: function() {
		return this.valideForm();
	},
	createWarningDiv: function(e,name,warning) {
		wd = document.createElement('div');
		wd.setAttribute('id',name);
		wd.innerHTML = warning;
		wd.style.position = 'absolute';
		wd.style.display = 'none';
		if (this.warningClass != '') wd.className = this.warningClass;
		wd.style.left = (findPosX(e) - this.warningOffsetX) + "px";
		wd.style.top = (findPosY(e) - this.warningOffsetY) + "px";
		wd.onclick = Function("this.style.display = 'none'");
		Element.setOpacity(wd, 0.8);
		Event.observe(e,'focus',Function("$('"+name+"').style.display = 'none'"));
		Event.observe(e,'click',Function("$('"+name+"').style.display = 'none'"));
//		document.body.appendChild(wd);
		this.parent.appendChild(wd);
	},
	valideForm: function() {
		// reposition warning tags, as form might have changed. Also disable them as default
		total = this.options.mandatory?this.options.mandatory.length:0;
		totald = this.options.defaults?this.options.defaults.length:0;
		useDefaults = total == totald;
		for(c=0;c<total;c++) {
			e = this.getElement(this.options.mandatory[c]);
			wd = $('af_' + this.options.mandatory[c]);
			wd.style.left = (findPosX(e) - this.warningOffsetX) + "px";
			wd.style.top = (findPosY(e) - this.warningOffsetY) + "px";
			wd.style.display = 'none'
		}			
		// first, check formats. If fails, empty the field
		total = this.options.is_id?this.options.is_id.length:0;
		for(c=0;c<total;c++) {
			valor = this.getElement(this.options.is_id[c]).value;
			if (!validaCGC(valor) && !validaCPF(valor)) this.getElement(this.options.is_id[c]).value = "";
		}
		total = this.options.is_cpf?this.options.is_cpf.length:0;
		for(c=0;c<total;c++) {
			valor = this.getElement(this.options.is_cpf[c]).value;
			if (!validaCPF(valor)) this.getElement(this.options.is_cpf[c]).value = "";
		}
		total = this.options.is_cnpj?this.options.is_cnpj.length:0;
		for(c=0;c<total;c++) {
			valor = this.getElement(this.options.is_cnpj[c]).value;
			if (!validaCGC(valor)) this.getElement(this.options.is_cnpj[c]).value = "";
		}
		total = this.options.integer?this.options.integer.length:0;
		for(c=0;c<total;c++) {
			valor = this.getElement(this.options.integer[c]).value;
			if (!isnumber(valor,false)) this.getElement(this.options.integer[c]).value = "";
		}
		total = this.options.float?this.options.float.length:0;
		for(c=0;c<total;c++) {
			valor = this.getElement(this.options.float[c]).value;
			if (!isnumber(valor,true)) this.getElement(this.options.float[c]).value = "";
		}
		total = this.options.mail?this.options.mail.length:0;
		for(c=0;c<total;c++) {
			valor = this.getElement(this.options.mail[c]).value;
			if (!ismail(valor)) this.getElement(this.options.mail[c]).value = "";
		}
		// now we check mandatory fields
		total = this.options.mandatory?this.options.mandatory.length:0;
		totalT = this.options.translation?this.options.translation.length:0;
		msg = "";
		for(c=0;c<total;c++) {
			isArray = this.isCheckboxArray(this.options.mandatory[c]);
			if (!isArray) {
				valor = this.getElement(this.options.mandatory[c]).value;
				if (valor == '' || (useDefaults && valor == this.options.defaults[c])) {
					if (total == totalT) msg += this.options.translation[c] + "\n";
					else msg += this.options.mandatory[c] + "\n";
					try{
						if (useDefaults) this.getElement(this.options.mandatory[c]).value = this.options.defaults[c];
					} catch(ee) {
					}
					$('af_'+this.options.mandatory[c]).style.display = '';
				}
			} else {
				e = this.getElement(this.options.mandatory[c],true);
				itotal = e.length;
				hasSelected = false;
				for(i=0;i<itotal;i++) {
					if (e[i].checked) {
						hasSelected = true;
						break;
					}
				}
				if (!hasSelected) {
					if (total == totalT) msg += this.options.translation[c] + "\n";
					else msg += this.options.mandatory[c] + "\n";
					$('af_'+this.options.mandatory[c]).style.display = '';
				}
			}
		}
		if (this.warningTitle != '' && msg != '') {
			alert(this.warningTitle + "_____________\n" + msg + " ");
		}
		return msg == '';
	}
}

/*

	options aceita: 
	
	mandatory: array com campos obrigatórios
	is_id: array com campos que devem ser CPF ou CNPJ
	is_cpf: array com campos que devem ser CPF
	is_cnpj: array com campos que devem ser CNPJ
	integer: array com campos que devem ser números inteiros (sem virgula/ponto)
	float: array com campos que devem ser números decimais (com vírgula/ponto)
	mail: array com campos que devem ser E-mail
	translation: array com o texto que aparece em cima dos campos obrigatórios se não preenchidos. Deve ter o mesmo número de itens que mandatory para funcionar
	defaults: array com o texto padrão (value="") do campo. Deve ter o mesmo número de itens que mandatory para funcionar

	>> O form não precisa ter onsubmit, a classe autoform vai adicionar <<

	Você pode simular a validação chamando [nome_do_objeto].valideForm();

	EXEMPLO: 

	// [seu_form] = new CAutoform( [nome do form] , {[ opções] } , [classe dos divs] , [altura dos divs] , [titulo do alert] );

Autoform = new CAutoform('frminfo', // <-- nome do form (name)
					  { 
					 mandatory: ['nome','tipo_empresa','cpf_cnpj','nome_responsavel','endereco','cep','telefone','email','uf','certificacao_pretendida_paises','oque_vc_pretende_certificar','form_local'],
					 is_id: ['cpf_cnpj'],
					 integer: ['cep','pv_propriedades','pt_total','pa_apiarios','pa_colmeias','pn_animais','pr_total'],
					 float: ['pv_area','pc_area','pg_distancia'],
					 mail: ['email'],
					 translation: ['Digite seu nome','Selecione o tipo de empresa','Preencha seu CPF/CNPJ','Digite o nome do responsável','Digite o endereço','Digite o CEP','Digite o Telefone','Preencha um E-mail válido','Selecione o estado','Selecione os paises pretendidos','Selecione as certificações predentidas','Informe o local de preenchimento deste formulário']
					   }, // <-- campos obrigatórios ou com formatação especial. 
					   'warning_class', // CLASS do div que avisa campos obrigatórios faltando
					   20, // altura acima do input que o aviso aparece (px)
					   'Atenção' // Título do alert no caso de erro de validação (se for '', não mostra alert)
					   );

*/
