/**************************************************
mickaForms v0.2 - mickele87@gmail.com
Requerimentos:	framework mootools (http://www.mootools.net)
**************************************************/

var mickaForms = new Class({
	
	/* Array das validações */
	validacoes   : ["obrigatorio","email","regex","data","mask"],
	
	// Styles divErro
	dePosition   : "absolute",
	deOpacity    : 0,
	deColor      : "#C00",
	deBackground : "#FDD",
	dePadding    : 5,
	deZindex     : 666,
	deFontFamily : "Trebuchet MS, Verdana, Arial",
	deFontSize   : 12,
	deBorder     : "1px solid #FCC",
	
	// Styles shadow
	shPosition   : "absolute",
	shOpacityIni : 0,
	shOpacityFim : 0.2,
	shBackground : "#000",
	shZindex     : 665,
	shMargin     : "2px 0 0 2px",
	shBorder     : "0",
	
	// Mensagens Padrões
	padrao_mensagem      : "Campo Inválido",
	obrigatorio_mensagem : "Campo Obrigatório",
	email_mensagem       : "E-mail Inválido",
	data_mensagem        : "Data Inválida (dd/mm/aaaa)",
	
	// Validações
	obrigatorio : null,
	obrigatorio_controller : function(args) {
		var arr = (args.split(/::/g));
		if (arr[0].trim() == this.el.name) {
			if (this.el.value.trim() == "") {this.el.focus();
				return (arr[1]) ? arr[1] : this.obrigatorio_mensagem;
			}
		}
	},
	
	email : null,
	email_controller : function(args) {
		var arr = (args.split(/::/g));
		if (arr[0].trim() == this.el.name) {
			var v = this.el.value.trim();
			if (!v.match(/\b[A-Za-z0-9_\.\-]{3,}\@([A-Za-z0-9_\.\-]+\.)+[A-Za-z]{2,4}?\b/) && v != "") {
				return (arr[1]) ? arr[1] : this.email_mensagem;
			}
		}
	},
	
	regex : null,
	regex_controller : function(args) {
		var arr = (args.split(/\//g));
		if (arr[0].trim() == this.el.name && arr[1].trim() != "") {
			var v = this.el.value.trim();
			if (!v.match(eval("/^" + arr[1]+ "$/")) && v != "") {
				return (arr[2]) ? arr[2] : this.padrao_mensagem;
			}
		}
	},
	
	data : null,
	data_controller : function(args) {
		var arr = (args.split(/::/g));
		
		var campos = (arr[0].split(/\//g));
		
		if (campos[1]) {
			
		} else if (campos[0].trim() == this.el.name && campos[0].trim() != "") {
			var v = this.el.value.trim();
			if (!v.match(/\b(0?[1-9]|[1-2][0-9]|3[0-1])\/(0?[1-9]|1[0-2])\/[0-9]{4}\b/) && v != "") {
				return (arr[1]) ? arr[1] : this.data_mensagem;
			}
		}
	},
	
	
	// Em desenvolvimento
	mask : null,
	mask_controller : function(args) {
		var arr = (args.split(/\//g));
		if (arr[0].trim() == this.el.name && arr[1].trim() != "") {
			var v = this.el.value.trim();
			arr[1] = arr[1].replace(/a/g,"[a-z]");
			arr[1] = arr[1].replace(/A/g,"[A-Z]");
			arr[1] = arr[1].replace(/9/g,"[0-9]");
			arr[1] = arr[1].replace(/\*/g,".");
			if (!v.match(eval("/^" + arr[1]+ "$/")) && v != "") {
				return (arr[2]) ? arr[2] : this.padrao_mensagem;
			}
		}
	},
	
	
	form     : null,
	
	el       : null,
	elTag    : null,
	elType   : null,
	elTop    : null,
	elLeft   : null,
	elWidth  : null,
	elHeight : null,
	
	msgE     : null,
	
	de       : "mickaFormsDivErro",
	deTop    : null,
	deLeft   : null,
	deWidth  : null,
	deHeight : null,
	
	iF       : "mickaFormsIframeErro",
	sh       : "mickaFormsShadowErro",
	
	initialize : function(args) {
		
		$extend(this, args);
		
		$(this.form).addEvent("submit", function(e) {
			new Event(e).stop();
		});
		$(this.form).addEvent("submit", function() {
			eval(this.id + ".validar()");
		});
		
	},
	
	validar : function() {
		
		this.removeAll();
		
		for (var i1 = 0; i1 < $(this.form).elements.length; i1++) {
			this.el = $(this.form).elements[i1];
			this.elTag    = this.el.tagName.toLowerCase();
			if ((this.displayNone()) && (this.el.disabled == "") && (this.elTag == "input" || this.elTag == "select" || this.elTag == "password" || this.elTag == "textarea")) {
				this.setInfoEl();
				for (var i2 = 0; i2 < this.validacoes.length; i2++) {
					if (eval("this." + this.validacoes[i2])) {
						var c = eval("this." + this.validacoes[i2]);
						for (var i3 = 0; i3 < c.length; i3++) {
							var erro = eval("this." + this.validacoes[i2] + "_controller('" + c[i3] + "')");
							if (erro) {
								this.msgE = erro;
								this.showErrors();
								this.el.focus();
								new Fx.Scroll(window, {
									wait: false,
									duration: 0
								}).toElement($(this.de));
								return false;
							}
						}
					}
				}
			}
		}
		$(this.form).submit();
	},
	
	removeAll : function() {
		if ($(this.de)) $(this.de).remove();
		if ($(this.iF)) $(this.iF).remove();
		if ($(this.sh)) $(this.sh).remove();
	},
	
	displayNone : function() {
		var el = this.el;
		while (el = el.parentNode) {
			if (el.style && el.style.display == "none") return false;
			if (el.style && el.style.visibility == "hidden") return false;
		}
		return true;
	},
	
	setInfoEl : function() {
		this.elType   = $(this.el).type;
		this.elTop    = $(this.el).getTop();
		this.elLeft   = $(this.el).getLeft();
		this.elWidth  = $(this.el).offsetWidth;
		this.elHeight = $(this.el).offsetHeight;
	},
	
	setInfoDe : function() {
		this.deTop    = $(this.de).getTop();
		this.deLeft   = $(this.de).getLeft();
		this.deWidth  = $(this.de).offsetWidth;
		this.deHeight = $(this.de).offsetHeight;
	},
	
	showErrors : function() {
		
		this.showDE();
		
		if (window.ie6) this.showIframe();
		
		$(this.el).addEvent('keyup', this.esconderErros);
		$(this.el).addEvent('change', this.esconderErros);
		
	},
	
	showDE : function() {
		
		var de = new Element('div', {
			'id': this.de
		}).setStyles({
			position   : this.dePosition,
			opacity    : this.deOpacity,
			color      : this.deColor,
			background : this.deBackground,
			padding    : this.dePadding,
			zIndex     : this.deZindex,
			fontFamily : this.deFontFamily,
			fontSize   : this.deFontSize,
			border     : this.deBorder
		}).setHTML(this.msgE);
		
		de.injectTop(document.body);
		
		this.setInfoDe();
		
		$(this.de).setStyles({
			top: this.elTop - this.deHeight,
			left: this.elLeft + this.elWidth/2 - this.deWidth/2
		}).effect('opacity', {
			'duration': 100,
			'wait': false
		}).start(0, 1);
		
		this.setInfoDe();
		
		this.showSh();
	},
	
	showSh : function() {
		var sh = new Element('div', {
			'id': this.sh
		}).setStyles({
			position   : this.shPosition,
			opacity    : this.shOpacityIni,
			background : this.shBackground,
			zIndex     : this.shZindex,
			margin     : this.shMargin,
			border     : this.shBorder,
			
			top    : this.deTop,
			left   : this.deLeft,
			width  : this.deWidth,
			height : this.deHeight
			
		}).injectTop(document.body);
		
		sh.effect('opacity', {
			'duration': 100,
			'wait': false
		}).start(this.shOpacityIni, this.shOpacityFim);
	},
	
	showIframe : function() {
		new Element('iframe', {
			'id': this.iF
		}).setStyles({
			filter : "alpha(opacity = 0)",
			position: "absolute",
			top    : this.deTop,
			left   : this.deLeft,
			width  : this.deWidth,
			height : this.deHeight,
			zIndex : 664
		}).injectTop(document.body);
	},
	
	esconderErros : function(event) {
		var k = new Event(event);
		if (k.key != 'enter') {
			eval(this.form.id + ".hideErrors()")
		}
	},
	
	hideErrors : function() {
		var iF = this.iF;
		$(this.de).effect('opacity', {
			'duration': 500,
			'wait': false
		}).start(1, 0).chain(function(){
			if ($(iF)) $(iF).remove();
		});
		$(this.sh).effect('opacity', {
			'duration': 200,
			'wait': false
		}).start(this.shOpacityFim, this.shOpacityIni);
		$(this.el).removeEvents('keyup');
		$(this.el).removeEvents('change');
	}
	
});