/**************************************************************
*
* CLASSE JAVASCRIPT FORMULARIOS
*
* CRIADO POR: CRISTIANO TAVELLA
* DATA: 20/03/2011
* OBS:
* EDITADO POR: CRISTIANO TAVELLA
* DATA: 13/03/2011
* OBS:
*
*************************************************************/

function getEmail() {
    var v_return = false;

    $(this.destino + ' *[name="formulario_email"]').each(function () {
        if ($.trim($(this).val()) == "" && typeof ($(this).attr('obrigatorio')) != 'undefined' && $(this).attr('obrigatorio').toLowerCase() == "true") {
            alert("Preencha o campo '" + $(this).attr('label') + "' para continuar.");
            $(this).focus();
            v_return = true;
            return false;
        }
    });

    if (v_return)
        return;

    this.layout_msg = setDadosMSg(this);

    $(this.IdBtnEnviar).hide();
    $(this.IdBtnLimpar).hide();
    $(this.IdAguarde).show();

    var v_this = this;

    //desabilita campos enquanto processa
    $(this.destino + ' *[name="formulario_email"]').each(function () {
        $(this).attr("disabled",true);
    });

    //evento antes do envio
    eval(this.evtAntesEnvio);

    //processa
    ajax({ action: "enviarFormulario", fkempresa: v_this.fkempresa, assunto: v_this.assunto, layout: v_this.layout_msg, email: v_this.email }, function (retorno) {
        if (retorno == "1")
            eval(v_this.evtPosEnvio);
        else
            alert("Houve um erro ao enviar o formulário tente novamente");


        //habilita campos 
        $(v_this.destino + ' *[name="formulario_email"]').each(function () {
            $(this).removeAttr("disabled");
        });
        $(v_this.IdAguarde).hide();
        $(v_this.IdBtnEnviar).show();
        $(v_this.IdBtnLimpar).show();
    });

}

