/**
 *
 * Copyleft (c) 2008 Carlos Alan P. Alves (carlosalan86@gmail.com)
 * --------------------------------------------------------------------------------------
 * Plugin com a fun??o de fazer a valida??o de formul?rios. com intuito de ajudar novatos
 * que queiram apren-der. Pe?o apenas que n?o tire a minha autoria. Muito Obrigado.
 * --------------------------------------------------------------------------------------
 *
 * Vers?o: 1.0.7
 *
 * LOG:
	Vers?o: 1.0.7 - 13/02/09 - Valida??o dos inputs type radio;
							 - Remo??o da variavel vl_elementos;
	Vers?o: 1.0.6 - 19/12/08 - Melhoramento da valida??o de e-mail;
	Vers?o: 1.0.5 - 12/09/08 - Melhoramento da valida??o de e-mail;
	Vers?o: 1.0.4 - 05/09/08 - Padronizando as variaveis;
	Vers?o: 1.0.3 - 05/09/08 - Agora o plugin apenas faz a valida??o sem enviar para canto algum[ var: vl_formaenvio:validar ];
	Vers?o: 1.0.2 - 28/08/08 - Plugin agora funciona com mais de um form na p?gina;
	Vers?o: 1.0.1 - 27/08/08 - Organiza??o da estrutura dos settings;
 *
 *
 */

