/* 
 * Arquivo que contem funcoes genericas de javascript
 */

// funcao que atualiza dinamicamente um combo box, atraves de um consulta.

function executeLightBox(image_url, img){
    img.lightBox({
        imageLoading: image_url.attr('class')+'/lightbox/loading.gif',
        imageBtnClose: image_url.attr('class')+'/lightbox/btn-close.gif',
        imageBtnPrev: image_url.attr('class')+'/lightbox/btn-prev.gif',
        imageBtnNext: image_url.attr('class')+'/lightbox/btn-next.gif',
        txtImage:'imagem',
        txtOf:'de'
    });
}


function loadPopup(link, div){
    loadDiv(link, div);
    loadPopUp();
}

function carregarCombo(elemento, url,  valor, method){
    $(elemento).html("<option value=''> Carregando ... </option>");
    $.post(url, {
        id: valor
    },
    function(response) {
        $(elemento).html(response);
        if (method)
            window[method]();//chamada dinamica de funcoes
    });
}

function loadImagem(link){
    loadDiv(link, '#conteudo');
    loadPopUp();
}

function loadPopUp(){
    var id = "#popUp";

    var maskHeight = $(document).height();
    var maskWidth = $(window).width();

    $('#mask').css({
        'width':maskWidth,
        'height':maskHeight
    });

    $('#mask').fadeIn(500);
    $('#mask').fadeTo("slow",0.8);

    //Get the window height and width
    var winH = $(window).height();
    var winW = $(window).width();

    $(id).css('top',  winH/2-$(id).height()/2);
    $(id).css('left', winW/2-$(id).width()/2);

    $(id).fadeIn(500);

}

function loadDiv(link, div){
    $(div).load(link);
}

function closeWindow(){
    $('#mask').hide();
    $('.window').hide();
    $('#divEstatisticas').show();
}


/* funcao que submete um form para ativar ou desativar objetos no BD*/
function ativarOrDesativar(input, form, opcao){
    $(input).val(opcao);
    $(form).submit();
}
/* FIM - funcao que submete um form para ativar ou desativar objetos no BD*/

function trim(str) {
    return str.replace(/^\s+|\s+$/g,"");
}

function carregarEmail(select, url, prefix, type){
    var id = $(select).val();//trocar nome
    if (id==''){
    }else{
        $.post(url, {
            id: id
        },
        function(response) {
            var vector = response.split('/#;/');
            var field = null;
            for(i = 0; i<vector.length; i++){
                field = vector[i].split('/:=>');
                if (field[0]=='corpo'){
                    var t = tinyMCE.get(prefix+field[0])
                    t.setContent(field[1]);
                }
                else{
                    $('#'+prefix+field[0]).val(field[1]);
                }
                    
            }
        });

    }
}

function carregarListaEmails(select, url, elemento){
    var valor = $(select).val();
    carregarCombo(elemento, url,  valor)
}

function check_extension(filename, ext) {
    if (filename!='') {
        if (filename.lastIndexOf("."+ext)!=-1) {
            return true;
        } else {
            displayMessage('Só arquivos no formato '+ext+' são permitidos.');

            return false;
        }
    }else
        displayMessage('Selecione um arquivo.');

    return false;
}

function setUsername(emailInput, user){
    var email =  trim($(emailInput).val());
    $(user).val(email);
}

function setPassword(emailInput, password){
    var email =  trim($(emailInput).val());
    $(password).val(email);
}


function setUserAndPasswords(emailInput, user, password){
    setUsername(emailInput, user);
    setPassword(emailInput, password);
    setPassword(emailInput, password+'_again');
}

function displayMessage(msg, type){
    switch (type) {
        case 'error':
            $('#message_div').css('color','red');
            break;
        case 'confirm':
            $('#message_div').css('color','green');
            break;
        case 'warning':
            $('#message_div').css('color','blue');
            break;
        default:
            break;
    }
    $('#message_div').text(msg);
    $('#message_div').css('display','block');
}

function processMessage(response){
    var result = response.split(';')
    var field;
    var type;
    var msg;

    for(i = 0; i<result.length; i++){
        field = result[i].split('=');
        if (field[0]=='type')
            type = field[1];
        else
            msg = field[1];
    }

    displayMessage(msg, type);
}

