/**************************************************
mickaForms v0.4 - mickele87@gmail.com
Requeriments:	framework mootools (http://www.mootools.net)
**************************************************/

var mickaForms = new Class({
	 
	/* Array of validations */
	validations   : ["required","number","email","regex","date","mask","cpf","cnpj","equal"],
	
	// 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",
	
	// Messages Language
	language : "pt",
	
	
	messages : {
		
		// Portuguese Brazilian
		pt : {
			standard	: "Campo Inv&aacute;lido",
			required	: "Campo Obrigat&oacute;rio",
			number		: "Somente Nmeros",
			email		: "E-mail Inv&aacute;lido",
			regex		: "Campo Inv&aacute;lido",
			equal		: "Campos Diferentes",
			different	: "Campos Iguais",
			cpf			: "CPF Inv&aacute;lido",
			cnpj		: "CNPJ Inv&aacute;lido",
			date		: "Data Inv&aacute;lida",
			mask		: "Campo Inv&aacute;lido"
		}
	},
	
	required : null,
	required_controller : function(args) {
		var arr = (args.split(/::/g));
		arr[0] = arr[0].trim();
		if ((arr[0].test(/^\#/) && arr[0] == "#" + this.el.id) || (arr[0] == this.el.name)) if (this.el.value.trim() == "") return (arr[1]) ? arr[1] : 'required_message';
		return false;
	},
	
	number : null,
	number_controller : function(args) {
		var arr = (args.split(/::/g));
		arr[0] = arr[0].trim();
		if ((arr[0].test(/^\#/) && arr[0] == "#" + this.el.id) || (arr[0] == this.el.name)) {
			var v = this.el.value.trim();
			if (!v.test(/^[0-9\,\.]+$/) && v != "") return (arr[1]) ? arr[1] : 'number_message';
		}
	},
	
	email : null,
	email_controller : function(args) {
		var arr = (args.split(/::/g));
		arr[0] = arr[0].trim();
		if ((arr[0].test(/^\#/) && arr[0] == "#" + this.el.id) || (arr[0] == this.el.name)) {
			var v = this.el.value.trim();
			if (!v.test(/^[A-Za-z0-9_\.\-]{2,}\@([A-Za-z0-9_\.\-]+\.)+[A-Za-z]{2,4}?$/) && v != "") return (arr[1]) ? arr[1] : 'email_message';
		}
	},
	
	regex : null,
	regex_controller : function(args) {
		var arr = (args.split(/\//g));
		arr[0] = arr[0].trim();
		if (((arr[0].test(/^\#/) && arr[0] == "#" + this.el.id) || (arr[0] == this.el.name)) && arr[1].trim() != "") {
			var v = this.el.value.trim();
			if (!v.test(eval("/^" + arr[1]+ "$/")) && v != "") return (arr[2]) ? arr[2] : 'regex_message';
		}
	},
	
	equal : null,
	equal_controller : function(args) {
		var arr = (args.split(/[\|:]/g));
		if ((arr[0].test(/^\#/) && arr[0] == "#" + this.el.id) || arr[0] == this.el.name) {
			var v = this.el.value.trim();
			var v2 = $(arr[1]).value.trim();
			if (v != v2) return (arr[3]) ? arr[3] : 'equal_message';
		}
	},
	
	different : null,
	different_controller : function(args) {
		var arr = (args.split(/[\|:]/g));
		if ((arr[0].test(/^\#/) && arr[0] == "#" + this.el.id) || arr[0] == this.el.name) {
			var v = this.el.value.trim();
			var v2 = $(arr[1]).value.trim();
			if (v != v2) return (arr[3]) ? arr[3] : 'different_message';
		}
	},
	
	cpf : null,
	cpf_controller : function(args) {
		var arr = (args.split(/::/g));
		arr[0] = arr[0].trim();
		if ((arr[0].test(/^\#/) && arr[0] == "#" + this.el.id) || (arr[0] == this.el.name)) {
			var v = this.el.value.trim().replace(/[\.\-]/g,"");
			var e = false;
			if (v.length < 11) e = true;
			if (/\D/.test(v)) e = true;
			if (v=="00000000000"||v=="11111111111"||v=="22222222222"||v=="33333333333"||v=="44444444444"||v=="55555555555"||v=="66666666666"||v=="77777777777"||v=="88888888888"||v=="99999999999") e = true;
			var a = [], b = new Number, c = 11;
			for (i=0; i<11; i++) {
				a[i] = v.charAt(i);
				if (i < 9) b += (a[i] * --c);
			}
			a[9] = ((x = b % 11) < 2) ? 0 : 11-x;
			b = 0;
			c = 11;
			for (y=0; y<10; y++) b += (a[y] * c--);
			a[10] = ((x = b % 11) < 2) ? 0 : 11-x;
			if ((v.charAt(9) != a[9]) || (v.charAt(10) != a[10])) e = true;
			if (e && v != "") return (arr[1]) ? arr[1] : 'cpf_message';
		}
	},
	
	cnpj : null,
	cnpj_controller : function(args) {
		var arr = (args.split(/::/g));
		arr[0] = arr[0].trim();
		if ((arr[0].test(/^\#/) && arr[0] == "#" + this.el.id) || (arr[0] == this.el.name)) {
			var v = this.el.value.trim().replace(/[\.\-\/]/g,"");
			var e = false;
			if (v.length < 14) e = true;
			if (/\D/.test(v)) e = true;
			var a = [], b = new Number, c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
			for (i=0; i<12; i++){
				a[i] = v.charAt(i);
				b += a[i] * c[i+1];
			}
			a[12] = ((x = b % 11) < 2) ? 0 : 11-x;
			b = 0;
			for (y=0; y<13; y++) b += (a[y] * c[y]);
			a[13] = ((x = b % 11) < 2) ? 0 : 11-x;
			if ((v.charAt(12) != a[12]) || (v.charAt(13) != a[13])) e = true;
			if (e && v != "") return (arr[1]) ? arr[1] : 'cnpj_message';
		}
	},
	
	
	// Em desenvolvimento
	date : null,
	date_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.test(/\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] : 'date_message';
			}
		}
	},
	
	
	// 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.test(eval("/^" + arr[1]+ "$/")) && v != "") {
				return (arr[2]) ? arr[2] : 'standard_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 + ".validate()");
		});
		
	},
	
	validate : 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.validations.length; i2++) {
					if (eval("this." + this.validations[i2])) {
						var c = eval("this." + this.validations[i2]);
						for (var i3 = 0; i3 < c.length; i3++) {
							var erro = eval("this." + this.validations[i2] + "_controller('" + c[i3] + "')");
							if (erro) {
								if (erro.test(/\_message$/)) {
									this.msgE = eval('this.messages.'+this.language+'.'+erro.replace(/\_message$/,''))
								} else {
									this.msgE = erro;
								}
								this.showErrors();
								this.el.focus();
								new Fx.Scroll(window, {
									wait: false,
									duration: 0
								}).toElement($(this.de));
								return false;
							}
						}
					}
				}
			}
		}
		if (this.otherValidations) for(var i = 0; i < this.otherValidations.length; i++) if (!eval(this.otherValidations[i])) 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,
			'styles' : {
				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,
			'styles' : {
				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,
			'styles' : {
				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');
	}
	
});