/*
 * CÓDIGO PRINCIPAL (requer Jquery)
 *
 * Este código contém ações relacionadas aos recursos principais da aplicação
 *
 * @package JS
 * @category Functions
 * @name ajax.functions.js
 * @author Alexandre de Oliveira <chavedomundo@gmail.com>
 * @since v0.1 25/06/2009
 */
/**
 * Variáveis do sistema
 */


var tarefas;
var cronometroTarefas = new Object();
var temTarefas;
var lastId = 0;
var primeiroLoad = true;

/**
 * O código abaixo é chamado automaticamente quando a página termina de carregar
 */
$(document).ready(function(){

    //alert(json_tarefas);
    temTarefas = false;
    initTarefas(json_tarefas);


    $(".nova_tarefa .input_tarefa").focus();
    /**
     * NOVA TAREFA
     *
     * Botão de submit com evento click
     */
    //$(".nova_tarefa .botao_submit").bind("click", function(){
        //submitNovaTarefa( $(".nova_tarefa .input_tarefa").attr("value") );
    //});
    
    //$(".merchandising").hide();
    if( !temTarefas ){
        //$(".merchandising:random").show();
    }
    /**
     * Atualiza eventos
     */
    setConfig();
    /**
     * LIGHTBOX
     */
    /**
     * Seleciona os elementos a com atributo name="modal"
     * e atribui evento a eles para amostragem de lightbox
     */
    $('a[name=modal]').click(function(e) {
        /*
         * Cancela o comportamento padrão do link e Armazena o atributo href do link
         */
        e.preventDefault();
        var id = "#" + $(this).attr('class');

        /*
         * Armazena a largura e a altura da tela
         */
        var maskHeight = $(document).height();
        var maskWidth = $(document).width();

        /*
         * Define largura e altura do div#mask iguais às dimensoes da tela
         */
        $('#mask').css({'width':maskWidth,'height':maskHeight});

        /*
         * Efeito de transição
         */
        $('#mask').fadeIn(400);
        $('#mask').fadeTo("slow", 0.9);

        /*
         * Armazena a largura e a altura da janela
         */
        var winH = $(window).height();
        var winW = $(window).width();

        /*
         * Centraliza na tela a janela popup
         */
        var top = (winH - $( id ).height()) / 2;
        var left = (winW - $( id ).width()) / 2;

        $( id ).css('top', top);
        $( id ).css('left', left);

        //alert(id);

        $(id).fadeIn(800);

        /**
         * Focus
         */
        if( id == "#modalcarregar" ){
            $("#modalcarregar input[name=email]").focus();
        } else if( id == "#modalgravar" ) {
            $("#modalgravar input[name=email]").focus();
        }
    });

    /**
     * Dá comando ao botão de fechar do Lightbox
     */
    $('.window .close').click(function(e){
        e.preventDefault();
        $('#mask, .window').fadeOut("normal");
    });

});




/*
 * Configurações iniciais dos elementos
 *
 * Deve ser chamado após todo callback Ajax
 */
function setConfig(){

    $(".tarefa").hover(
        function(){
            $(".opcoes", this).fadeIn("fast");
        },
        function(){
            $(".opcoes", this).fadeOut("fast");
        }
    );

    /**
     * Se tem tarefa, esconde botões que não devem aparecer
     */
    temTarefas = false;

    if( $("div.tarefa").length > 0 ){
        temTarefas = true;
    }

    //alert( temTarefas + ' - ' + $("div.tarefa").length );

    if ( temTarefas == true ){
        $(".avisos").hide();
        $(".tarefa .opcoes").hide();
        $(".merchandising").slideUp();
        $("li.limpar_lista").show();
        $("li.salvar_lista").show();
    } else {
        $("li.limpar_lista").fadeOut("fast");
        $("li.salvar_lista").fadeOut("fast");
        // Se não há .merchandising, mostra um
        if( $(".merchandising").css("display") == "none" ){

            /**
             * Mostra um merchan randômico
             */
            var merchanQtd = $(".merchandising").size();
            var merchanRandom = Math.floor(Math.random() * merchanQtd +1 );
            if( primeiroLoad == true ){
                $("#merchan_"+merchanRandom).show();
            } else {
                $("#merchan_"+merchanRandom).slideDown("slow");
            }
        }
    }

    primeiroLoad = false;
    /**
     * Função que esconde ou mostra elementos HTML de acordo com a existência
     * ou não de tarefas.
     */
    gerenciaHtml();
}