function processDadosFromServer(response, prefix, type){
    var vector = response.split('/#;/');
    var field = null;
    for(i = 0; i<vector.length; i++){
        field = vector[i].split('/:=>');
        if (type=='val'){
            $('#'+prefix+field[0]).val(field[1]);
        }
        else {
            $('#'+prefix+field[0]).text(field[1]);
        }
    }
}

function getDadosFromServer(select, url, prefix, type){
    var id = $(select).val();//trocar nome
    if (id==''){
    }
    else{
        $.post(url, {
            id: id
        },
        function(response) {
            processDadosFromServer(response, prefix, type);
        });
    }
}

function processIndexCheckBoxes(isChecked){
    var ids = '';
    $('#message_div').css('display','none');
    $('.indexForm :checkbox').each(function(){
        $(this).attr('checked',isChecked);
        ids+= $(this).val()+",";

        if ($('#modulo').length != 0 &&  $('#modulo').attr('class')== 'usuarios' && $(this).val()==$('#user_id').attr('class') && isChecked){
            displayMessage($('#msg_user').attr('class'), 'warning');
        }
    // insertOrRemoveAtSession($('#url').val(),this);
    });

    ids+= ids.substring(0,ids.length-1);
    sendIdsToSession(ids, isChecked);
}

function sendIdsToSession(ids, isChecked){
    var url = $('#url').val();

    $.post(url, {
        objects: ids,
        checked: isChecked,
        is_batch: 'true'
    },
    function() {
        });
}

function mudarImageCheck(a){
    var path = a.find('img').attr('src')
    if (a.attr('lang')== 'todos'){
        a.attr('lang', 'nenhum');
        a.find('img').attr('src', path.split("cheked_16.png",1)+'uncheked_16.png');
        processIndexCheckBoxes(true);
    }else{
        a.attr('lang', 'todos');
        a.find('img').attr('src',path.split("uncheked_16.png",1)+'cheked_16.png');
        processIndexCheckBoxes(false);
    }
}

function insertOrRemoveAtSession(url, checkbox){
    $('#message_div').css('display','none');
    if ($('#modulo').length != 0 &&  $('#modulo').attr('class')== 'usuarios' && $(checkbox).val()==$('#user_id').attr('class') && $(checkbox).attr('checked')){
        displayMessage($('#msg_user').attr('class'), 'warning');
    }
    $.post(url, {
        id: $(checkbox).val(),
        checked: $(checkbox).attr('checked')
    },
    function() {
        });
}

function carregarBairros(){
    if ($("select[name*='cidade_id']").length!=0){
        carregarCombo("select[name*='bairro_id']", $('#url_get_bairros').val(), $("select[name*='cidade_id']").val());
    }
}

/*function slideSwitch() {
    var $active = $('#slideshow IMG.active');

    if ( $active.length == 0 ) $active = $('#slideshow img:last');

    var $next =  $active.next().length ? $active.next()
    : $('#slideshow img:first');

    $active.addClass('last-active');

    $next.css({
        opacity: 0.0
    })
    .addClass('active')
    .animate({
        opacity: 1.0
    }, 1000, function() {
        $active.removeClass('active last-active');
    });
}*/


$(document).ready(function() {

    $('.window .close').live("click",function (e) {
        e.preventDefault();
        closeWindow();
    });

    $('#mask').click(function () {
        closeWindow();
    });

    $('.selecionarObjetos').click(function(e){
        e.preventDefault();
        mudarImageCheck($(this));
    });

    if ($("select[name*='categoria_id']").length!=0){
    //carregarCombo("select[name*='secao_id']", $('#url_get_secoes').val(), $(this).val());
    }

    $("select[name*='categoria_id']").change(function(){
        carregarCombo("select[name*='secao_id']", $('#url_get_secoes').val(), $(this).val());
    });

    $("select[id='categoria']").change(function(){
        carregarCombo("select[id='secao']", $('#url_get_secoes').val(), $(this).val());
    });


    /* funcao que captura o click do link de exclusao de uma lista de objetos*/
    $('#batchDelete').click(function(e){
        e.preventDefault();
        var msg = $(this).attr('type');
        if (confirm(msg)){
            var form = $('.divForm form');
            form.attr('action',$(this).attr('href'));
            form.submit();
        }

    });
    /* FIM - funcao que captura o click do link de exclusao de uma lista de objetos*/

   
    
});

