/* Copyright 2003-2008 Emergent Music LLC  All rights reserved.
 * $Id$
 */
 
FLYFI.MAX_JSON_RECOMMENDED_TRACKS = 20;
FLYFI.RECSREQUESTED_DELAYMSEC = 3000;   // if server not ready with recs, wait this long and try again

FLYFI.current_playerTrackDicts_lastMatchTS = null; // set to TS so we know whether to update
FLYFI.current_playerTrackDicts = [];
FLYFI.current_recCount = 0; // number of recommendations showing in the list - should be 0 to FLYFI.MAX_JSON_RECOMMENDED_TRACKS
                            // don't compute this on the fly since the list may be reset when new items are added, returning a bad number

FLYFI.current_playerTrackCells = null;

FLYFI.playerTracks_orderBy = null;
FLYFI.playerTracks_paging = new FLYFI.Paging(0); // For now we do not have paging in the brown player - show all tracks

FLYFI.playerTracks_trackIDJustAdded = null; // when a track has been added, remember it's id here so we can scroll to it after we get the new list from the server

FLYFI.requestedRecs_libraryID = null; // set when recs have been requested from the servers so that we don't start more than one request

FLYFI.scrollExtraInList = 4 * 22;   // show four lines at the bottom when scrolling

FLYFI.playerTracks_haveFree = function() {
    // return whether there is a free track in the current list
    if (FLYFI.current_playerTrackDicts.length === 0) {
        return false;
    }
    
    var l = FLYFI.current_playerTrackDicts.length;
    for (var i = 0; i < l; ++i) {
        if (FLYFI.current_playerTrackDicts[i].free) {
            return true;
        }
    }
    return false;
};

FLYFI.removePlayerTrackDict = function (trackID, tracks) {
    if (!tracks) {
        tracks = FLYFI.current_playerTrackDicts;
    }
    var l = tracks.length;
    for (var i = 0; i < l; ++i) {
        if (tracks[i].trackID == trackID) {
            if (!tracks[i].approved) {
                FLYFI.current_recCount -= 1;
            }
            tracks.splice(i, 1);
            break;
        }
    }
    // FLYFI.setCurrentRecCount(); - avoid looping through the array twice - just decrement the count locally.
};
FLYFI.removePlayerContestEntryDict = function (contestEntryID, tracks) {
    if (!tracks) {
        tracks = FLYFI.current_playerTrackDicts;
    }
    var l = tracks.length;
    for (var i = 0; i < l; ++i) {
        if (tracks[i].contestEntryID == contestEntryID) {
            if (!tracks[i].approved) {
                FLYFI.current_recCount -= 1;
            }
            tracks.splice(i, 1);
            break;
        }
    }
    // FLYFI.setCurrentRecCount(); - avoid looping through the array twice - just decrement the count locally.
};

FLYFI.removeUnapprovedPlayerTrackDicts = function (tracks, removeWidgets) {
    if (!tracks) {
        tracks = FLYFI.current_playerTrackDicts;
    }
    var l = tracks.length;
    for (var i = l - 1; i >= 0; --i) {
        if (!tracks[i].approved) {
            if (removeWidgets) {
                tracks[i].widget.remove();
            }
            tracks.splice(i, 1);
        }
    }
    FLYFI.current_recCount = 0;
};

FLYFI.approveAndMovePlayerTrackDict = function (trackID, tracks) {
    if (!tracks) {
        tracks = FLYFI.current_playerTrackDicts;
    }
    var lastApproved = null;
    var l = tracks.length;
    for (var i = 0; i < l; ++i) {
        if (tracks[i].approved) {
            lastApproved = i;
        }
        
        var next = tracks[i];
        if (next.trackID == trackID) {
            next.approved = true;
            if (!lastApproved) {
                if (i !== 0) {
                    tracks.splice(i, 1);
                    tracks.splice(0, 0, next);
                    break;
                }
            } else {
                if (lastApproved + 1 != i) {
                    tracks.splice(i, 1);
                    tracks.splice(lastApproved ? lastApproved + 1 : 0, 0, next);
                    break;
                }
            }
        }
    }
    FLYFI.setCurrentRecCount(tracks);
};


