$(function(){
	
	function resetForm(id) {
	$('#'+id).each(function(){
	        this.reset();
	});
	}
	
	//Valida forms
	$("form").bind("submit", function(){							  
		if(!empty($(this).attr('initialfunc')))
			eval($(this).attr('initialfunc'));
		//alert("form");
		$('.msgerr').css("display","none");
		errorlist="";
		var checkerros = new Array();
		var contcheck=0;
		var err = false;
		var inv = false; //Variavel que define se o formulário submetido está valido ou nao
		var id_form = $(this).attr("id");

		$("#"+id_form+" .vfield").each(function(){
			err = validaCampoVazio($(this).attr("id"),id_form);
			if(err)
			inv = true;
		});
		
		
		function matrizCheck(msg,valido)
		{
			this.msg=msg;
			this.valido=valido;
		}

		$("#"+id_form+" .vcheckrad").each(function(){
			
			if(empty(checkerros[contcheck]))
				{
				checkerros[contcheck]= new matrizCheck($(this).attr('msg'),false);
				err=false;
				}
			else if(checkerros[contcheck].msg!=$(this).attr('msg'))
				contcheck++;
			
			if($(this).attr("checked") == true)
			{
			checkerros[contcheck].valido=true;	
			err = true;
			//inv = false;
			}
			else if(err==false)
			{
				checkerros[contcheck].valido=false;
				//inv = true;
			}
		});
		
		$("#"+id_form+" .vemail").each(function(){
			err = validaEmail($(this).attr("id"),id_form);
			if(err)
			inv = true;
		}) ;
		
		$("#"+id_form+" .passwd").each(function(){
			err = validaSenhas("senha", "passwd",id_form);
			if(err)
			inv = true;
		}) ;
		
		for (var i in checkerros){
			if(!checkerros[i].valido)
			{
			inv = true;
				if($(".errorlist")[0])
				{
				errorlist+='<div class="msgerr" >'+$("#"+checkerros[i].msg).html()+'<\/div>';
				}
				else
				{
				$("#"+checkerros[i].msg).css("display","inline");
				}
			}
		}
	
		if(inv){
			formInvalido = true;
			if(!empty(errorlist))
				{
				Message("Erros no preenchimento",errorlist);
				if(!empty($(this).attr('errorfunc')))
				eval($(this).attr('errorfunc'));
				}
			return false;
		} else formInvalido = false;
		
		/* ckeditor erro ao editar CORRIGIDO */
		$("#"+id_form+" .ckclass").each(function(){
			//alert("Serialize: "+$(this).attr("name"));
			fields = $(this).attr("name");
			var oEditor = eval("CKEDITOR.instances."+fields);
			//alert("texto no editor:"+oEditor.getData());
			$(this).val(oEditor.getData());
		});
		
		//alert("Serialize2: "+$(this).serialize());
		
		if(empty($(this).attr("noAjax")))
		{
			$.ajax({
			type: "POST",
			url: $(this).attr("action"),
			data: $(this).serialize(),
			dataType: 'json',
			success: function(e){
				if(e.retorno)
				{
					if(e.comand)
						for (var c in e.comand)
							eval(e.comand[c]);
					if(e.funcao)
						eval(e.funcao)(e.parametros[0],e.parametros[1],e.parametros[2],e.parametros[3]);
				}
				else
					eval(e.funcao)(e.parametros[0]);
				
				resetForm(id_form);
			}
			});
			return false;
		}	
		});	
});
