window.addEvent('domready', function() {
	//time to implement basic show / hide
	Element.implement({

        //implement show
		show: function() {
			this.setStyle('display','');
		},

		//implement show
		showModal: function() {
			this.setStyles({
			    display: 'block',
			    opacity: 0.8
			});
		},

		//implement hide
		hide: function() {
			this.setStyle('display','none');
		}
	});
});

/**
 * Procede com a abertura da pesquisa
 * @author Luiz Antonio B. Silva [Labs]
 * @copyright Labs 2009
 **/
function checkParticipante(){

    var vabertura = parseInt($('dt_abertura').value);
    if (!vabertura) {
        alert('O Ano de Abertura é de preenchimento obrigatório!');
        $('dt_abertura').focus()
        return;
    }

    if (vabertura > 2009 || vabertura < 1900) {
        alert('O Ano de Abertura não parece correto!');
        $('dt_abertura').focus()
        return;
    }

    var d = new Date().getFullYear();
    if ((d-vabertura) <= 1) {
        $('identificacao').hide();
        $('area_agradecimento_data').show();
        return false;
    }

    var vcnpj = $('cnpj').value;
    if (!vcnpj) {
        alert('O CNPJ é de preenchimento obrigatório!' + vcnpj);
        $('cnpj').focus();
        return;
    }
    if (!isCnpj(vcnpj)) {
       alert('O CNPJ informado não é válido!');
       $('cnpj').focus();
       return;
    }

    $('modal').showModal();
    $('cadastro').getElements('.text').each(function(item, index){
        item.value = '';
    });
    var myRequest = new Request.JSON({
        url: 'lib/pesquisas.php',
        method: 'post',
        data: {
            cnpj: vcnpj,
            op: 'checkParticipante'
        },
        onSuccess: function(participante) {
            $('modal').hide();

            if (participante) {
                questObj.participante = new Hash(participante);
                questObj.entidades_key = participante['entidades_key'];
                questObj.participante.each(function(value, key){
                    if ($(key)) {
                        $(key).value = value;
                    }
                });
                if (!questObj.participante.dt_abertura) {
                    $('dt_abertura').value = vabertura;
                }
            }
            $('cadastro').show();
        }
    }).send();
}


function iniciarPesquisa(){

    // ===--- Recupera dados:
    var ok = true;
    $('cadastro').getElements('.text').each(function(item, index){
        if (!item.value && item.hasClass('obrigatorio')) {
            $(item).highlight('red');
            alert('Os campos marcados com asterisco (*) são de preenchimento obrigatório!');
            ok = false;
        }
        questObj.participante[item.id] = item.value;
    });
    questObj.participante.dt_abertura = $('dt_abertura').value;
    questObj.participante.cnpj = $('cnpj').value;
    if (!ok) {
        return;
    }

    var myRequest = new Request.JSON({
        url: 'lib/pesquisas.php',
        method: 'post',
        data: {
            questionarios_key: questObj.questionarios_key,
            entidades_key: (questObj.entidades_key || 0),
            participante: Hash.toQueryString(questObj.participante),
            op: 'gravaParticipante'
        },
        onSuccess: function(res) {
            questObj['entidades_key'] = res.entidades_key;
            $('identificacao').hide();
            $('cadastro').hide();

            $('lbl_nome').set('text', questObj.participante.nome);
            $('lbl_razao').set('text', questObj.participante.razao_social);
            $('area_perguntas').show();
            //nextPage();
        }
    }).send();
}


/**
 * Envia a pesquisa ao servidor.
 * @author Luiz Antonio B. Silva [Labs]
 * @copyright Labs 2009
 **/
function enviarPesquisa(){

    // ===--- Valida perguntas:
    var ok = true;
    $$('.area_pergunta').each(function(item){
        if (item.get('validacao') && ok) {
            var func = item.get('validacao');
            eval('ok = '+func+'(item)');
            if (!ok) return;
        }
    });
    if (!ok) return;

    var myRequest = new Request.JSON({
        url: 'lib/pesquisas.php',
        method: 'post',
        data: {
            questionarios_key: questObj.questionarios_key,
            entidades_key: questObj.entidades_key,
            respostas: $('respostas').toQueryString(),
            op: 'gravaRespostas'
        },
        onSuccess: function(res) {
            if (res) {
                alert('Desculpe-nos, mas ocorreu um erro ao salvar seus dados.\n'+res['erro']);

            } else {
                $('area_perguntas').hide();
                $('area_agradecimento_ok').show();
            }
        }
    }).send();
}


/**
 * Exibe perguntas dependendo da seleção de opções.
 * @author Luiz Antonio B. Silva [Labs]
 * @copyright Labs 2009
 **/
function showPerguntas(opt, numeros){
    for (var x=0;x<numeros.length;x++){
        var p = numeros[x];
        if ($('perg_'+p)) {
            if ($(opt).checked) {
                $('perg_'+p).show();
            }
        }
    }
}

/**
 * Esconde perguntas dependendo da seleção de opções.
 * @author Luiz Antonio B. Silva [Labs]
 * @copyright Labs 2009
 **/