FLYFI.clearPlayerTracks = function() {
    // a new library is being shown, so clear and hide the tracks
    $('#player_shell .playlist_container .tracklist').empty();
    FLYFI.processResponse_LibraryTracks({'totalAvailable': null, 'tracks': [], 'reccommendationsRequested': false}, false);
    if (FLYFI.playerControls) {
        FLYFI.playerControls.clearTrackDictsAndWidgets();
    }
};

FLYFI.addToKeepers = function(trackID) {
    FLYFI.ensureCloud(function() {
                    FLYFI.callback_addToKeepers(trackID);
                });
};

// Server calls

FLYFI.onServer_LibraryTracks = function(result, libraryID, append) {
    FLYFI.processResponse_LibraryTracks(result, append);
    FLYFI.isRefreshingCloud = false;
    if (result.reccommendationsRequested && (FLYFI.current_recCount < FLYFI.MAX_JSON_RECOMMENDED_TRACKS)) { 
        // don't have enough recommendations and more are pending, so set a timer to get them
       setTimeout("FLYFI.ensureEnoughRecs(" + libraryID + ", true)", FLYFI.RECSREQUESTED_DELAYMSEC);
    } else {
        FLYFI.requestedRecs_libraryID = null;    
    }
};

FLYFI.processResponse_LibraryTracks = function(result, append) { // NYI: user can change libraries while this is processing - need mutex!
    // process tracks returned by the server
    // if (append) then add them to the end, else replace the whole list
    FLYFI.playerTracks_paging.available = result.totalAvailable;
    if (FLYFI.playerTracks_paging.available === null) {
        FLYFI.playerTracks_paging.clear();
        FLYFI.current_playerTrackDicts = [];
        FLYFI.setCurrentRecCount();
        FLYFI.current_playerTrackDicts_lastMatchTS = null;
    } else if (!append && FLYFI.current_playerTrackDicts_lastMatchTS &&
                (FLYFI.current_playerTrackDicts_lastMatchTS == result.last_match_ts)) {
        return; // same tracks we already have so don't update again
    } else {
        if (append) {
            FLYFI.current_playerTrackDicts = FLYFI.current_playerTrackDicts.concat(result.tracks);
            FLYFI.setCurrentRecCount();
            FLYFI.playerTracks_appended(result.tracks.length);
        } else {
            FLYFI.current_playerTrackDicts = result.tracks;
            FLYFI.setCurrentRecCount();
            FLYFI.playerTracks_updated();
            if (FLYFI.isContestCreation() && FLYFI.initialContestEntryID) {
                FLYFI.selectContestEntry(FLYFI.initialContestEntryID);
            } else if (FLYFI.isContestCreation() && FLYFI.contestEntryErrors) { // error in a new entry
                FLYFI.contestCreation_showEntryForm();
            } else {
                var firstCell = null;
                var firstTrackID = null;
                if (FLYFI.currentPlaylistDict) {
                    firstTrackID = FLYFI.preferences.getTrackForLibrary(FLYFI.currentPlaylistDict.libraryID);
                    if (firstTrackID) {
                        firstCell = $('#player_shell .playlist_container .tracklist .track-' + firstTrackID);
                    }
                }
                if (firstCell === null) {
                    firstCell = $('#player_shell .playlist_container .tracklist .trackcell:first');
                    if (firstCell.hasClass('rec_divider')) {
                        firstCell = firstCell.next();
                    }
                }
                if (firstCell.length > 0) {
                    if (!FLYFI.playingTrack.playing && FLYFI.subsequentLibrarySelected && !FLYFI.isWidgetCreationPage() && !FLYFI.isContest()) {
                        firstCell.click(); // if no track playing, play it
                    } else {
                        FLYFI.addTrackClassExclusive(firstCell, 'activetrack');
                        if (FLYFI.playerControls) {
                            var firstTrackDict = firstCell && firstTrackID ? FLYFI.playerControls.trackDictForID(firstTrackID) : null;
                            if (firstTrackDict) {
                                FLYFI.playerControls.selectTrack(firstTrackDict);
                            } else if (FLYFI.contestEntryEdited) {
                                FLYFI.contestCreation_showEntryForm(firstTrackDict);  // data and errors are already there - just show them
                            } else {
                                FLYFI.playerControls.selectFirstTrack();
                            }
                        }
                    }
                    FLYFI.scrollListToRow(firstCell.parent('.tracklist'), firstCell, FLYFI.scrollExtraInList);
                } else if (FLYFI.contestEntryEdited) {
                    FLYFI.contestCreation_showEntryForm();  // data and errors are already there - just show them
                } else {
                    FLYFI.playerControls.selectFirstTrack(); // no track, but need to clear it
                }
            }
            FLYFI.subsequentLibrarySelected = true;
        }
        FLYFI.current_playerTrackDicts_lastMatchTS = result.last_match_ts;
        FLYFI.playerTracks_paging.setItemsShown(FLYFI.current_playerTrackDicts.length);
    }
};
FLYFI.onServerError_LibraryTracks = function(request, textStatus, errorThrown) {
    FLYFI.showJSONError(request, textStatus, errorThrown);
};

