/*
 * Plugin Jquery para validação de formularios
 *
 * @author: Andrei Rafael Brayer
 *
 * @param: validar_email
 * @param: validar_value, o campo deve conter rel="value_original"
 * @param: validar_textarea
 */
$.fn.validadorFormularios = function(options){
    
    // configuração padrão
    var options = jQuery.extend( {
            retorno: true,
            classReferencia: 'validador',
            valorPadrao: 'validar_value',
            valorEmail: 'validar_email',
            idTextarea: '',
            msgAlertPadrao: 'Por favor preencha o campo ',
            msgAlertValue: 'Por favor preencha o campo ',
            msgAlertEmail: 'Por favor preencha corretamente o campo ',
            submitAjax: false ,
            ajaxUrl:'',
            ajaxLoadingId:'div-loading'
          },options);

    $(this).submit(function(){
        var ElementoForm = $(this);
        options.retorno = true;
               
        var QtdCampos = $(this).find('.'+options.classReferencia).length ;
        var NumCount = 1;

        $(this).find('.'+options.classReferencia).each(function(){

            if($(this).hasClass(options.valorPadrao)){
                if($(this).val() == $(this).attr('rel')){
                    alert(options.msgAlertValue+$(this).prev().html().replace(':', '.'));
                    options.retorno = false; return false;
                }
            }
            if($(this).hasClass(options.valorEmail)){
                if(checaEmail($(this).val())){
                    alert(options.msgAlertEmail+$(this).prev().html().replace(':', '.'));
                    options.retorno = false; return false;
                }
            }
            if($(this).val() == ''){
                alert(options.msgAlertPadrao+$(this).prev().html().replace(':', '.'));
                options.retorno = false; return false;
            }
            if(options.idTextarea != ''){
                if(NumCount == QtdCampos){
                    if($('#'+options.idTextarea).hasClass(options.valorPadrao)){
                        if($('#'+options.idTextarea).val() == $('#'+options.idTextarea).attr('rel')){
                            alert(options.msgAlertValue+$('#'+options.idTextarea).parent().prev().html().replace(':', '.'));
                            options.retorno = false; return false;
                        }
                    }
                    if($('#'+options.idTextarea).val() == ''){
                        alert(options.msgAlertPadrao+$('#'+options.idTextarea).parent().prev().html().replace(':', '.'));
                        options.retorno = false; return false;
                    }
                }
            }
           NumCount = (NumCount+1);
        })
        if(options.submitAjax){
            if(options.retorno){
                var left = cauculaWigth(400);
                $('#'+options.ajaxLoadingId).show();
                $.blockUI({ message: jQuery('#div-carregando'),css: { width:'400px', left: left+'px', top:'20%',border:'0;'} });

                var data = $(this).serialize();
                $.post(options.ajaxUrl, data, function(result){
                    $('#'+options.ajaxLoadingId).hide();
                    //ElementoForm.clearForm();
                    ElementoForm.find('textarea').each(function(){
                        $(this).val('');
                    })
                    $.unblockUI();
                    window.setTimeout('alertNewsletter('+result+')', 400);
                    
                });
                options.retorno = false;
            }
        }

        return options.retorno;
    });
    // Chama a função : $('#id_form').validadorFormularios('class_dos_campos');
}
/* Checa o e-mail */
function checaEmail(str) {
    var at="@"
    var dot="."
    var lat=str.indexOf(at)
    var lstr=str.length
    var ldot=str.indexOf(dot)

    if (str.indexOf(at)==-1){return true; }
    if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){ return true; }
    if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){ return true; }
    if (str.indexOf(at,(lat+1))!=-1){  return true; }
    if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){  return true; }
    if (str.indexOf(dot,(lat+2))==-1){ return true; }
    if (str.indexOf(" ")!=-1){ return true; }
    return false
}
function alertNewsletter(data)
{
    if(data == 1){
        jQuery('#carregando').hide();
        alert('Este e-mail já está cadastrado!');
    }else if(data == 2){
        alert('Obrigado por se interessar em nossas notícias!');
    }else if(data == 3){
        alert('Seu e-mail foi removido com sucesso!');
    }else if(data == 4){
        jQuery('#carregando').hide();
        alert('Este e-mail não está cadastrado em nossa base de dados!');
    }
    return false;
}