function setDadosMSg(v_this) {
    var layout_msg = v_this.layout_msg;

    layout_msg = layout_msg.replace(/</g, "!abretag!");
    layout_msg = layout_msg.replace(/>/g, "!fechatag!");
    layout_msg = layout_msg.replace(/\[assunto\]/g, v_this.assunto);

    layout_msg = layout_msg.replace(/\[url_favoritos\]/g, v_raiz + "ListaFavoritos/" + (typeof (v_lista_imoveis_favoritos) == "undefined" ? "" : v_lista_imoveis_favoritos));
   
    if (v_this.imovel == "")
        layout_msg = layout_msg.replace(/\[url\]/g, location.href);
    else
        layout_msg = layout_msg.replace(/\[url\]/g, v_this.imovel);

    var data = new Date;
    var data2 = data.getDate() + "/" + (data.getMonth() + 1) + "/" + data.getFullYear() + " " + data.getHours() + ":" + data.getMinutes() + ":" + data.getSeconds();

    layout_msg = layout_msg.replace(/\[data\]/g, data2);

    var dados = "";

    $(v_this.destino + ' *[name="formulario_email"]').each(function () {
        if (typeof ($(this).attr("titulo")) != "undefined") {
            dados += '<tr><td style="font-weight:bold;	background-color:#E6E6E6; text-align:center;" colspan="2">';
            dados += $(this).attr("titulo") + '</td></tr>';
        }
        else if ($(this).attr("type") == "radio") {
            if ($(this).attr("checked")) {
                eval('layout_msg = layout_msg.replace(/\\\[' + $(this).attr("alt") + '\\\]/g, "' + $(this).val() + '");');

                dados += '<tr><td style="width: 75px;text-align:right;font-weight:bold;	background-color:#E6E6E6;	width: 150px;">';
                dados += $(this).attr('label') + '</td>';
                dados += '<td style="border-top: 1px solid #E6E6E6;	border-bottom: 1px solid #E6E6E6;border-right: 1px solid #E6E6E6;"> ';
                dados += $(this).val().replace(/(\r)?\n/g, "<br/>") + '</td></tr>';
            }
        }
        else if ($(this).attr("type") == "checkbox") {
            if ($(this).attr("checked")) {
                eval('layout_msg = layout_msg.replace(/\\\[' + $(this).attr("id") + '\\\]/g, "Sim");');

                dados += '<tr><td style="width: 75px;text-align:right;font-weight:bold;	background-color:#E6E6E6;	width: 150px;">';
                dados += $(this).attr('label') + '</td>';
                dados += '<td style="border-top: 1px solid #E6E6E6;	border-bottom: 1px solid #E6E6E6;border-right: 1px solid #E6E6E6;"> ';
                dados += 'Sim</td></tr>';
            }
            else {
                eval('layout_msg = layout_msg.replace(/\\\[' + $(this).attr("id") + '\\\]/g, "Não");');

                dados += '<tr><td style="width: 75px;text-align:right;font-weight:bold;	background-color:#E6E6E6;	width: 150px;">';
                dados += $(this).attr('label') + '</td>';
                dados += '<td style="border-top: 1px solid #E6E6E6;	border-bottom: 1px solid #E6E6E6;border-right: 1px solid #E6E6E6;"> ';
                dados += 'Não</td></tr>';
            }
        }
        else {
            eval('layout_msg = layout_msg.replace(/\\\[' + $(this).attr("id") + '\\\]/g, "' + $(this).val().replace(/(\r)?\n/g, "!abretag!br/!fechatag!") + '");');

            dados += '<tr><td style="width: 75px;text-align:right;font-weight:bold;	background-color:#E6E6E6;	width: 150px;">';
            dados += $(this).attr('label') + '</td>';
            dados += '<td style="border-top: 1px solid #E6E6E6;	border-bottom: 1px solid #E6E6E6;border-right: 1px solid #E6E6E6;"> ';
            dados += $(this).val().replace(/(\r)?\n/g, "<br/>") + '</td></tr>';
        }
    });

    dados = dados.replace(/</g, "!abretag!");
    dados = dados.replace(/>/g, "!fechatag!");

    eval('layout_msg = layout_msg.replace(/\\\[formulario_dados\\\]/g, \'' + dados + '\');');

    return(layout_msg); 
}

function imprimir() {
    
    $(this.destino).append(this.layout);

    var v_this = this;

    $(this.IdBtnEnviar).click(function () {
        v_this.getEmail();
    });

    if (this.IdBtnLimpar != null && this.IdBtnLimpar != '') {
        $(this.IdBtnLimpar).click(function () {
            if (confirm("Deseja realmente limpar o formulário?")) {
                $(v_this.destino + ' *[name="formulario_email"]').each(function () {
                    $(this).val('');
                });                
            }
        });
    }

    $(document).ready(function () {
        $(v_this.destino + " .masc_telefone").keypress(function () { mascara(this, telefone); });
        $(v_this.destino + " .masc_data").keypress(function () { mascara(this, data); });
        $(v_this.destino + " .masc_hora").keypress(function () { mascara(this, hora); });
        $(v_this.destino + " .masc_anos").keypress(function () { mascara(this, anos); });

        $("input[type='text'],input[type='password'],textarea").focus(function () { if ($(this).val() == "") { $(this).css("background-color", "#FFFFB3"); } });
        $("input[type='text'],input[type='password'],textarea").blur(function () { $(this).css("background-color", "#FFFFFF"); });


        $(v_this.destino + " .masc_money").maskMoney({ thousands: '.', decimal: ',' });
    });


}