FLYFI.callback_addToKeepers = function(trackID) { // define it out here so that my_currentLibraryDict is not evaluated until the callback is made
    if (FLYFI.currentPlaylistDict) { // user may have deleted the library
        FLYFI.get_NoResponse("/library/" + FLYFI.currentPlaylistDict.libraryID + "/json/playedtoend/track/" + trackID + "/sourcelibrary/" + FLYFI.currentPlaylistDict.libraryID  + "/",
            null, // nothing to do on success 
            FLYFI.showJSONError);
    }
};
         
FLYFI.shouldShowTrackInPlayerTracks = function(trackDict) {
    if (FLYFI.isContest()) {
        return true;    // always show all contest entries
    }
    
    if (trackDict.free) { // show free track only if enabled
        return FLYFI.filter_showTracks_Free;
    } else {
        return FLYFI.filter_showTracks_YouTube;    
    }
    
    // obsolete - the server does not give us YouTubeIDs since it takes too long - may eventually restore this if we can know
    if (trackDict.videoYouTubeIDs && trackDict.videoYouTubeIDs.length > 0) { // show YouTube track only if enabled
        return FLYFI.filter_showTracks_YouTube;
    } else {
        return FLYFI.filter_showTracks_Other; // show non-YouTube track only if enabled
    }
};