/**
 * SAFARI não suporta um monte de funções jQuery.
 */
function seSafari(){
    // verifica se é o safari problemático
    safari = false;
    jQuery.each(jQuery.browser, function(i, val) {
        //alert(i);
        if($.browser.safari)
            safari = true;
          //  alert("Do stuff for safari");
    });

    if(safari){
        return true;
    } else {
        return false;
    }
}

/**
 * LOGIN
 */
function ajaxLogin(este){

    $("#ajax_login_status").hide();
    $("#ajax_login_status div").hide();
    $("#ajax_login_status .carregando").show();
    $("#ajax_login_status").fadeIn();

    var varLogin = este.email.value;
    var varSenha = este.senha.value;

    var tarefasCount = 0;
    jQuery.each(tarefas, function(i, value){
        tarefasCount++;
    })

    /**
     * Se houverem tarefas não salvas, alerta o usuário para salvá-las antes.
     */
    if( tarefasCount > 0 ){
        if( !confirm("Você está prestes a perder suas tarefas."+
                    " Para que isto não ocorra, salve sua lista antes de continuar.\n\n" +
                    "Pressione OK para continuar mesmo assim.") ){
            $("#ajax_login_status div").hide();
            return false;
        }
    }
    $.ajax(
        {
            url: WEBROOT+"usuarios/ajaxlogin/",
            //global: false,
            type: "POST",
            data: ({
                login : varLogin,
                senha : varSenha
            }),
            dataType: "html",
            complete: function(msg){
                //alert(msg.responseText);
                if( msg.responseText == 1 ){
                    $("#ajax_login_status div").hide();
                    $("#ajax_login_status .login_certo").show();
                    window.location = THIS_LOCATION+"site/principal/login:loaded";
                } else {
                    $("#ajax_login_status div").hide();
                    $("#ajax_login_status .login_errado").show();
                }
            }
        }
    );

    return false;
}

function saveAjaxLogin(este, merge){

    $("#save_ajax_login_status").hide();
    $("#save_ajax_login_status div").hide();
    $("#save_ajax_login_status .carregando").show();
    $("#save_ajax_login_status").fadeIn();

    var varLogin = este.email.value;
    var varSenha = este.senha.value;

    /**
     * Verifica se há ordem de mesclagem
     */
    if(merge == 1){
        merge = "merge";
    } else {
        merge = "";
    }
    
    $.ajax(
        {
            url: WEBROOT+"usuarios/saveajaxlogin/"+merge,
            //global: false,
            type: "POST",
            data: ({
                login : varLogin,
                senha : varSenha
            }),
            dataType: "html",
            complete: function(msg){
                /**
                 * Resultados
                 *      1: Sucesso, logou e salvou a lista
                 *      0: Insucesso, login incorreto
                 *     -1: Conflito, há lista salvas anteriormente
                 *
                 */

                //alert(msg.responseText);

                if( msg.responseText == 2 ){
                    $("#save_ajax_login_status div").hide();
                    $("#save_ajax_login_status .carregando").show();
                    alert(  "Mesclagem concluída com sucesso.\n" +
                            "Pressione OK para recarregar suas tarefas.");
                    window.location = THIS_LOCATION;
                }
                /**
                 * LOGIN SEM CONFLIFTT
                 */
                else if( msg.responseText == 1 ){
                    $("#save_ajax_login_status div").hide();
                    $("#save_ajax_login_status .login_certo").show();
                    alert(  "Tarefas salvas com sucesso.\n\n" +
                            "Pressione OK para atualizar sua lista de tarefas.");
                    window.location = THIS_LOCATION;

                }
                /**
                 * Senha incorreta
                 */
                else if( msg.responseText == 0 ) {
                    $("#save_ajax_login_status div").hide();
                    $("#save_ajax_login_status .login_errado").show();
                }
                /**
                 * CONFLITO DE TAREFAS
                 *
                 * Já existêm tarefas no DB
                 */
                else if( msg.responseText == -1 ) {
                    $("#save_ajax_login_status div").hide();
                    $("#save_ajax_login_status .carregando").show();
                    if ( confirm(   "Seus dados estão corretos, entretanto você"+
                                    " já tem tarefas salvas anteriormente.\n\n" +
                                    "Pressione OK para mesclar as duas listas (recomendado).") ){
                        saveAjaxLogin(este,1);
                    } else {
                        $("#save_ajax_login_status div").hide();
                        $("#save_ajax_login_status .nao_salvou").show();
                    }
                }
            }
        }
    );
    
    return false;

}