jQuery.fn.validacao = function(options)
{
    var form = this;
    var settings =
	{
		vl_bsubmit: 'button[id="goform"]', //Elemento que ativa a valida??o;
		vl_formaenvio: 'validar' //file, ajax, validar;
	};

	if(options) { jQuery.extend(settings, options); }

    jQuery(settings.vl_bsubmit).click(function()
	{
		if(form.is('form'))
		{
            var x = 0;
            var ca = "";

			/*
				@ Inicio
				@ Verifica??o todos os campos que tiverem o atributo title;
			*/
            jQuery.each(jQuery(form).find('[title]'), function()
			{
                var elemento = jQuery(this);
				var tipo = jQuery(elemento)[0].type;
				switch(tipo)
				{
					case 'radio':
						var r = 0;
						jQuery(jQuery('input[name="'+elemento.attr('name')+'"]'), form).each(function() {
							if(jQuery(this).attr('checked') == true)
								r++;
						});

						if (r <= 0)
							if(jQuery('#'+elemento.attr('name')).attr('id') == null)
								jQuery('<span id="'+elemento.attr('name')+'" class="msgErro">'+elemento.attr('title')+'</span>').insertBefore(jQuery('input[name="'+jQuery(this).attr('name')+'"]:last'));
					break;
					case 'password':
					case 'text':
					case 'textarea':
					case 'file':
					case 'select-one':
						if(elemento.val() == "" || elemento.val() == 0)
						{
							if(ca == "")
								ca = elemento;

							ca.focus();
							x = (x + 1);
							if(jQuery('#'+elemento.attr('name')).attr('id') == null)
								jQuery('<span id="'+elemento.attr('name')+'" class="msgErro">'+elemento.attr('title')+'</span>').insertAfter(elemento);
						}
					break;
				}

				jQuery("[name="+elemento.attr('name')+"]").click(function (e) { if(jQuery('#'+jQuery(this).attr('name'))) { jQuery('#'+jQuery(this).attr('name')).remove(); } });
                jQuery("[name="+elemento.attr('name')+"]").keypress(function (e) { if(jQuery('#'+jQuery(this).attr('name'))) jQuery('#'+jQuery(this).attr('name')).remove(); });
            });

			/*
				@ Inicio
				@ Verifica??o do campo e-mail;
			*/
        	if (settings.vl_campoemail)
			{
    			if(x == 0)
				{

					var elemento = jQuery(settings.vl_campoemail);
					if(elemento.val() != "" && elemento.val() != null)
					{
						var erEmail = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
						if (!erEmail.test(elemento.val()))
						{
							x = 1;
							elemento.focus();
							elemento.addClass("erro");
							if(jQuery('#'+elemento.attr('name')).attr('id') == null)
								jQuery('<span id="'+elemento.attr('name')+'" class="msgErro">Por favor confira seu e-mail.</span>').insertAfter(elemento);
						}
					}
    			}
        	}


			if (settings.cpf) {

				if(x == 0) {

					jQuery("#valid_cpf").css('display', 'none');

            		if (jQuery(settings.cpf).val()) {
					   var i;
					   var cpf = jQuery(settings.cpf).val();
					   cpf = cpf.replace( ".", "" );
					   cpf = cpf.replace( ".", "" );
					   cpf = cpf.replace( "-", "" );

					   if( (cpf == '11111111111') || (cpf == '22222222222') ||
							(cpf == '33333333333') || (cpf == '44444444444') ||
							(cpf == '55555555555') || (cpf == '66666666666') ||
							(cpf == '77777777777') || (cpf == '88888888888') ||
							(cpf == '99999999999') || (cpf == '00000000000') ) {
								jQuery(settings.cpf).focus();
								jQuery("#valid_cpf").css('display', 'block');
								x = 1;
						}

						var c = cpf.substr(0,9);
						var dv = cpf.substr(9,2);
						var d1 = 0;

						for (i = 0; i < 9; i++){
							d1 += c.charAt(i)*(10-i);
						}

						if (d1 == 0) {
							jQuery(settings.cpf).focus();
							jQuery("#valid_cpf").css('display', 'block');
							x = 1;
						}

						d1 = 11 - (d1 % 11);
						if (d1 > 9)
							d1 = 0;

						if (dv.charAt(0) != d1) {
							jQuery(settings.cpf).focus();
							jQuery("#valid_cpf").css('display', 'block');
							x = 1;
						}


						d1 *= 2;
						for (i = 0; i < 9; i++) {
							d1 += c.charAt(i)*(11-i);
						}

						d1 = 11 - (d1 % 11);
						if (d1 > 9)
							d1 = 0;

						if (dv.charAt(1) != d1) {
							jQuery(settings.cpf).focus();
							jQuery("#valid_cpf").css('display', 'block');
							x = 1;
						}
            		}
    			}

        	}


			/*
				@ Inicio
				@ Verifica??o do campo arquivo;
			*/
        	if (settings.vl_file)
			{

				if(x == 0)
				{
					var spli = settings.vl_file.split('#');
					var campoFile = jQuery(spli[0]);
					if(campoFile.attr('class') != null)
					{
						if(campoFile.val() != '')
						{

							if(spli[1] == 'imagens')	{ var ext = /(.jpg|.JPG)$/; textArq = '.jpg' }
							if(spli[1] == 'documentos')	{ var ext = /(.doc|.DOC|.pdf|.PDF)$/; textArq = '.doc ou .pdf' }

							if (!ext.test(campoFile.val()))
							{
								x = (x + 1);
								if(jQuery('#'+jQuery(settings.vl_file).attr('name')).attr('id') == null)
									jQuery('<span id="'+jQuery(settings.vl_file).attr('name')+'" class="msgErro">Aceito apenas arquivos '+textArq+'</span>').insertAfter(campoFile);
							}

							campoFile.click(function (e)
							{
								var campo = jQuery(this);
								if(jQuery('#'+jQuery(settings.vl_file).attr('name')).attr('id'))
									jQuery('span[id="'+jQuery(settings.vl_file).attr('name')+'"]').remove();
							});
						}
					}
				}
        	 }

			/* @ Se todos os campos estiverem ok, a variavel x deve estar como 0, ent?o os dados ser?o enviados;  */
			if(x == 0)
			{
				switch(settings.vl_formaenvio)
				{
					case 'ajax':
						var avisoOriginal = jQuery(".aviso").attr('title');

						jQuery(".aviso").css('display', 'block');
						jQuery(".aviso").addClass('valid');
					    jQuery(".aviso").html('Aguarde...');

					    jQuery.ajax({
					        type: "POST",
                                                url: settings.vl_pgexterna,
                                                data: jQuery(form).serialize(),
                                                success: function(msg)
							{

								//alert(msg);

								/*
									@ ?rea Livre para desenvolvimento dos retornos do [ vl_pgexterna ];
								*/
								switch(msg)
								{

								    case 'erro_cadastro':
										jQuery(".aviso").html('Dados n?o foram inseridos.');
									break;

									case 'cadastro_duplicado':
										jQuery(".aviso").html('E-mail ja cadastrado.');
									break;

									case 'cadastro_ok':
									default:

										jQuery(".aviso").html('Sua mensagem foi enviada.');

										jQuery(":input", form).each(function()
										{
											var elemento = jQuery(this);

											if(elemento.attr('class') != "botao") {
											    elemento.val('');
											}
										});

									break;
								}
		                    }
		                })
					break;

					case 'file':
					    window.document.trabalhe.action = settings.vl_pgexterna;
		                window.document.trabalhe.submit();
					break;

					default:
					    return true;
					break;
				}
			}
		}
	 return false;
    });
};