FLYFI.playerTracks_updated = function() {
    var list = $('#player_shell .playlist_container .tracklist');
    var newList = list.clone(true);
    newList.empty();
    
    if (!FLYFI.currentPlaylistDict) { // user may have deleted the library
        return;
    }
    
    var oldList = null;
    
    if (FLYFI.current_playerTrackDicts) {
        FLYFI.current_playerTrackCells = [];
        var l = FLYFI.current_playerTrackDicts.length;
        var dividerShown = false;
        var prevTrack = null;
        for (var i = 0; i < l; ++i) {
            var trackDict = FLYFI.current_playerTrackDicts[i];
            if (FLYFI.shouldShowTrackInPlayerTracks(trackDict)) {
                if (FLYFI.playerControls && FLYFI.playerControls.newPlayer && !trackDict.approved && (!prevTrack || prevTrack.approved)) {
                    newList.append(FLYFI.RecDivider_widgetCallback(FLYFI.playerControls.playlistDict));
                    dividerShown = true;
                }
                var cell = new FLYFI.PlayerTrackCell(trackDict, FLYFI.currentPlaylistDict.writable, FLYFI.playerControls);
                FLYFI.current_playerTrackCells[i] = cell;
                newList.append(cell.html());
                prevTrack = trackDict;
            }
        }
        if (FLYFI.playerControls && FLYFI.playerControls.newPlayer && FLYFI.playerControls.playlistDict.writable && !dividerShown) {
            newList.append(FLYFI.RecDivider_widgetCallback(FLYFI.playerControls.playlistDict));
        }
        oldList = list.replaceWith(newList);
        oldList = null;
        
        if (FLYFI.playerTracks_trackIDJustAdded) {
            var row = list.find('.track-' + FLYFI.playerTracks_trackIDJustAdded);
            FLYFI.scrollListToRow(list, row, FLYFI.scrollExtraInList);
            FLYFI.playerTracks_trackIDJustAdded = null;
        }
        
        list = $('#player_shell .playlist_container .tracklist'); // jQuery needs us to get it again since the list was changed 
        list.find('.approved:last').addClass('last');
        FLYFI.enableSortingOfCurrentLibrary(list);
    } else {
        oldList = list.replaceWith(newList);
        oldList = null;
        if (FLYFI.playerControls) {
            FLYFI.playerControls.clear();
        }
    }
};

FLYFI.playerTracks_appended = function(count) {
    var playerTracks = $('#player_shell .playlist_container .tracklist');
    if (!FLYFI.currentPlaylistDict) { // user may have deleted the library
        return;
    }
    
    for (var i = 0; i < count; ++i) {
        var index = FLYFI.current_playerTrackDicts.length - count + i;
        var trackDict = FLYFI.current_playerTrackDicts[index];
        if (FLYFI.shouldShowTrackInPlayerTracks(trackDict)) {
            var cell = new FLYFI.PlayerTrackCell(trackDict, FLYFI.currentPlaylistDict.writable, FLYFI.playerControls);
            FLYFI.current_playerTrackCells[index] = cell;
            playerTracks.append(cell.html());
        }
    }
    playerTracks.find('.approved').removeClass('last');
    playerTracks.find('.approved:last').addClass('last');
    FLYFI.enableSortingOfCurrentLibrary(playerTracks);
};

FLYFI.enableSortingOfCurrentLibrary = function(list) {
    if (FLYFI.currentPlaylistDict && FLYFI.isMyPlaylist(FLYFI.currentPlaylistDict.libraryID) &&
        (!FLYFI.isContest() || FLYFI.isContestCreation())) { // no reordering on contest pages (unless creating a contest)
        list.sortable({ axis: 'y',
                        update: FLYFI.onSortUpdate_playerTracks
                    });
    }
};

FLYFI.onSortUpdate_playerTracks = function(event, ui) {
    if (!FLYFI.currentPlaylistDict) { // user may have deleted the library
        return;
    }
    var libraryID = FLYFI.currentPlaylistDict.libraryID;
    
    var tracks = ui.item.parents('.ui-sortable').find('.trackcell:not(.ui-sortable-helper)');       

    var trackIDs = [];
    var l = tracks.length;
    for (var i = 0; i < l; ++i) {
        var track = tracks.eq(i);

        // collect the new order
        trackIDs.push(FLYFI.trackIDFromWidget(track));
    }
    
    // send the new order to the server
    FLYFI.server_updateTrackOrder(libraryID, trackIDs);
};

FLYFI.getPlayerTrackCell = function(trackID) {
    var l = FLYFI.current_playerTrackCells.length;
    for (var i = 0; i < l; ++i) {
        var cell = FLYFI.current_playerTrackCells[i];
        if (cell.trackDict.trackID == trackID) {
            return cell;
        }
    }
    return null;
};

// Sorting