function hidePerguntas(opt, numeros){
    for (var x=0;x<numeros.length;x++){
        var p = numeros[x];
        if ($('perg_'+p)) {
            if ($(opt).checked) {
                $('perg_'+p).hide();
                $('perg_'+p).getElements('.chk').each(function(item){
                    item.checked = false;
                });
                $('perg_'+p).getElements('.rad').each(function(item){
                    item.checked = false;
                });
                $('perg_'+p).getElements('.text').each(function(item){
                    item.value = '';
                });
            } else {
                $('perg_'+p).show();
            }
        }
    }
}

/**
 * Verifica se o usuário selecionou mais respostas que o permitido.
 * @author Luiz Antonio B. Silva [Labs]
 * @copyright Labs 2009
 **/
function checkLimite(sender, opt, n, max){
    var total = 0;
    $('perg_'+n).getElements('.chk').each(function(item){
        if (item.checked) {
            total++;
        }
    });

    if (total > max) {
        $(sender).checked = false;
        alert('Escolha apenas '+max+' opções.')
    }
}

/**
 * Verifica se o total de extras soma mais que 100.
 * @access public
 * @return void
 **/
function check100(pergunta){
    var t = 0;
    pergunta.getElements('.inp_extra').each(function(item){
        var n = (item.value ? toFloat(item.value) : 0);
        t += parseFloat(n);
    });

    if (t != 100) {
        pergunta.setStyles({
            'background-color': '#ff99ff'
        });
        alert('O total das opções deverá ser igual a 100%.');
        var myFx = new Fx.Scroll(window).toElement(pergunta);
        return false;
    }
    return true;
}

function toFloat(valor){
    if (!valor) {
        return 0;
    }

    if (typeof(valor) == 'string') {
        valor = valor.replace(/\./, '');
        valor = valor.replace(/,/, '.');
        return parseFloat(valor);
    }

    return valor;
}

/**
 * Verifica se existe uma sequencia de números em extras.
 * @access public
 * @return void
 **/
function checkSequencia(pergunta){
    var arr = [];
    pergunta.getElements('.inp_extra').each(function(item){
        if (Number(item.value) > 0) {
            arr.push(Number(item.value));
        }
    }.bind(this));
    arr.sort(function(a,b){return a - b});
    for (var x=0;x<arr.length;x++){
        if (x == 0) {
            if (arr[x] != 1) {
                return setPerguntaErro(pergunta, 'A sequência de números não parece válida.');
                return false;
            }
        } else {
            if ((arr[x]-arr[x-1]) != 1) {
                return setPerguntaErro(pergunta, 'A sequência de números não parece válida.');
                return false;
            }
        }
    }
    return true;
}

function setPerguntaErro(pergunta, msg){
    pergunta.setStyles({
        'background-color': '#ff99ff'
    });
    alert(msg);
    var myFx = new Fx.Scroll(window).toElement(pergunta);
    return false;
}


/**
 * Exibe ou esconde área de informações complementares.
 * @author Luiz Antonio B. Silva [Labs]
 * @copyright Labs 2009
 **/
function swapExtraCheck(opt, n){
    if ($(opt).checked) {
        $('extra_'+opt).show();
    } else {
        $('extra_'+opt).hide();
        $('extra_'+opt).getElements('.inp_extra').each(function(item){
            item.value = '';
        });
    }
}

/**
 * Certifica que as áreas extras de outros radios estejam
 * escondidas.
 * @author Luiz Antonio B. Silva [Labs]
 * @copyright Labs 2009
 **/
function swapExtraRadio(opt, n){
    $('perg_'+n).getElements('.area_extra').hide();
    swapExtraCheck(opt, n);
}

/**
 *
 * @access public
 * @return void
 **/
function validateMask(type, inp){
    switch (type) {
        case 'float': inp.value = inp.value.replace(/[^0123456789,]/gm, ''); break;
        case 'int'  : inp.value = inp.value.replace(/\D/gm, ''); break;
        //case 'float': maskFloat(inp); break;
    }
}

function checkEmail(valor){
    var reEmail = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
    return (reEmail.test(valor));
}

function maskFloat(inp){

    // ===--- Limpa string:
    sinal = (inp.value.substr(0,1) == '-' ? '-' : '');
    var value  = inp.value.replace(/\D/gm, '');
    var res = '';

    // ===--- Só decimal:
    var len = value.length;
    if (len > 0 && len <= 2){
        res = ',' + value;

    // ===--- Maior que decimal:
    } else if (len > 2) {

        // ===--- Retira decimal:
        res = ',' + value.substr(value.length-2, 2);
        value  = value.substring(0, value.length-2);

        // ===--- Retira milhares:
        var n=0;
        while (value.length > 3){
            res = (n > 0 ? '.' + res : res);
            res = value.substr(value.length-3, 3) + res;
            value  = value.substring(0, value.length-3);
            n++;
        }
        var r = value + res;
        var p = (r.length > 6 ? '.' : '');
        res = value + p + res;
    }

    // ===--- Retorna:
    if (!res) {
        //res = '0,00';
    }

    inp.value = sinal + res;
}