

var numFotos = 0;
var fotoCod = 0; // Codigo da foto selecionada.
var fotoPosition = 1;
var lastPage = false;
var fotosVisiveis = 0;
var fotoInicial = 1;
var fotoLocalPosition = 1;
var backServerPage = 1;
var nextServerPage = 1;
var first = true;
var noMove = false;

$(document).ready(function(){

    // Info da foto pequena
    $("a.pict-thumb").hover(
        function (e) {
            var infoTag = $(this).find(".photo-info");
            var infoCont = $(infoTag).contents().clone();
            var infoPhoto = document.createElement("div");
            var infoP = document.createElement("img");
            $(infoP).attr({
                "src":"/imagens/layout/bg-photo-info.gif",
                "class":"p"
            });
            $(infoPhoto).attr("id","photo-info");
            $(infoPhoto).css({
                "left" : (e.pageX - 41) + "px",
                "top": (e.pageY + 25) + "px"
            });
            $(infoPhoto).append(infoCont);
            $(infoPhoto).append(infoP);
            $("body").append(infoPhoto);
            $("#photo-info").fadeIn("fast");
        },
        function () {
            $("#photo-info").remove();
        }
        );

    $("a.pict-thumb").mousemove(
        function (e){
            $("#photo-info").css({
                "left":(e.pageX - 41) + "px",
                "top":(e.pageY + 25) + "px"
            });
        }
        );

    // fim info foto pequena

    // Função de anterior
    $('#btnAntLista').click(function() {
        previousPhotoList();
    });

    //Função de próxima
    $('#btnProxLista').click(function() {
        nextPhotoList();
    });

    // Funções das estrelas de rating
    $(".star-rating a").hover(
        function (e) {
            $("#midia-user-rating").html($(this).html());
            $("#midia-user-rating").show();
        },
        function () {
            $("#midia-user-rating").hide();
        }
        );
    $('.star-rating a').css('cursor','pointer');
    $("#midia-user-rating").hide();


    if (numFotos == 0)
        $('.placeslist-info').hide();

    // Lightbox (ainda não funcionando)
    /*
    $('a[rel=lightbox]').lightBox({
        overlayBgColor: '#000',
        overlayOpacity: 0.4,
        imageLoading: '/imagens/layout/ajax-loader.gif',
        imageBtnClose: '/imagens/layout/bt-exit.png',
        imageBtnPrev: '/imagens/layout/bt-prev2.png',
        imageBtnNext: '/imagens/layout/bt-next2.png',
        containerResizeSpeed: 350,
        containerBorderSize:50
    });*/

    atualizarFotosVisiveis();
    
    if(fotosVisiveis < 27 && backServerPage-1 > 1) {
        preloadImages(--backServerPage, true, true);
        noMove = true;
    }

    // Seleciona a foto atual na lista do topo
    fotoSeleciona(fotoCod);

    if(fotoLocalPosition >= 18) {
        preloadImages(++nextServerPage, false);
    }

    //fixListAccents();

    // Número de fotos atualmente na página
    //fotosVisiveis = $('.carousel-photos a').length;

    //alert(numFotos);
    //alert('Visiveis = '+fotosVisiveis);

});

function fixListAccents() {
    $('.carousel-photos a').each(function() {
        text = $(this).children('.photo-info').children('strong').text();
        text = decodeURIComponent(escape(text));
        text = text.substr(0, text.length-2);
        $(this).children('.photo-info').children('strong').text(text);
        $(this).children('img').attr('alt', text);
    });
}

/**
 *  Recupera a pagina da foto atual (com 9 itens por página)
 */
function getFotoPage() {
    var x = Math.ceil(fotoPosition/18);
    //alert('pagina: '+x);
    return x;
}

function atualizarFotosVisiveis() {
    fotosVisiveis = $('ul.carousel-photos li').length;
}

/**
 * Função que faz o slide da lista para a esquerda
 */
function previousPhotoList() {
    if(backServerPage >= 1) {
        
        fotoLocalPosition-=9;

        //alert('diferença : '+(numFotos - fotoPosition));
        //alert('comaparação : '+(fotosVisiveis-10));

        //movePhotoList(fotoLocalPosition);

        if(backServerPage > 1 && (fotoLocalPosition < 18)) {
            fotoLocalPosition +=27;
            preloadImages(--backServerPage, true);
        }
        if(fotoLocalPosition < 9 && backServerPage == 1) {
            fotoLocalPosition = 1;
            $('#btnAntLista').hide();
            $('#btnProxLista').show();
        } else {
            $('#btnAntLista').show();
            $('#btnProxLista').show();
        }

        movePhotoList(fotoLocalPosition);
    }
}