function Formulario(parametros) {
    // Código fkempresa
    this.fkempresa = parametros.fkempresa;
    // Assunto do formulario
	this.assunto = parametros.assunto;
    //Id do botao enviar
	this.IdBtnEnviar = parametros.IdBtnEnviar;
	//Id do botao limpar
	this.IdBtnLimpar = parametros.IdBtnLimpar;
	//Id da div aguarde
	this.IdAguarde = parametros.IdAguarde;
    //Evento antes envio
	this.evtAntesEnvio = parametros.evtAntesEnvio;
	//Evento após envio
	this.evtPosEnvio = parametros.evtPosEnvio;
	//Id de destino
	this.destino = parametros.destino;
    //Email do formulario
    this.email = parametros.emailEnvio;
    // Layout da consulta
	this.layout = parametros.layout;
	// Layout da consulta msg
	this.layout_msg = parametros.layout_msg;
	//imovel
	this.imovel = "";

    //Métodos
	this.imprimir = imprimir;
	this.getEmail = getEmail;

}


//Mascarás

function mascara(o, f) {
    v_obj = o
    v_fun = f
    setTimeout("execmascara()", 1)
}

function execmascara() {
    v_obj.value = v_fun(v_obj.value)
}

function telefone(v) {
    if (v.length < 15) {
        v = v.replace(/\D/g, "")                 //Remove tudo o que não é dígito
        v = v.replace(/^(\d\d)(\d)/g, "($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos
        v = v.replace(/(\d{4})(\d)/, "$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    }
    else {
        v = v.substring(0, v.length - 1);
    }
    return v
}

function data(v) {
    if (v.length < 11) {
        v = v.replace(/\D/g, "")                    //Remove tudo o que não é dígito
        v = v.replace(/(\d{2})(\d)/, "$1/$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
        v = v.replace(/(\d{2})(\d)/, "$1/$2")       //Coloca um ponto entre o terceiro e o quarto dígitos    
    }
    else {
        v = v.substring(0, v.length - 1);
    }
    return v
}

function hora(v) {
    if (v.length < 6) {
        v = v.replace(/\D/g, "")                    //Remove tudo o que não é dígito
        v = v.replace(/(\d{2})(\d)/, "$1:$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    }

    return v;
}

function cep(v) {
    v = v.replace(/D/g, "")                //Remove tudo o que não é dígito
    v = v.replace(/^(\d{5})(\d)/, "$1-$2") //Esse é tão fácil que não merece explicações
    return v
}

function cpf(v) {
    v = v.replace(/\D/g, "")                    //Remove tudo o que não é dígito
    v = v.replace(/(\d{3})(\d)/, "$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v = v.replace(/(\d{3})(\d)/, "$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    //de novo (para o segundo bloco de números)
    v = v.replace(/(\d{3})(\d{1,2})$/, "$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
    return v
}

function rg(v) {
    v = v.replace(/\D/g, "")                    //Remove tudo o que não é dígito
    v = v.replace(/(\d{2})(\d)/, "$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v = v.replace(/(\d{3})(\d)/, "$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    //de novo (para o segundo bloco de números)
    v = v.replace(/(\d{3})(\d{1,2})$/, "$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
    return v
}

function cnpj(v) {
    v = v.replace(/\D/g, "")                           //Remove tudo o que não é dígito
    v = v.replace(/^(\d{2})(\d)/, "$1.$2")             //Coloca ponto entre o segundo e o terceiro dígitos
    v = v.replace(/^(\d{2})\.(\d{3})(\d)/, "$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
    v = v.replace(/\.(\d{3})(\d)/, ".$1/$2")           //Coloca uma barra entre o oitavo e o nono dígitos
    v = v.replace(/(\d{4})(\d)/, "$1-$2")              //Coloca um hífen depois do bloco de quatro dígitos
    return v
}

function anos(v) {
        v = v.replace(/\D/g, "")                    //Remove tudo o que não é dígito
        //v = v.replace(" anos", "")       //Coloca um ponto entre o terceiro e o quarto dígitos
    return v+" anos";
}

//chama o masked money
var j = document.createElement("script");
j.type = "text/javascript";
j.src = v_raiz + "Scripts/jquery.maskMoney.js";
document.body.appendChild(j);


