﻿
// Verifica se existe novas musicas a serem adicionadas na lista de reproducao
function CheckQueue() {
    jQuery.ajax({
        type: "POST",
        url: "/Player/ajax/ListaReproducao/CheckQueue.aspx",
        cache: false,
        success: function (data) {
            var $playnow = $("#hfSongToPlay", data);

            // Verifica se existe musica para iniciar a tocar
            if ($playnow.val() != "") {
                var id = $playnow.val();                
                PlayOn(id);
                $(window).focus();
                ListaReproducao_OnClick();
            } else {

                // Remove o input hidden
                var $tracks = $("table tbody", data);

                if ($tracks.html() != null) {

                    // Adiciona as musicas na lista
                    $("#listaReproducao table tbody").append($tracks.html());

                    // Reorganiza as cores
                    $("#listaReproducao table tbody tr.trTrack").addClass("alternative");
                    $("#listaReproducao table tbody tr.trTrack:even").removeClass("alternative");

                    // Ajusta tamanho da tela
                    resizeMenuContent();

                    // Ajusta as colunas da tabela
                    AjustaTabela();

                    // Evento de click na musica
                    $("#listaReproducao a.playMusic").unbind("click");
                    $("#listaReproducao a.playMusic").click(function () {

                        // Recupera o ID da musica na lista de reproducao
                        var id = $(this).attr("rel");

                        // Toca a musica da lista de reproducao
                        PlayOn(id);

                        return false;
                    });
                }
            }

            setTimeout(function () { CheckQueue(); }, 1500);
        }
    });    
   
}

// Carrega a lista de reproducao
function LoadSongs() {
    jQuery.ajax({
        type: "POST",
        url: "/PLayer/Ajax/ListaReproducao/LoadSongs.aspx",
        cache: false,
        success: function (data) {
            $("#tracks").hide()
            $("#listaReproducao table tbody").html(data);
            $("#listaReproducao .loadBox").remove();
            $("#listaReproducao").show();
            $("#dvRadio").hide();                                              

            // Ajusta as colunas da tabela
            AjustaTabela();

            // Ajusta o tamanho da tela
            resizeMenuContent();

            // Adiciona classe na ultima tr da tabela
            $(".tbTracks tr").last().addClass("lastTr");      

            // Evento de click na musica
            $("#listaReproducao a.playMusic").click(function () {

                if (bannerON) { return false; }

                // Recupera o ID da musica na lista de reproducao
                var id = $(this).attr("rel");

                // Toca a musica da lista de reproducao
                PlayOn(id);

                // Desliga a radio
                RadioOFF();

                return false;
            });


            // Acoes dos botoes de compartilhar das musicas
            ButtonShareActions();

            // Marca a musica que esta tocando
            if (musica != null) {
                var obj = $("#listaReproducao a.playMusic[rel=" + musica.ListaReproducao_id + "]").parent().parent();
                $(obj).addClass("selected");
            }

            // Evento de click de selecionar todas as musicas
            $("#checkAll").change(function () {
                $(".checkTrack").attr("checked", this.checked);
            });
        }
    });
}

// Limpa a lista de reproducao
function CleanList() {
    jQuery.ajax({
        type: "POST",
        url: "/Player/Ajax/ListaReproducao/DelAll.aspx",        
        cache: false,
        success: function (data) {
            LoadSongs();
        }
    });
}

// Deleta as musicas da lista de reproducao
function DelSongs(songs) {
    // Efetua o post(ajax) com as musicas
    jQuery.ajax({
        type: "POST",
        url: "/Player/Ajax/ListaReproducao/DelSongs.aspx",
        data: "songs=" + songs,
        cache: false,
        success: function (data) {
            LoadSongs();
        }
    });
}

// Adiciona as musicas na playlist selecionada na combo
function AddToPlaylist(playlist_id, arrID) {  
    jQuery.ajax({
        type: "POST",
        url: "/Player/Ajax/ListaReproducao/AddToPlaylist.aspx",
        data: "playlist_id=" + playlist_id + "&songs=" + arrID,
        cache: false,
        success: function (data) {            
            LoadMenu();
            jQuery.jGrowl("Música(s) adicionada(s) com sucesso.", { theme: 'sucesso' });
        }
    });
}