FLYFI.send_update_playerTracks_OrderToServer = function() {
    if (!FLYFI.currentPlaylistDict) { // user may have deleted the library
        return;
    }
    var libraryID = FLYFI.currentPlaylistDict.libraryID;

    var tracks = $('#playlist .track');
    
    var idArray = [];
    var l = tracks.length;
    for (var i = 0; i < l; ++i) {
        idArray.push(FLYFI.trackIDFromWidget(tracks.eq(i)));
    }
    var ids = idArray.join(",");
    FLYFI.post_NoResponse('/library/' + libraryID + '/json/update_track_order_from_ids/', 
                            { ordered_tracks: ids }
                        );
};

FLYFI.onStop_SortableKeepers = function() {
    $(this).css('top', '0px'); // jquery misplaces item, so put it back
    $(this).css('left', '0px');
    
    FLYFI.send_update_playerTracks_OrderToServer();
    $('#playlist').updateRanks();
};

// Notifications

FLYFI.update_playerTracks = function(callback) {
    if (!FLYFI.currentPlaylistDict || (!FLYFI.currentPlaylistDict.libraryID && !FLYFI.currentPlaylistDict.contestCategoryID)) {
        FLYFI.current_playerTrackDicts = [];
        FLYFI.setCurrentRecCount();
        FLYFI.current_playerTrackDicts_lastMatchTS = null;
        FLYFI.playerTracks_updated();
    } else {
        var libraryID = FLYFI.currentPlaylistDict.libraryID;
        if (FLYFI.currentPlaylistDict.iscloud) {
            var url = ['/library/'];
            url.push(libraryID.toString());
            url.push('/json/cloud_tracks/');
            FLYFI.getJSONWithSpinner(url.join(''), 
                                    '#player_shell .playlist_container .spinner',
                                    function(result) { 
                                                        FLYFI.onServer_LibraryTracks(result, libraryID, false); 
                                                        if (callback) { callback(); }
                                                    },
                                    FLYFI.onServerError_LibraryTracks);
        } else {
            if (FLYFI.currentPlaylistDict.contestCategoryID) {
                FLYFI.server.contestCategoryTracks(FLYFI.currentPlaylistDict.contestCategoryID, 
                                    '#player_shell .playlist_container .spinner',
                                    function(result) { 
                                                    FLYFI.processResponse_LibraryTracks(result, false);
                                                        if (callback) { callback(); }
                                                    },
                                    FLYFI.onServerError_LibraryTracks);
            } else {
                FLYFI.server.libraryTracks(libraryID, FLYFI.playerTracks_orderBy, FLYFI.playerTracks_paging.start, FLYFI.playerTracks_paging.itemsToShow,
                                    '#player_shell .playlist_container .spinner',
                                    function(result) { 
                                                    FLYFI.onServer_LibraryTracks(result, libraryID, false); 
                                                        if (callback) { callback(); }
                                                    },
                                    FLYFI.onServerError_LibraryTracks);
            }
        }
    }
};

// Recs