/**
 * Função que faz o slide da lista para a direita
 */
function nextPhotoList() {
    if(nextServerPage  >= Math.ceil(numFotos/27) && fotosVisiveis - fotoLocalPosition < 0) {
        return false;
    }

    fotoLocalPosition+=9;

    if((nextServerPage  < Math.ceil(numFotos/27)) && fotosVisiveis - fotoLocalPosition <= 18) {
        preloadImages(++nextServerPage);
    }
    if(fotosVisiveis - fotoLocalPosition <= 9 && nextServerPage  >= Math.ceil(numFotos/27)) {
        fotoLocalPosition = fotosVisiveis - 8;
        $('#btnProxLista').hide();
        $('#btnAntLista').show();
    } else {
        $('#btnProxLista').show();
        $('#btnAntLista').show();
    }

    movePhotoList(fotoLocalPosition);
}

/**
 * Função que move a lista de fotos para a posição indicada
 */
function movePhotoList(position, noAnimation, moveFirst) {
    if(!noAnimation) {
        if(moveFirst) {
            movePhotoList(position+18, true);
        }
        $("ul.carousel-photos").animate({
        left: (-106*(position-1)) + "px"
        }, 800 );//1500
    } else {
        $("ul.carousel-photos").css('left',(-106*(position-1)) + "px" );
    }
}

/**
 * Carrega fotos por ajax
 */
function preloadImages(page, prepend, moveNext) {
    var linkItem = $("#link_item").val();
    var url = linkItem+'fotos/listar/'+page+'/';
    //var params = 'codigo='+$('#cod_item').val()+'&tipo='+$('#tipo_item').val();
    //params += '&pag='+page;


    $.getJSON(url, null,
        function(data) {
            var result = eval(data);
            if (result['status'] == 'erro-login'){
                naoLogado();
            } else if (result['status'] == 'sucesso') {
                var fotos = result['fotos'];
                if(result['fotos'].length == 0) {
                    lastPage = true;
                    return false;
                }                
                var content = '';
                for(var x = 0; x < fotos.length; x++) {
                     content += "<li>"+
                            "<a href='javascript:changePhoto("+fotos[x].cod_foto+");' class='pict-thumb' id='other-photos-"+fotos[x].cod_foto+"'>"+
                                "<img src='"+fotos[x].image_src+"' alt='"+fotos[x].descricao+"'>"+
                                "<div class='photo-info'><strong>"+fotos[x].descricao+"</strong>"+
                                    "<span class='pstars level"+fotos[x].media_notas+"'>Nível "+fotos[x].media_notas+"</span>"+
                                    "<small>Enviado por<br>"+fotos[x].autor+"</small>"+
                                "</div>"+
                            "</a>"+
                        "</li>";
                    
                }
                if(prepend) {
                    $('ul.carousel-photos').prepend(content);
                }else {
                    $('ul.carousel-photos').append(content);
                }               
                if(moveNext && prepend) {
                    fotoLocalPosition += fotos.length;
                    movePhotoList(fotoLocalPosition, true);
                }
                atualizarFotosVisiveis();
            }
        });
}

/**
 * Seleciona a foto na lista de cima da página
 */
function fotoSeleciona(codFotoSelecionada){
    $('.carousel-photos li a').removeClass('active');
    var fotoSel = $('#other-photos-' + codFotoSelecionada);    
    $(fotoSel).addClass('active');
    setupLinks();
}

/**
 *  Cria os links de anteror e próximo de acordo com a foto
 *
 */
function setupLinks() {
    var carrouselPhotos = $('.carousel-photos a');

    for (i = 0; i < carrouselPhotos.length; i++) {
        if($(carrouselPhotos[i]).hasClass('active')) {

            fotoLocalPosition = i+1;

            var id = $(carrouselPhotos[i-1]).attr('id');
            if (! id)
                id = $(carrouselPhotos[carrouselPhotos.length-1]).attr('id');

            if(id) {
                id = id.split("-");
                id = id[id.length-1];
                $('#innerPrevious').attr('href', "javascript:changePhoto("+id+");");
            } else {
                $('#innerPrevious').hide();
            }

            var id2 = $(carrouselPhotos[i+1]).attr('id');
            if (! id2)
                id2 = $(carrouselPhotos[0]).attr('id');

            if(id2) {
                id2 = id2.split("-");
                id2 = id2[id2.length-1];
                $('#innerNext').attr('href', "javascript:changePhoto("+id2+");");
            } else {
                $('#innerNext').hide();
            }

            //alert("Posicao da foto:" +fotoPosition);
//            if(fotosVisiveis - fotoLocalPosition < 10 && numFotos > 10) {
//                fotoLocalPosition -= 8;
//            } else if(numFotos <= 9) {
//                fotoLocalPosition = 1;
//            }
            if(fotoLocalPosition == 1) {
                //fotoLocalPosition = fotosVisiveis - 8;
                $('#btnAntLista').hide();
                $('#btnProxLista').show();
            }

            if(numFotos <= 9) {
                $('#btnProxLista').hide();
                $('#btnAntLista').hide();
                movePhotoList(1, true);
            } else {

                if(first && !noMove) {
                    movePhotoList(fotoLocalPosition, true);
                    first = false;
                }

            }

            break;
        }
    }
}