// Adiciona as musicas da playlist na lista de reproducao
function AddPlaylistToQueue(playlist_id, playnow) {

    var left = (screen.width - 1024) / 2;
    var newwindow = window.open('/Player/Default.aspx', 'player', 'left=' + left + ',height=' + (screen.height - 100) + ',width=1024');
    if (newwindow) {
        newwindow.focus();

        jQuery.ajax({
            type: "POST",
            url: "/Player/Ajax/ListaReproducao/AddSongs.aspx",
            data: "playlist_id=" + playlist_id + "&play=" + playnow,
            cache: false,
            success: function (id) {
                if (id.length > 0) {
                    // Sucesso    
                    jQuery.jGrowl("Música(s) adicionada(s) com sucesso.", { theme: 'sucesso' });
                } else {
                    // Erro
                    jQuery.jGrowl("Ocorreu um erro ao adicionar a(s) música(s).", { theme: 'erro' });
                }
            }
        });

        
    }
    return false;
    //OpenPlayer();
}

// Adiciona as musicas na fila de reproducao
function AddToQueue(songs, play) {    
    // Efetua o post(ajax) com as musicas
    jQuery.ajax({
        type: "POST",
        url: "/Player/Ajax/ListaReproducao/AddSongs.aspx",
        data: "songs=" + songs + "&play=" + play,
        cache: false,
        success: function (id) {
            if (id.length > 0) {
                // Sucesso    
                jQuery.jGrowl("Música(s) adicionada(s) com sucesso.", { theme: 'sucesso' });
            } else {
                // Erro
                jQuery.jGrowl("Ocorreu um erro ao adicionar a(s) música(s).", { theme: 'erro' });
            }

        }
    });
}

// Adiciona as musicas na fila de reproducao e toca a primeira
function AddAndPlay(songs) {        
    // Efetua o post(ajax) com as musicas
    jQuery.ajax({
        type: "POST",
        url: "/Player/Ajax/ListaReproducao/AddSongs.aspx",
        data: "songs=" + songs,
        cache: false,
        success: function (id) {            
            if (id.length > 0) {
                // Play                
                PlayOn(id);
            }
        }
    });
}

// Evento click na lista de reproducao no menu
function ListaReproducao_OnClick() {
    listaReproducao = 1;

    // Efetua o post(ajax) com as musicas
    $("#tracks").prepend(loading);
    $("#listaReproducao").prepend(loading);

    $("#btnPlayAllAddQueue").hide();    
    
    // desmarca item selecionado no menu
    CleanMenuSelected(); 

    // Esconde todos os botoes
    HideAllActionButtons();

    $("#btExcludeItens").show();
    $("#btLimparListaReproducao").show();
    $("#divAddPlaylist").show();
    $("#btAdicionarBiblioteca").show();
    $(".playlistControl").show();
    
    //Marca o item clicado
    $("#lnkListaReproducao").addClass("selected");
    LoadSongs();

}

// Verifica se o player ja esta aberto e abre em fullscreen caso nao esteja
function OpenPlayer() {
    // Verifica se o player esta aberto
    jQuery.get('/Player/ajax/PlayerOpened.aspx', function (data) {
        if (data != 1) {
            var left = (screen.width - 1024) / 2;
            var newwindow = window.open('/Player/Default.aspx', 'player', 'left=' + left + ',height=' + (screen.height - 100) + ',width=1024');
            if (newwindow) { newwindow.focus(); }    
        }
    });            
}

// Acoes dos botoes na pagina de tocar e adicionar na lista de reproducao
function ActionButtons() {

    jQuery("#btnAddQueue").click(function () {
        var id = GetSongsToPlayQueue();
        AddToQueue(id.toString(), 0);
        OpenPlayer();
        return false;
    });

    jQuery("#btnPlayAll").click(function () {        
        //OpenPlayer();
        var left = (screen.width - 1024) / 2;
        var newwindow = window.open('/Player/Default.aspx', 'player', 'left=' + left + ',height=' + (screen.height - 100) + ',width=1024');
        if (newwindow) {
            newwindow.focus();
            var id = GetSongsToPlayQueue();
            AddToQueue(id.toString(), 1);
            return false; 
        }
    });

    jQuery(".minorPlay .addListButton, .mcontrol .ListBtnArt").click(function () {
        var id = jQuery(this).attr("rel");
        AddToQueue(id.toString(), 0);
        OpenPlayer();        
        return false;
    });

    jQuery(".minorPlay .playButton, .mcontrol .playMusicArt, .listaItens .play").click(function () {        
        //OpenPlayer();
        var left = (screen.width - 1024) / 2;
        var newwindow = window.open('/Player/Default.aspx', 'player', 'left=' + left + ',height=' + (screen.height - 100) + ',width=1024');
        if (newwindow) {
            newwindow.focus();
            var id = jQuery(this).attr("rel");
            AddToQueue(id.toString(), 1);
            return false; 
        }
    });

}

function GetSongsToPlayQueue() {
    var songs = jQuery(".minorPlay .playButton");
    var id = [];
    for (var i = 0; i < songs.length; i++) {
        id.push(jQuery(songs[i]).attr("rel"));
    }
    return id;
}