FLYFI.setCurrentRecCount = function(tracks) {
    if (!tracks) {
        tracks = FLYFI.current_playerTrackDicts;
    }
    var recs = 0;
    var l = tracks.length;
    for (var i = 0; i < l; ++i) {
        if (!tracks[i].approved) {
            recs += 1;
        }
    }
    FLYFI.current_recCount = recs;
};
FLYFI.ensureEnoughRecs = function(libraryID, force) {
    if (!FLYFI.currentPlaylistDict || !FLYFI.currentPlaylistDict.writable ||
        libraryID != FLYFI.currentPlaylistDict.libraryID ||          /* user changed libraries - only the current one should ask for recs */
        (!force && libraryID == FLYFI.requestedRecs_libraryID)  /* already requesting recs for that library */
        ) { return; }  
    
    var needed = FLYFI.MAX_JSON_RECOMMENDED_TRACKS - FLYFI.current_recCount;
    if (needed <= 0) {
        return;
    }

    if (FLYFI.recsRequestWasSent && !force) {
        return; // Do not send overlapping calls
    } else {
        FLYFI.recsRequestWasSent = true;
    }
    
    FLYFI.requestedRecs_libraryID = libraryID;
    try {
        FLYFI.getJSONWithSpinner('/library/' + libraryID + '/json/cloud_tracks/approved_count/0/unapproved_start/' + FLYFI.current_recCount + '/unapproved_count/' + needed + '/', 
                                '#player_shell .playlist_container .spinner',
                                function(result) {
                                                FLYFI.recsRequestWasSent = false;
                                                if (FLYFI.isRefreshingCloud) {
                                                     // Do not override
                                                    return;
                                                }
                                                if (FLYFI.currentPlaylistDict) { // user may have deleted the library
                                                    FLYFI.onServer_LibraryTracks(result, libraryID, true); 
                                                }
                                            },
                                function(request, textStatus, errorThrown) {
                                                FLYFI.recsRequestWasSent = false;
                                                FLYFI.requestedRecs_libraryID = null; 
                                                FLYFI.onServerError_LibraryTracks(request, textStatus, errorThrown);
                                            });
    }
    catch(err) {
        FLYFI.recsRequestWasSent = false;
    }
};

// List filters controls

FLYFI.setControls_listfilter = function() {
    // Note: there are two sets of these controls - one for player and one in the interstitial dialog
    var parents = FLYFI.getCheckboxListFilterParents();
    FLYFI.setCheckBox(parents.find('.checkbox_listfilter_YouTube input'), FLYFI.filter_showTracks_YouTube);
    FLYFI.setCheckBox(parents.find('.checkbox_listfilter_Other input'), FLYFI.filter_showTracks_Other);
    FLYFI.setCheckBox(parents.find('.checkbox_listfilter_Free input'), FLYFI.filter_showTracks_Free);
};

FLYFI.onClickCheckBox_listfilter = function(event) {
    // Note: there are two sets of these controls - one for coldstart and one for not coldstart

    // the #player_shell controls are the master controls - the dialog just follows along
    var wantYouTube = $('#player_shell .checkbox_listfilter_YouTube input:checked').length > 0;
    var wantOther = $('#player_shell .checkbox_listfilter_Other input:checked').length > 0;
    var wantFree = $('#player_shell .checkbox_listfilter_Free input:checked').length > 0;
    
    FLYFI.updateListFilterControls(wantYouTube, wantOther, wantFree);
};

FLYFI.updateListFilterControls = function(wantYouTube, wantOther, wantFree) {
    // force the controls to the supplied values
    var needUpdate = false;
    
    if (FLYFI.filter_showTracks_YouTube != wantYouTube) {
        FLYFI.filter_showTracks_YouTube = wantYouTube;
        FLYFI.preferences.setBoolean('showTracks_YouTube', FLYFI.filter_showTracks_YouTube);
        needUpdate = true;
    }
    if (FLYFI.filter_showTracks_Other != wantOther) {
        FLYFI.filter_showTracks_Other = wantOther;
        FLYFI.preferences.setBoolean('showTracks_Other', FLYFI.filter_showTracks_Other);
        needUpdate = true;
    }
    if (FLYFI.filter_showTracks_Free != wantFree) {
        FLYFI.filter_showTracks_Free = wantFree;
        FLYFI.preferences.setBoolean('showTracks_Free', FLYFI.filter_showTracks_Free);
        needUpdate = true;
    }
        
    FLYFI.setControls_listfilter();

    if (needUpdate) {
        FLYFI.playerTracks_updated();
    }
};

FLYFI.onClickCheckBox_listfilter_YouTube_Text = function(event) {
    $('#player_shell .checkbox_listfilter_YouTube input').click();
    FLYFI.onClickCheckBox_listfilter();
}; 

FLYFI.onClickCheckBox_listfilter_Other_Text = function(event) {
    $('#player_shell .checkbox_listfilter_Other input').click();
    FLYFI.onClickCheckBox_listfilter();
}; 

