/**
 * playlist Javascript
 * 
 * @author: Chanel Munezero <chanel.munezero@escapemg.com>
 */
(function(){
    if(!window.gs) {
        return;
    }
    
    var playlist = window.gs.playlist = {
        // default options/settings
        playlist: 0,
        sortContainer: null,
        saveTimeout: null,
        pageUrl: '/add_songs.php',
        
        empty: null
    };
    
    playlist.init = function(pla)
    {
        pla = pla || "ul.playlist.songs";
        playlist.sortContainer = $(pla).sortable({
            axis: 'y',
            handle: '.move',
            containment: 'parent',
            change: function() {
                gs.widget.refreshPreview();
            }
        });
        if($('#songCount').length) {
            if(parseInt($('#songCount').text()) <= 0 ) {
                $("#widgetButtonSubmit").css('opacity', 0.5)
            }
        }
        if($('#singleHasSongs').val()=='1') {
            $('#singleWidgetButtonSubmit').removeAttr('disabled').css('opacity', 1);
        } else {
            $('#singleWidgetButtonSubmit').attr('disabled', 'true').css('opacity', .5);
        }
        if($('#playlistDecide').length) {
            gs.playlist.showDecide();
        }
    };
    
    playlist.showDecide = function()
    {
        var options = {
            onHide: function(hash) {
                gs.widget.showPreviews();
                gs.modal_hide(hash);
            },
            onShow: function(hash) {
                gs.widget.hidePreviews();
                $(hash.w).append($('#playlistDecide'));
                gs.modal_show(hash);
            }
        }
        var divinfo = {
            newid: 'playDecide',
            newclass: 'modalbox'
        };
        gs.lbFactory.newModalBox(options, divinfo, true);
    }
    
    playlist.addSong = function(songID, isProcessing)
    {
        if(songID) {
            isProcessing = isProcessing || false;
            isProcessing = (isProcessing) ? '1' : '0';
            // get new playlist song row
            $.getJSON(playlist.pageUrl+'?action=add&songs='+songID+'&isProcessing='+isProcessing+'&widgetid='+gs.widget.widgetid, gs.playlist.addMusicCallback);
        }
    };
    
    playlist.addFile = function(fileID, isProcessing, info)
    {
        if(info && info.fileID) {
            fileID = fileID || info.fileID;
        }
        debug('fileid: ',fileID);
        if(fileID) {
            isProcessing = isProcessing || false;
            isProcessing = (isProcessing) ? '1' : '0';
            // get new playlist song row
            $.getJSON(playlist.pageUrl+'?action=add&files='+fileID+'&isProcessing='+isProcessing+'&widgetid='+gs.widget.widgetid, gs.playlist.addMusicCallback);
        }
    };
    
    playlist.addMusic = function(type, id, isProcessing)
    {
        if(id) {
            isProcessing = isProcessing || false;
            isProcessing = (isProcessing) ? '1' : '0';
            if(id && id.join) {
                // handle arrays
                id = id.join(',');
            }
            if(type=='playlist') {
                var params = 'playlist='+id;
            } else {
                var params = 'songs='+id;
            }
            params += '&widgetid='+gs.widget.widgetid;
            if($('#sr-'+id).parents('#songResults.singleSong').length) {
                if($('#sr-'+id).get(0).className.match('added')) {
                    if(window.player && window.player.songID && window.player.songID == id) {
                        player.stopStream();
                    }
                    var widgetID = $('#singleWidgetID').val();
                    $.post('add_songs.php?action=remove&widgetid='+gs.widget.widgetid+'&songs='+id);
                    $('#sr-'+id).removeClass('added');
                    $('#singleWidgetButtonSubmit').attr('disabled', 'true').css('opacity', .5);
                    return false;
                }
                params += '&type=1';
            }
            // get new playlist song row
            $.getJSON(playlist.pageUrl+'?action=add&'+params+'&isProcessing='+isProcessing, gs.playlist.addMusicCallback);
        }
    };
    
    playlist.addMusicCallback = function(json)
    {
        debug('addMusicCallback, json:',json);
        if(json.Custom && json.Custom.html) {
            $(playlist.sortContainer).append(json.Custom.html);
            $(playlist.sortContainer).sortable('refresh');
            $(playlist.sortContainer).parent().parent().show();
            debug('sortContainer', playlist.sortContainer);
            
            var numSongs = (json.Custom && json.Custom.numsongs) ? json.Custom.numsongs : 1;
            playlist.changeSongCount(numSongs);
            $('#playlistContainer').show();
            
            // make sure this is single song, then highlight row
            if($('#theme-0,#theme-1').filter(':visible').is('.singleSong')) {
                $('#sr-'+json.Custom.id).addClass('added').siblings().removeClass('added');
                $('#singleWidgetButtonSubmit').removeAttr('disabled').css('opacity', 1);
                debug("refresh single widget");
                gs.widget.refreshSinglePreview();
            } else {
                debug('refresh reg widget');
                gs.widget.refreshPreview();
            }
        } else {
            // error
            debug('search error');
            $('#searchError').html('Could not add song to playlist.').show();
        }
    }
    
    playlist.genreAddSong = function(obj, songID)
    {
        $(obj).parent().toggleClass('added');
        if($(obj).parent().parent().children('.added').length) {
            $('#genreSubmit').css('opacity', 1.0);
        } else {
            $('#genreSubmit').css('opacity', 0.5);
        }
    }
    
    playlist.submitSongs = function(obj)
    {
        var songs = [];
        $(obj).parent().siblings('.results').children('.added').each(function() {
            songs.push(this.id.split("-")[1]);
        });
        debug(songs);
        gs.playlist.addMusic('song',songs);
        $(obj).siblings('.close').click();
    }
    
    playlist.removeSong = function(obj, songID, isFile)
    {
        if(window.player && window.player.songID && window.player.songID == songID) {
            player.stopStream();
        }
        
        var widgetID = $('#playlistWidgetID').val();
        songID = (isFile) ? 'f'+songID : songID;
        $.post('/add_songs.php?action=remove&widgetid='+gs.widget.widgetid+'&songs='+songID)
        $(obj).parents('li.song').remove();
        $(playlist.sortContainer).sortable('refresh');
        playlist.changeSongCount(-1);
    };
    
    playlist.removePlaylist = function(obj, playlistID)
    {
        $(obj).parent().remove();
        $(playlist.sortContainer).sortable('refresh');
        playlist.changeSongCount(-1);
    };
    
    playlist.closePage = function()
    {
        clearTimeout(gs.playlist.saveTimeout);
        window.close();
    }
    
    playlist.save = function()
    {
        var songIDs = playlist.getSongIDs();
        var songs = songIDs.join(',');
        $.postJSON('/add_songs?action=save&songs='+songs+'&widgetid='+gs.widget.widgetid, function(json) {
            debug(json);
            //$("#header .isSaved,#footer .isSaved").show();
            ///*
            var options = {
                ajax: '/add_songs?action=lb',
                onHide: function(hash) {
                    gs.widget.showPreviews();
                    gs.modal_hide(hash);
                },
                onShow: function(hash) {
                    gs.widget.hidePreviews();
                    gs.modal_show(hash);
                }
            };
            var divinfo = {
                newid: 'plaSave',
                newclass: 'modalbox'
            };
            gs.lbFactory.newModalBox(options, divinfo, true);
        });
    }
    
    playlist.toggleSongs = function(obj, clickObj)
    {
        $(obj).children().toggle();
        $(clickObj).parent().parent().toggleClass('open');
    }
    
    playlist.getSongIDs = function()
    {
        var container = $('ul.playlist.songs');
        if(!container.length) {
            container = $('#widgetPlaylist');
        }
        var song = $(container).get(0).firstChild;
        var sort = [];
        if(song.nodeType!=3) {
            sort.push(song.id.split("-")[1]);
        }
        while(song = song.nextSibling) {
            if(song.nodeType==3){continue;}
            sort.push(song.id.split("-")[1]);
        }
        return sort;
    }
    
    playlist.changeSongCount = function(dif)
    {
        var curCount = parseInt($("#songCount").html()) + parseInt(dif);
        $("#songCount").html(''+curCount);
        if(curCount>0) {
            $("#widgetButtonSubmit").css('opacity', 1.0);
        } else {
            $("#widgetButtonSubmit").css('opacity', 0.5);
        }
    }
})();