function putLoadingImages(commentOnly) {
    if(!commentOnly)
        $('.first-result').html("<img src='/imagens/layout/ajax-loader-blue.gif' alt='Carregando' style='margin-left:35%; margin-top:20%;'/>Carregando");
    $('#comentarios_box').html("<img src='/imagens/layout/ajax-loader-blue.gif' alt='Carregando' style='margin-left:35%; margin-top:20%;'/>Carregando");

}

function changePhoto(codFoto) {
    var linkItem = $("#link_item").val();
    var urlToSend = linkItem+"fotos/"+codFoto+"/ajax/";
    //var parameters = "foto="+codFoto;
    //parameters += "&cache="+$('#cache').val();
    //parameters += "&cod_item="+$('#cod_item').val();
    //parameters += "&tipo_item="+$('#tipo_item').val();

    putLoadingImages();

    $.ajax({
        cache : false,
        type : 'POST',
        url : urlToSend,        
        dataType : 'json',
        error : function() {alert("Ocorreu um erro no request de AJAX.")},
        success : function(response) {

            response = eval(response);

            if(response.status == "sucesso") {
                $('#photo-wrapper').replaceWith(response['html']);
//                var text = $('#text-photo').text();
//                text = decodeURIComponent(escape(text));
//                text = text.substr(0, text.length-2);
//                $('#text-photo').text(text);
                fotoSeleciona(codFoto);
            } else if(response.status == "erro-inexistente") {
                $('#photo-wrapper').replaceWith(response['html']);
            } else {
                alert("Ocorreu um erro ao selecionar a foto.");
            }
        }

    });
}



/*
 * Comentarios
 */

function changeComments(pag) {
    var linkItem = $("#link_item").val();
    var urlComments = linkItem+'fotos/'+$("#cod_foto").val()+'/comentarios/'+pag+"/";
//    var parameters = "cod_foto="+$("#cod_foto").val();
//    parameters += "&pagComentarios="+pag;
//    parameters += "&cache="+$('#cache').val();

    putLoadingImages(true);

    $.getJSON(urlComments, null, function(response) {
        if(response.status == "sucesso") {
            $('div.minibox').replaceWith(response.html);
        } else {
            alert("Ocorreu um erro ao paginar os comentários");
        }
    });
}

function reloadComments () {
    closefloatbox();

    setTimeout("changeComments($('#pag_com').val())", 1000);
}


// Estrelinhas //

/**
 * Seleciona estrelinha.
 */
function midiaSelecionarVoto(midiaEstrela, numero_estrela) {
    document.getElementById("current-rating").style.width = (numero_estrela*100/5) + '%';
    document.getElementById("midia-nota").value = numero_estrela;
    $("#midia-user-rating").html(midiaEstrela.innerHTML);

    // Envia nota por ajax
    var url = '/includes/ajax/fotos/votar-fotos.php';
    var parametros = 'foto=' + fotoCod + '&nota=' + numero_estrela;

    $.post(	url,
        parametros,
        function(result){
            result = eval(result);
            if ( result['status'] == 'sucesso'){
                var fbDenuncia;
                fbDenuncia = new FloatBox('Avalie', '<h3>Foto avaliada com sucesso!</h3>');
                fbDenuncia.abrir();
            }
            else if ( result['status'] == 'erro-login' ){
                naoLogado();
                document.getElementById("current-rating").style.width = 0+'px';
                document.getElementById("midia-nota").value= 0;
                $("#midia-user-rating").html('');
            }
            else {
                FloatBoxAlert();
                document.getElementById("current-rating").style.width = 0+'px';
                document.getElementById("midia-nota").value= 0;
                $("#midia-user-rating").html('');
            }
        },
        "json");
}


/**
 * Define quantidade de comentï¿½rios (dessa forma nï¿½o ï¿½ necessï¿½rio atualizar cache da Foto para atualizar qtde de comentï¿½rios).
 */
function midiaQtdeComentarios(qtdeComentarios)
{
    $('#numComments').text(qtdeComentarios);
}