FLYFI.onClickCheckBox_listfilter_Free_Text = function(event) {
    $('#player_shell .checkbox_listfilter_Free input').click();
    FLYFI.onClickCheckBox_listfilter();
}; 

FLYFI.temp_listfilter = function() {
    // Temporarily (meaning just for the current page) set the list to show free and video tracks - used by Custom Radio
    if (FLYFI.filter_showTracks_YouTube || FLYFI.filter_showTracks_Other || !FLYFI.filter_showTracks_Free) {
        FLYFI.filter_showTracks_YouTube = true;
        FLYFI.filter_showTracks_Other = false;
        FLYFI.filter_showTracks_Free = true;
        FLYFI.playerTracks_updated();
    }
}; 

FLYFI.setClick_checkboxListFilter_Input = function(parent) {
    parent.find('.checkbox_listfilter_YouTube input').click(FLYFI.onClickCheckBox_listfilter_YouTube_Text);
    parent.find('.checkbox_listfilter_Free input').click(FLYFI.onClickCheckBox_listfilter_Free_Text);
};

FLYFI.setClick_checkboxListFilter_Label = function(parent) {
    parent.find('.checkbox_listfilter_YouTube .checkboxlabel').click(FLYFI.onClickCheckBox_listfilter_YouTube_Text);  
    parent.find('.checkbox_listfilter_Other .checkboxlabel').click(FLYFI.onClickCheckBox_listfilter_Other_Text);
    parent.find('.checkbox_listfilter_Free .checkboxlabel').click(FLYFI.onClickCheckBox_listfilter_Free_Text);
};

FLYFI.setListFilter_YouTube = function() {
    FLYFI.filter_showTracks_YouTube = true;
    FLYFI.filter_showTracks_Other = false;
    FLYFI.filter_showTracks_Free = false;
};

FLYFI.getInterstitialForms = function() {
    return $('#home_votedown_interstitial_form, #interstitial_form');
};

FLYFI.getCheckboxListFilterParents = function() {
    return $('#home_votedown_interstitial_form, #interstitial_form, #player_shell');
};

$(document).ready(function() {
    if (!FLYFI.isLikeIPhone()) {
        FLYFI.filter_showTracks_YouTube = FLYFI.preferences.getBoolean('showTracks_YouTube', true);    // include non-free tracks playable at YouTube in the list?
        FLYFI.filter_showTracks_Other = FLYFI.preferences.getBoolean('showTracks_Other', false);     // include non-free tracks not playable at YouTube in the list?
        FLYFI.filter_showTracks_Free = FLYFI.preferences.getBoolean('showTracks_Free', true);       // include free tracks in the list?
    } else {
        // iPhone can only play free tracks
        FLYFI.filter_showTracks_YouTube = false; 
        FLYFI.filter_showTracks_Other = false;
        FLYFI.filter_showTracks_Free = true;
    }
    
    // Note: these track controls are both in the dialogs and in the page.  The ones in the
    // dialogs just set the other, which are the ones that control the output.  Optimize to
    // use ID searches, not class searches
    var interstitialForms = FLYFI.getInterstitialForms();
    var playerShell = $('#player_shell');
    FLYFI.setClick_checkboxListFilter_Input(interstitialForms);
    FLYFI.setClick_checkboxListFilter_Label(interstitialForms);
    FLYFI.setClick_checkboxListFilter_Label(playerShell);
    
    playerShell.find('.checkbox_listfilter_YouTube input, .checkbox_listfilter_Other input, .checkbox_listfilter_Free input').click(FLYFI.onClickCheckBox_listfilter);
    
    if (FLYFI.isCustomRadioPlayer()) {   // force the lists in Custom Radio to show only free tracks
        FLYFI.temp_listfilter();
    } 
    FLYFI.setControls_listfilter();
    FLYFI.subsequentLibrarySelected = false;
});


