/* Copyright 2003-2008 Emergent Music LLC  All rights reserved.
 * $Id$
 */

/* mylibraries.js
    Handle the lists of libraries for the current user. 
    Created from clouds.js and myclouds.js when we went to flyfi.com
*/

FLYFI.libraryDicts_MyClouds = []; 
FLYFI.libraryDicts_MyPlaylists = []; 
FLYFI.libraryDicts_MyExternalPlaylists = []; 
FLYFI.libraryDicts_MostsPlaylists = []; 
FLYFI.customRadioLibraries = [];            // index is the libraryID, and the value is whether to include in the radio
FLYFI.customRadioLibraries_Prefabs = [];   // index is the libraryID, and the value is whether to include in the radio
FLYFI.customRadioLibraries_RequiredPrefabLibaryIDs = [];    // libraryIDs for prefabs that are required in a custom radio

FLYFI.loadedInitialLibraries = false;
FLYFI.currentPlaylistDict = null;  // the library or contest category currently selected

FLYFI.libraryIDFromWidget = function(widget) {
    return FLYFI.IDFromWidget('library-', widget);
};

FLYFI.contestCategoryIDFromWidget = function(widget) {
    return FLYFI.IDFromWidget('category-', widget);
};

FLYFI.contestEntryIDFromWidget = function(widget) {
    return FLYFI.IDFromWidget('contestEntry-', widget);
};

FLYFI.sameItem = function(itemDict1, itemDict2) {
    // return whether the two dicts refer to the same item
    return ( (!itemDict1 &&               (itemDict1 == itemDict2)) ||
             (itemDict1.trackID &&        (itemDict1.trackID == itemDict2.trackID)) ||
             (itemDict1.contestEntryID && (itemDict1.contestEntryID == itemDict2.contestEntryID)) 
           );
};

FLYFI.onServer_ListMine = function(result, resetCurrentLibrary) {
    FLYFI.libraryDicts_MyClouds = result.clouds; 
    FLYFI.libraryDicts_MyPlaylists = result.my_playlists;
    FLYFI.libraryDicts_MyExternalPlaylists = result.external_playlists;
    FLYFI.libraryDicts_MostsPlaylists = result.most_playlists;
    if (!FLYFI.playerControls) { // Some pages without a brown player need the library list anyway.
        return;
    }

    FLYFI.redisplayMyCloudList();

    var lastLibraryID = null;
    if ((!FLYFI.isContest() || FLYFI.isContestCreation()) && result && result.last_library) { // first contest is set in FLYFI._redisplayContestCategoryList
        lastLibraryID = result.last_library.libraryID;
    }

    if (resetCurrentLibrary && !FLYFI.isContestCreation()) {
        FLYFI.selectLibraryByID(lastLibraryID);
    }
    FLYFI.setIfPostStart();
};

FLYFI.onClick_Playlist = function(event) {
    event.preventDefault();
    var libraryID = $(this).attr('libraryid');
    if (libraryID) {
        FLYFI.selectLibraryByID(libraryID);
    } else {
        var categoryWidget = $(this).parent('.contestcategory');
        var contestCategoryID = FLYFI.contestCategoryIDFromWidget(categoryWidget);
        FLYFI.selectCategoryByID(contestCategoryID);
    }
	FLYFI.trackAjaxCall("selectLibrary");
};

FLYFI.onClick_Delete = function(event, libraryTypeString, spinnerSelector, playlistDicts, itemSelector) {
    event.preventDefault();
    event.stopPropagation();
    
    var target = $(event.target);
    
    var a = target.parents('a');
    var libraryID = a.attr('libraryid');
    var playlistDict = null;
    if (libraryID) {
        for (var i = 0; i < playlistDicts.length; ++i) {
            if (playlistDicts[i].libraryID == libraryID) {
                playlistDict = playlistDicts[i];
                break;
            }
        }
    } else {
        var w = target.parents('.contestcategory');
        var categoryID = FLYFI.contestCategoryIDFromWidget(w);
        for (var j = 0; j < playlistDicts.length; ++j) {
            if (playlistDicts[j].contestCategoryID == categoryID) {
                playlistDict = playlistDicts[j];
                break;
            }
        }
    }
    if (!playlistDict) {
        return;
    }
	var name = playlistDict.name;
    var prompt = playlistDict.isshared ?
                   "Are you sure you want to delete shared playlist '" + name + "'?  Since you created it, this will remove the playlist for all FlyFi Community Playlist users who are sharing it as well." 
                 : "Discard the " + libraryTypeString + " '" + name + "'?";
	if (!confirm(prompt)) {
		return;
	}

    if (playlistDict.libraryID) {
        FLYFI.server.deleteLibrary(playlistDict.libraryID, spinnerSelector, function() {}, FLYFI.showJSONError);
    } else {
        FLYFI.removeContestCategoryLocal(playlistDict.contestCategoryID);
        FLYFI.server.deleteContestCategory(playlistDict.contestCategoryID, spinnerSelector, function() {}, FLYFI.showJSONError);
    }

    var l = playlistDicts.length;
    for (var k = 0; k < l; ++k) {
        if (playlistDicts[k].libraryID == libraryID) {
            playlistDicts.splice(k, 1);
            break;
        }
    }
    FLYFI.setIfPostStart();

    var li = target.parents(itemSelector);
    var nextID;
    var next = li.next();
    if (next.length === 0) {
        next = li.siblings(':last');
        if (next.length === 0) {
            var groups = li.parents('.libraries');
            var others = groups.find('.grooveitems li');
            var olen = others.length;
            for (var o = 0; o < olen; ++o) {
                var other = others[o];
                if (li[0] != other) {
                    next = other;
                    break;
                }
            }
        }
    }
    if (next.length > 0) {
        if (FLYFI.isContestCreation()) {
            nextID = FLYFI.contestCategoryIDFromWidget(next);
        } else {
            nextID = next.find('a').attr('libraryid');
        }
    }
    li.remove();
    
    if (!FLYFI.currentPlaylistDict || FLYFI.currentPlaylistDict.libraryID == libraryID) {
        if (nextID) {
            if (FLYFI.isContestCreation()) {
                FLYFI.selectCategoryByID(nextID);
            } else {
                FLYFI.selectLibraryByID(nextID);
            }
        } else {
            FLYFI.setCurrentPlaylist(null);
        }
    }
    FLYFI.trackAjaxCall('deleteLibrary');
};
FLYFI.onClick_DeleteLibrary = function(event) {
    FLYFI.onClick_Delete(event, 'groove', '.grooves_spinner', FLYFI.libraryDicts_MyClouds, '.grooveitem');
        
};
FLYFI.onClick_DeletePlaylist = function(event) {
    if (FLYFI.isContestCreation()) {
        var playlists = FLYFI.getContestCategories(window.json_contest_category_dicts);
        FLYFI.onClick_Delete(event, 'contest category', '.playlists_spinner', playlists, '.playlistitem');
    } else {
        FLYFI.onClick_Delete(event, 'playlist', '.playlists_spinner', FLYFI.libraryDicts_MyPlaylists, '.playlistitem');
    }
};

FLYFI.showOrHideRecs = function(libraryDict) {
    FLYFI.post_NoResponse('/' + window.level + '/library/' + libraryDict.libraryID + '/json/' + (libraryDict.hide_recs ? 'hide/' : 'show/'), 
                                {}, 
                                libraryDict.showHideRecsCallback ? function() { libraryDict.showHideRecsCallback(libraryDict); } : null,
                                FLYFI.showJSONError);
};

FLYFI._filterLibraries = function(libraries, filter) {
	var filtered = [];
    var l = libraries.length;
	for (var i = 0; i < l; i++) {
		var library = libraries[i];
		if (filter(library)) {
			filtered.push(library);
		}
	}
	return filtered;
};

FLYFI.redisplayMyCloudList = function (){
    FLYFI._redisplayPlaylistList('#grooves', 'grooveitem', 
                                FLYFI._filterLibraries(FLYFI.libraryDicts_MyClouds, function(library) {return !library.isitunescloud && !library.isshared;}), 
                                FLYFI.onClick_Playlist, FLYFI.onClick_DeleteLibrary, Boolean(FLYFI.isCustomRadioPlayer()), FLYFI.customRadioLibraries, FLYFI.onClick_playlistCheckbox);
    FLYFI._redisplayPlaylistList('#sharedplaylists', 'grooveitem', 
                                FLYFI._filterLibraries(FLYFI.libraryDicts_MyClouds, function(library) {return library.isshared;}), 
                                FLYFI.onClick_Playlist, FLYFI.onClick_DeleteLibrary, Boolean(FLYFI.isCustomRadioPlayer()), FLYFI.customRadioLibraries, FLYFI.onClick_playlistCheckbox, true);
    FLYFI._redisplayPlaylistList('#itunesgrooves', 'grooveitem', 
                                FLYFI._filterLibraries(FLYFI.libraryDicts_MyClouds, function(library) {return library.isitunescloud;}), 
                                FLYFI.onClick_Playlist, FLYFI.onClick_DeleteLibrary, Boolean(FLYFI.isCustomRadioPlayer()), FLYFI.customRadioLibraries, FLYFI.onClick_playlistCheckbox, true);
                                
    var playlists = FLYFI.libraryDicts_MyPlaylists.concat(FLYFI.libraryDicts_MostsPlaylists);
    var orderedlist = FLYFI.customRadioLibraries;
    if (FLYFI.isContest() || FLYFI.isContestCreation()) {
        playlists = FLYFI.getContestCategories(window.json_contest_category_dicts);
        orderedlist = FLYFI.orderedContestCategoryIDsandIncludes(playlists);
    } 
    FLYFI._redisplayPlaylistList('#playlists', 'playlistitem', 
                                playlists, 
                                FLYFI.onClick_Playlist, FLYFI.onClick_DeletePlaylist, Boolean(FLYFI.isCustomRadioPlayer()), orderedlist, FLYFI.onClick_playlistCheckbox);
    if (FLYFI.isCustomRadioPlayer()) {
        $('#playlists .grooveitems').sortable({ axis: 'y',
                                                update: FLYFI.onSortUpdate_playlists
                                            });
    }
};

FLYFI._redisplayPlaylistList = function(parentSelector, newItemClass, playlistDicts, 
                                        onClickFunc, onClickDeleteFunc, showCheckboxes, 
                                        orderedIDsAndChecks, onClickCheckboxFunc, hideSectionIfEmpty) {    
    /* rebuild the list of playlists in parentSelector with items of newItemClass.  
        The data is in playlistDicts, but the order and whether to check the item are in orderedIDsAndChecks.
        Any libraries not in orderedIDsAndChecks are put at the end, unchecked. 
    */
    var parent = $(parentSelector);
    var list = parent.find('.grooveitems');
    var toggle = parent.find('.toggle');
    var newList = list.clone(true);
    var nextID = null;
    var includeInList = null;
    newList.empty();
    
    var idsNotYetShown = [];
    var l = playlistDicts.length;
    for (var x = 0; x < l; ++x) {
        if (playlistDicts[x].libraryID) {
            nextID = playlistDicts[x].libraryID;
        } else {
            nextID = playlistDicts[x].contestCategoryID;
        }
        idsNotYetShown.push(nextID);
    }

    if (orderedIDsAndChecks) {
        l = orderedIDsAndChecks.length;
        for (var i = 0; i < l; ++i) {
            nextID = orderedIDsAndChecks[i][0];
            includeInList = orderedIDsAndChecks[i][1];
            
            var widget = FLYFI.getPlaylistWidget(nextID, newItemClass, playlistDicts, onClickFunc, onClickDeleteFunc, showCheckboxes, includeInList, onClickCheckboxFunc);
            newList.append(widget);

            var ll = idsNotYetShown.length;
            for (var y = 0; y < ll; ++y) {
                if (idsNotYetShown[y] == nextID) {
                    idsNotYetShown.splice(y, 1);    // library found, so remove it from the pending list
                    break;
                }
            }
        }
    }
    
    l = idsNotYetShown.length;
    for (var j = 0; j < l; ++j) {
        nextID = idsNotYetShown[j];
        includeInList = false;
        var widget2 = FLYFI.getPlaylistWidget(nextID, newItemClass, playlistDicts, onClickFunc, onClickDeleteFunc, showCheckboxes, includeInList, onClickCheckboxFunc);
        newList.append(widget2);
    }
    
    var oldList = list.replaceWith(newList);
    oldList = null;
    
    if (FLYFI.isWidget) {
        FLYFI.setWidgetLibraryList(parentSelector + ' .grooveitems');
    }
    
    if (playlistDicts.length > 0) {
        parent.show();
        toggle.show();
    } else {
        toggle.hide();
        if (hideSectionIfEmpty) {
            parent.hide();
        }
    }
};

FLYFI.getPlaylistWidget = function(targetID, newItemClass, playlistDicts, onClickFunc, onClickDeleteFunc, showCheckboxes, includeInRadio, onClickCheckboxFunc) {
    var playlistDict = null; 
    var l = playlistDicts.length;
    for (var i = 0; i < l; ++i) {
        if ((playlistDicts[i].libraryID && playlistDicts[i].libraryID == targetID) ||
            (playlistDicts[i].contestCategoryID == targetID)) {
            playlistDict = playlistDicts[i];
            break;
        }
    }
    if (playlistDict === null) {
        return;
    } 
        
    var a = [];
    a.push('<li class="');
    a.push(newItemClass);
    if (playlistDict.libraryID) {
        a.push(' library-');
        a.push(playlistDict.libraryID);
    }
    
    if (FLYFI.isContestCreation()) {
        if (playlistDict.contestCategoryID) {
            a.push(' contestcategory');
            a.push(' category-' + playlistDict.contestCategoryID);
        } else {
            return; // don't add this one since it is not a category in this contest
        }
    }
    if (playlistDict.computed) {
        a.push(' computed');
    }
    a.push('">');
    a.push('<a href="#"');
    if (playlistDict.libraryID) { // NYI - get rid of libraryid= in favor of class
        a.push(' libraryid="');
        a.push(playlistDict.libraryID);
    }
    a.push('">');
    a.push(playlistDict.name);
    if (playlistDict.writable && !playlistDict.isitunescloud) {
        a.push('<span class="deletelibrary"> [-] </span>');
    }
    a.push('</a>');
    if (showCheckboxes) {
        a.push('<input type="checkbox" ');
        if (includeInRadio || (FLYFI.isContestCreation() && playlistDict.contestCategoryInclude)) {
            a.push(' checked="checked"');
        }
        a.push('/>'); 
    }
    a.push('</li>');
    var widget = $(a.join(''));
    widget.find('a').click(onClickFunc);
    if (playlistDict.writable) {
        widget.find('.deletelibrary').click(onClickDeleteFunc);
    }
    if (showCheckboxes) {
        widget.find('input').click(onClickCheckboxFunc);
    }
    return widget;
};

FLYFI._redisplayContestCategoryList = function(parentSelector, newItemClass, categoryDicts, onClickFunc) {    
    /* rebuild the list of contests in parentSelector with items of newItemClass.  The data is in categoryDicts. */
    var parent = $(parentSelector);
    var list = parent.find('.grooveitems');
    var toggle = parent.find('.toggle');
    var newList = list.clone(true);
    newList.empty();
    
    var l = categoryDicts.length;
    for (var i = 0; i < l; ++i) {
        var categoryDict = categoryDicts[i];
        var widget = FLYFI.getCategoryWidget(categoryDict, newItemClass, onClickFunc);
        newList.append(widget);
    }
    
    var oldList = list.replaceWith(newList);
    oldList = null;
      
    if (l > 0) {
        parent.show();
        toggle.show();
        if (FLYFI.isContest()) {
            if (FLYFI.isContestCreation() && (FLYFI.initialContestCategoryID || FLYFI.initialContestEntryID)) {
                FLYFI.selectEditedContestEntry();
            } else {
                FLYFI.selectFirstCategory();
            }
        }
    } else {
        toggle.hide();
        parent.hide();
    }
};
FLYFI.getCategoryWidget = function(categoryDict, newItemClass, onClickFunc) {
    var a = [];
    a.push('<li class="contestcategory ');
    a.push(     newItemClass);
    a.push(     ' category-');
    a.push(     categoryDict.contestCategoryID);
    a.push('">');
    a.push(     '<a href="#">');
    a.push(         categoryDict.contestCategoryName);
    a.push(     '</a>');
    a.push('</li>');
    var widget = $(a.join(''));
    widget.find('a').click(onClickFunc);
    return widget;
};

FLYFI.onClick_playlistCheckbox = function(event) {
    if (FLYFI.isContestCreation()) {
        FLYFI.server_updateContestCategories();
    } else {
        FLYFI._onClick_playlistCheckbox(event, FLYFI.customRadioLibraries);
    }
};
FLYFI.onClick_prefabCheckbox = function(event) {
    FLYFI._onClick_playlistCheckbox(event, FLYFI.customRadioLibraries_Prefabs);
};
FLYFI._onClick_playlistCheckbox = function(event, libraryIDsArray) {
    var checkbox = $(event.target);
    var libraryID = FLYFI.libraryIDFromWidget(checkbox.parents('li'));
    FLYFI._do_onClick_playlistCheckbox(checkbox, libraryID, libraryIDsArray);
};
FLYFI._do_onClick_playlistCheckbox = function(checkbox, libraryID, libraryIDsArray) { // NYI - check categories, too?
    FLYFI.selectLibraryByID(libraryID, function() { FLYFI._callback_onClick_playlistCheckbox(checkbox, libraryID, libraryIDsArray); } );
};

FLYFI._callback_onClick_playlistCheckbox = function(checkbox, libraryID, libraryIDsArray) {
    // the library has been loaded - allow the check
    if (checkbox.attr('checked')) {
        libraryIDsArray[libraryID] = true;
    } else {
        libraryIDsArray[libraryID] = null;
    }
    FLYFI.server_CustomRadioSetStations();
};

FLYFI.in_Widget_Set = false;    // don't allow more than one request, but if get another while one is pending, start it afterwards
FLYFI.pending_Widget_Set = false;

FLYFI.server_CustomRadioSetStations = function() {
    var stations = []; // ordered list of (libraryID, includingInRadio)
    var checkboxes = $('#playlists .grooveitems input, #grooves .grooveitems input');
    var l = checkboxes.length;
    var checkbox = null;
    var i = null;
    for (i = 0; i < l; ++i) {
        checkbox = checkboxes.eq(i);
        stations.push('(' + FLYFI.libraryIDFromWidget(checkbox.parents('li')) + ',' + (checkbox.attr('checked') ? 'True' : 'False') + ')');
    }

    var prefabs = [];
    checkboxes = $('#prefabs_free .grooveitems input, #prefabs_video .grooveitems input');
    l = checkboxes.length;
    for (i = 0; i < l; ++i) {
        checkbox = checkboxes.eq(i);
        prefabs.push('(' + FLYFI.libraryIDFromWidget(checkbox.parents('li')) + ',' + (checkbox.attr('checked') ? 'True' : 'False') + ')');
    }

    if (FLYFI.in_Widget_Set) {
        FLYFI.pending_Widget_Set = true;
    } else {
        FLYFI.in_Widget_Set = true;
        FLYFI.postJSONWithSpinner('/' + window.level + '/music/custom_radio/stations/set/json/',
                        {stations: '[' + stations.join(',') + ']', prefabs: '[' + prefabs.join(',') + ']'},
                        '.customradio_spinner', 
                        FLYFI.onServer_CustomRadioWidget,
                        FLYFI.showJSONError);
    }
};

FLYFI.playlistInRadioPlayer = function(libraryID) {
    var checkbox = $('.grooveitems .library-' + libraryID + ' input');
    return Boolean(checkbox.attr('checked'));
};

FLYFI.addPlaylistToRadioPlayer = function(libraryID) {
    var checkbox = $('.grooveitems .library-' + libraryID + ' input');
    checkbox.attr({'checked': 'checked'});
    FLYFI._do_onClick_playlistCheckbox(checkbox, libraryID, FLYFI.libraryIsPrefab(libraryID) ? FLYFI.customRadioLibraries_Prefabs : FLYFI.customRadioLibraries);
};

FLYFI.libraryIsPrefab = function (libraryID) {
    var l = FLYFI.customRadioLibraries_Prefabs.length;
    for (var i = 0; i < l; ++i) {
        if (FLYFI.customRadioLibraries_Prefabs[i][0] == libraryID) {
            return true;
        }
    }
    return false;
};

FLYFI.onServer_CustomRadioWidget = function(json) {
    if (FLYFI.onServer_Widget_Set) {
        FLYFI.onServer_Widget_Set();
    } else { // NYI - older code - obsolete?
        var widgetcode = json.widgetcode;
        // var widgetcodeescaped = json.widgetcodeescaped;
        
        $('.flyficustomradio').replaceWith($(widgetcode));
        $('#widgetcode').text(widgetcode);
    }
};

FLYFI.server_updateContestCategories = function() {
    var categories = []; // ordered list of (categoryID, includeInContest)
    var checkboxes = $('#playlists .grooveitems input');
    var l = checkboxes.length;
    var checkbox = null;
    var i = null;
    for (i = 0; i < l; ++i) {
        checkbox = checkboxes.eq(i);
        if (checkbox.parents('.computed').length > 0) {
            continue; // no 'mosts' lists
        }
        categories.push('(' + FLYFI.contestCategoryIDFromWidget(checkbox.parents('li')) + ',' + (checkbox.attr('checked') ? 'True' : 'False') + ')');
    }
    FLYFI.server.setContestCategories('[' + categories.join(',') + ']', function() {}, FLYFI.showJSONError);
};

FLYFI.onSortUpdate_playlists = function(event, ui) {
    if (FLYFI.isContestCreation()) {
        FLYFI.server_updateContestCategories();
    } else {
        FLYFI.server_CustomRadioSetStations();
    }
};

FLYFI.onSortUpdate_prefabs = function(event, ui) {
    FLYFI.server_CustomRadioSetStations();
};

FLYFI.ensureMyPlaylist = function(playlistName, callback) {
    // make sure there is a cloud to take any votes or completed tracks
    if (FLYFI.currentPlaylistDict && FLYFI.currentPlaylistDict.name == playlistName && callback) {
        callback(FLYFI.currentPlaylistDict);
    } else {
        FLYFI.waitingForServer_ensureMyPlaylist = true;
        FLYFI.postJSONWithSpinner('/library/json/new/playlist/',
                        {artists: '', name: playlistName ? playlistName : 'My Playlist'},
                        '.playlists_spinner', 
                        function(result) {
                            var libraryDict = result[0];
                            // var trackCount = result[1];
                            FLYFI.waitingForServer_ensureMyPlaylist = false;
                            FLYFI.setCurrentPlaylist(libraryDict);
                            FLYFI.updateMyClouds(null, callback, true);
                        },
                        FLYFI.showJSONError);
    }
};

FLYFI.ensureBookMarkLibrary = function(callback) {
    // make sure there is a cloud to take Bookmarked tracks
    if (FLYFI.currentPlaylistDict && FLYFI.currentPlaylistDict.name == 'Bookmarks' && callback) {
        callback(FLYFI.currentPlaylistDict);
    }else {
        var bookmarkLibraryDict = FLYFI.findBookMarkLibraryDict();
        if (bookmarkLibraryDict) {
            callback(bookmarkLibraryDict);
        } else {
            FLYFI.waitingForServer_ensureMyPlaylist = true;
            var currentLibraryID = FLYFI.currentPlaylistDict.libraryID;
            var currentTrackDict = FLYFI.playerControls.trackDict;
            FLYFI.postJSONWithSpinner('/library/json/new/playlist/',
                            {artists: '', name: 'Bookmarks'},
                            '.playlists_spinner', 
                            function(result) {
                                var libraryDict = result[0];
                                // var trackCount = result[1];
                                FLYFI.waitingForServer_ensureMyPlaylist = false;
                                FLYFI.updateMyClouds(null,  
                                                        function() {
                                                            if (callback) {
                                                                callback(libraryDict); 
                                                            }
                                                            FLYFI.selectLibraryByID(currentLibraryID); 
                                                            FLYFI.playerControls.selectTrack(currentTrackDict, false); 
                                                        }, 
                                                        false);
                            },
                            FLYFI.showJSONError);
        }
    }
};


FLYFI.setCurrentPlaylist = function(playlistDict) {
    FLYFI.currentPlaylistDict = playlistDict;
    if (FLYFI.playerControls) {
        FLYFI.playerControls.setPlaylistDict(playlistDict);
    }
    if (FLYFI.isContestCreation()) {
        if (playlistDict) {
            FLYFI.contestCreation_showEntryList();
        } else {
            FLYFI.contestCreation_hideEntryList();
        }        
    }
    // NYI - list not set here for contests!
    $(window).trigger(FLYFI.MSG_LibrarySelect);
};

FLYFI.setMyCloudsFromPage = function() {
    // The page has the initial data so that we don't need to do another request to show the page
    // return whether the page data was used
    if (window.jsonListMine) {
        FLYFI.onServer_ListMine(window.jsonListMine, true);
        window.jsonListMine = null;
        FLYFI.loadedInitialLibraries = true;
        $(window).trigger(FLYFI.MSG_LoadInitialLibraries);
        return true;
    } else {
        return false;
    }
};

FLYFI.onClick_Prefab = function(event) {
    event.preventDefault();
    var libraryID = $(this).attr('libraryid');
    FLYFI.selectLibraryByID(libraryID);
    FLYFI.showPostStart();
};

FLYFI.setPrefabsFromPage = function () {
    var list = null;
    var libraryID = null;
    var l = null;
    var i = null;
    if (window.jsonPrefabs_free) {
        FLYFI._redisplayPlaylistList('#prefabs_free', 'playlistitem', 
                                    window.jsonPrefabs_free, FLYFI.onClick_Prefab,
                                    null, Boolean(FLYFI.isCustomRadioPlayer()), FLYFI.customRadioLibraries_Prefabs, FLYFI.onClick_prefabCheckbox);
        if (FLYFI.customRadioLibraries_RequiredPrefabLibaryIDs.length > 0) {
            list = $('#prefabs_free .grooveitems');
            l = FLYFI.customRadioLibraries_RequiredPrefabLibaryIDs.length;
            for (i = 0; i < l; ++i) {
                libraryID = FLYFI.customRadioLibraries_RequiredPrefabLibaryIDs[i];
                list.find('.library-' + libraryID + ' input').attr('disabled', 'disabled');
            }
        }
        if (FLYFI.isCustomRadioPlayer()) {
            $('#prefabs_free .grooveitems').sortable({ axis: 'y',
                                                    update: FLYFI.onSortUpdate_prefabs
                                                });
        }
    }
    if (window.jsonPrefabs_video) {
        FLYFI._redisplayPlaylistList('#prefabs_video', 'playlistitem', 
                                    window.jsonPrefabs_video, FLYFI.onClick_Prefab,
                                    null, Boolean(FLYFI.isCustomRadioPlayer()), FLYFI.customRadioLibraries_Prefabs, FLYFI.onClick_prefabCheckbox);
        if (FLYFI.customRadioLibraries_RequiredPrefabLibaryIDs.length > 0) {
            list = $('#prefabs_video .grooveitems');
            l = FLYFI.customRadioLibraries_RequiredPrefabLibaryIDs.length;
            for (i = 0; i < l; ++i) {
                libraryID = FLYFI.customRadioLibraries_RequiredPrefabLibaryIDs[i];
                list.find('.library-' + libraryID + ' input').attr('disabled', 'disabled');
            }
        }
        if (FLYFI.isCustomRadioPlayer()) {
            $('#prefabs_video .grooveitems').sortable({ axis: 'y',
                                                    update: FLYFI.onSortUpdate_prefabs
                                                });
        }
    }
    if (window.json_contest_category_dicts) {
        FLYFI._redisplayContestCategoryList('#prefabs_contest', 'playlistitem', 
                                    window.json_contest_category_dicts, FLYFI.onClick_ContestCategory);
    }
};

FLYFI.selectContestCategory = function(categoryID) {
    var categoryDict = null;
    var l = window.json_contest_category_dicts.length;
    for (var i=0; i< l; i++) {
        if (window.json_contest_category_dicts[i].contestCategoryID == categoryID) {
            categoryDict = window.json_contest_category_dicts[i];
            break;
        }
    }
    if (categoryDict) {
        var categoryItems;
        if (FLYFI.isContestCreation()) {
            categoryItems = $('#playlists .grooveitems');
        } else {
            categoryItems = $('#prefabs_contest .grooveitems');
        }
        var targetItem = categoryItems.find('.category-' + categoryDict.contestCategoryID + ' a');
        if (!targetItem.hasClass('active')) {
            categoryItems.find('a').removeClass('active');
            targetItem.addClass('active');
        }
        FLYFI.scrollListToRow(targetItem.parents('.contestcategories'), targetItem.parents('.item'), FLYFI.scrollExtraInList);

        if (FLYFI.playingTrack.playerControls == FLYFI.playerControls) { // Clear the controls if there is a track playing in the brown player
            FLYFI.playingTrack.pause();
        }
        if (FLYFI.playerControls) {
            FLYFI.playerControls.clear();
        }

        FLYFI.setCurrentPlaylist(categoryDict);
        FLYFI.updateCurrentLibraryName();
        FLYFI.refreshCloud();
    }
};

FLYFI.selectPlaylist = function(playlistDict, callback) {
    var grooveitems = $('#grooves .grooveitems, #itunesgrooves .grooveitems, #playlists .grooveitems, #prefabs_free .grooveitems, #prefabs_video .grooveitems, #prefabs_contests .grooveitems');
    var targetItem = grooveitems.find('a[libraryid=' + playlistDict.libraryID + ']');
    if (targetItem.length === 0) {
        targetItem = grooveitems.find('.category-' + playlistDict.contestCategoryID + ' a');
    }
    if (!targetItem.hasClass('active')) {
        grooveitems.find('a').removeClass('active');
        targetItem.addClass('active');
    }
    if (FLYFI.isLikeIPhone()) {
        FLYFI.showIPhonePlayer();
    } else {
        FLYFI.scrollListToRow(targetItem.parents('.libraries'), targetItem.parents('.grooveitem, .playlistitem'), FLYFI.scrollExtraInList);
    }

    if (FLYFI.isContestCreation()) {
        FLYFI.setContestCategoryType(playlistDict);
    }
    // Select the passed in library and update the list, then update other other content(TBC, MM) to match the library

	if (FLYFI.playingTrack.playerControls == FLYFI.playerControls) { // Clear the controls if there is a track playing in the brown player
        FLYFI.playingTrack.pause();
	}
    if (FLYFI.playerControls) {
        FLYFI.playerControls.clear();
    }

    FLYFI.setCurrentPlaylist(playlistDict);
    FLYFI.updateCurrentLibraryName();
    FLYFI.refreshCloud(callback);
};

FLYFI.isMyPlaylist = function(libraryID) {
    var l = FLYFI.libraryDicts_MyPlaylists.length;
    for (var i=0; i < l; i++) {
        if (FLYFI.libraryDicts_MyPlaylists[i].libraryID == libraryID) {
            return true;
        }
    }
    return false;
};

FLYFI.findBookMarkLibraryDict = function() {
    // return the libraryDict for the 'Bookmarks' library if it exists
    var l = FLYFI.libraryDicts_MyPlaylists.length;
    for (var i=0; i < l; i++) {
        if (FLYFI.libraryDicts_MyPlaylists[i].name == 'Bookmarks') {
            return FLYFI.libraryDicts_MyPlaylists[i];
        }
    }
    return null;
};

FLYFI.selectCategoryByID = function(contestCategoryID, callback) {
    // use this for the contest creation page, where categories are shown like a playlists (including disabled categories)
    // to select a category on the contest page, use FLYFI.selectContestCategory() instead.
    if (!window.json_contest_category_dicts) {
        return;
    }
    var l = window.json_contest_category_dicts.length;
    for (var i=0; i< l; i++) {
        if (window.json_contest_category_dicts[i].contestCategoryID == contestCategoryID) {
            FLYFI.selectPlaylist(window.json_contest_category_dicts[i], callback);
        }
    }
}; 

FLYFI.selectLibraryByID = function(id, callback) {
    var libraryDict = null;
    var l = FLYFI.libraryDicts_MyClouds.length;
    for (var i=0; i< l; i++) {
        if (FLYFI.libraryDicts_MyClouds[i].libraryID == id) {
            libraryDict = FLYFI.libraryDicts_MyClouds[i];
            break;
        }
    }
    if (!libraryDict) {
        l = FLYFI.libraryDicts_MyPlaylists.length;
        for (i=0; i< l; i++) {
            if (FLYFI.libraryDicts_MyPlaylists[i].libraryID == id) {
                libraryDict = FLYFI.libraryDicts_MyPlaylists[i];
                break;
            }
        }
    }
    if (!libraryDict) {
        l = FLYFI.libraryDicts_MostsPlaylists.length;
        for (i=0; i< l; i++) {
            if (FLYFI.libraryDicts_MostsPlaylists[i].libraryID == id) {
                libraryDict = FLYFI.libraryDicts_MostsPlaylists[i];
                break;
            }
        }
    }
    if (!libraryDict && window.jsonPrefabs_free) {
        l = window.jsonPrefabs_free.length;
        for (i=0; i< l; i++) {
            if (window.jsonPrefabs_free[i].libraryID == id) {
                libraryDict = window.jsonPrefabs_free[i];
                break;
            }
        }
    }
    if (!libraryDict && window.jsonPrefabs_video) {
        l = window.jsonPrefabs_video.length;
        for (i=0; i< l; i++) {
            if (window.jsonPrefabs_video[i].libraryID == id) {
                libraryDict = window.jsonPrefabs_video[i];
                break;
            }
        }
    }
    if (libraryDict) {
        FLYFI.selectPlaylist(libraryDict, callback);
    }
};

FLYFI.refreshCloud = function(callback) {
	FLYFI.isRefreshingCloud = true;
    FLYFI.clearPlayerTracks();
    FLYFI.update_playerTracks(function() { 
                                if (callback) { callback(); }
                                setTimeout(FLYFI.updateTBCforLibrary, 400);
                            });
};

FLYFI.updateCurrentLibraryName = function() {
    var current_library_name = "";
    if (FLYFI.currentPlaylistDict === null) {
        current_library_name = "(no cloud selected)";
    } else if (!FLYFI.currentPlaylistDict.name) {
        current_library_name = "(cloud has no name)";
    } else  {
        current_library_name = FLYFI.currentPlaylistDict.name;
    }
    FLYFI.setCurrentLibraryName(current_library_name);
    FLYFI.setCurrentLibraryGenres([]);
    
    if (FLYFI.currentPlaylistDict && FLYFI.currentPlaylistDict.writable) {
        $('.edit_cloud_btn').show();
    } else {
        $('.edit_cloud_btn').hide();
    }
    
    if (FLYFI.isContest()) {
        FLYFI.setContestCategoryClass(FLYFI.currentPlaylistDict);
    }
};

FLYFI.setCurrentLibraryName = function(name) {
    $('.current_station .station_name').text(name);
};

FLYFI.setCurrentLibraryGenres = function(genres) {
    // NYI - should have genreDicts
    if (genres.length > 0) {
        $('.current_station .station_genres').text(genres);
        $('.station_genre_list').show();
    } else {
        $('.station_genre_list').hide();
    }
};

FLYFI.replaceTrackInLibrary = function(trackID, libraryID, callback) {
    if (trackID && libraryID) {
        FLYFI.postJSON('/library/json/' + libraryID + '/replacetrack/',
                        {'trackId': trackID},
                        callback, FLYFI.showJSONError);
    }
};

FLYFI.refreshRecsForLibrary = function(libraryID, callback) {
    if (libraryID) {
        FLYFI.postJSON('/library/json/' + libraryID + '/refreshrecs/',
                        {},
                        callback, FLYFI.showJSONError);
    }
};

FLYFI.updateMyClouds = function(event, callback, resetCurrentLibrary) {
    if (typeof(resetCurrentLibrary) == 'undefined') {
        resetCurrentLibrary = true;
    }
    if (!FLYFI.setMyCloudsFromPage()) {
        FLYFI.getJSONWithSpinner('/library/json/listmine/', 
                                    '.grooves_spinner', 
                                    function (result) { 
                                        FLYFI.onServer_ListMine(result, resetCurrentLibrary); 
                                        if (callback) {
                                            callback(FLYFI.currentPlaylistDict);
                                        }
                                        if (!FLYFI.loadedInitialLibraries) {
                                            FLYFI.loadedInitialLibraries = true;
                                            $(window).trigger(FLYFI.MSG_LoadInitialLibraries);
                                        }
                                    }, 
                                    FLYFI.showJSONError);
    }
};

FLYFI.updateTBCforLibrary = function() {
    if (FLYFI.currentPlaylistDict) {
        var tbcItems = $('#tbc');  // don't get TBC if there isn't any place to show it
        if (tbcItems.length > 0) {
            FLYFI.postJSONWithSpinner('/' + window.level + '/library/' + FLYFI.currentPlaylistDict.libraryID + '/select/json/tbc/', 
                            {},
                            '#tbc .spinner', 
                            FLYFI.onServer_SelectJsonTBC, 
                            FLYFI.showJSONError);
        }
    }
};
FLYFI.onServer_SelectJsonTBC = function(results) {
    FLYFI.videoData = results.videoDicts;
    $(window).trigger(FLYFI.MSG_TBC_Video_Updated);
    
    FLYFI.tbc_articles = results.tbc_articles;
    FLYFI.tbc_newreleases = results.tbc_newreleases;
    $(window).trigger(FLYFI.MSG_TBC_Updated);
};

FLYFI.setIfPostStart = function() {
    if ((FLYFI.libraryDicts_MyClouds.length > 0) || (FLYFI.libraryDicts_MyPlaylists.length > 0) || FLYFI.isContest() || FLYFI.isWidgetCreationPage()) {
        FLYFI.showPostStart();
        return;
    }
    
    if (FLYFI.preferences.getBoolean(FLYFI.NOTCOLDSTART, false)) {
        FLYFI.showCoolStart();
        return;
    }
    
    FLYFI.showColdStart();
};
FLYFI.showPostStart = function() {
	var body = $('body');
	if (body.hasClass("poststart")) {
		body.removeClass("makenewlist");
		return;
	}
    FLYFI.preferences.setBoolean(FLYFI.NOTCOLDSTART, true); // only show cold start once
    body.addClass('poststart').removeClass('coldstart').removeClass('coolstart');
    $('#freemusicmain').hide();    
    $('#freemusicmain .tabnav').show();
    $('#tbc').show();
    $(window).trigger(FLYFI.MSG_PostStart);
	FLYFI.trackAjaxCall("showPostStart");
};
FLYFI.showCoolStart = function() {
    FLYFI.preferences.setBoolean(FLYFI.NOTCOLDSTART, true); // only show cold start once
    $('body').addClass('coolstart').removeClass('coldstart').removeClass('poststart');
    $('#tbc').hide();
    $('#freemusicmain .tabnav').hide();
    $('#freemusicmain').show();
    $(window).trigger(FLYFI.MSG_CoolStart);
	FLYFI.trackAjaxCall("showCoolStart");
};
FLYFI.showColdStart = function() {
    $('body').addClass('coldstart').removeClass('poststart').removeClass('coolstart');
    $('#tbc').hide();
    $('#freemusicmain .tabnav').hide();
    $('#freemusicmain').show();    
	FLYFI.trackAjaxCall("showColdStart");
};

// Expand/Collapse Lists

FLYFI.grooves_visible = true;
FLYFI.onMinimize_Grooves = function(event) {
	FLYFI.grooves_visible = FLYFI._onMinimize(event, '#grooves', FLYFI.grooves_visible);
};

FLYFI.shared_visible = true;
FLYFI.onMinimize_SharedPlaylists = function(event) {
	FLYFI.shared_visible = FLYFI._onMinimize(event, '#sharedplaylists', FLYFI.shared_visible);
};

FLYFI.itunesgrooves_visible = true;
FLYFI.onMinimize_ITunesGrooves = function(event) {
	FLYFI.itunesgrooves_visible = FLYFI._onMinimize(event, '#itunesgrooves', FLYFI.itunesgrooves_visible);
};

FLYFI.playlists_visible = true;
FLYFI.onMinimize_Playlists = function(event) {
	FLYFI.playlists_visible = FLYFI._onMinimize(event, '#playlists', FLYFI.playlists_visible);
};

FLYFI.prefabs_free_visible = true;
FLYFI.onMinimize_Prefabs_free = function(event) {
	FLYFI.prefabs_free_visible = FLYFI._onMinimize(event, '#prefabs_free', FLYFI.prefabs_free_visible);
};

FLYFI.prefabs_video_visible = true;
FLYFI.onMinimize_Prefabs_video = function(event) {
	FLYFI.prefabs_video_visible = FLYFI._onMinimize(event, '#prefabs_video', FLYFI.prefabs_video_visible);
};

FLYFI._onMinimize = function(event, playlistTag, isVisible) {
    event.preventDefault();
    if (isVisible) {
        $(playlistTag + ' .grooveitems').hide();
        $(playlistTag).addClass('closed');        
        return false;
    }
    $(playlistTag + ' .grooveitems').show();
    $(playlistTag).removeClass('closed');        
    return true;
};

// New Groove Form

FLYFI.prepareForm_NewGroove = function(formSelector, dialogSelector, interstitialDialogSelector) {
    $(formSelector).show();
    $(interstitialDialogSelector).hide();
    
    var dialog = $(dialogSelector);
    dialog.find('.nomatch').hide();
    dialog.find('.groovename').val('');
    dialog.find('.artists').val('').focus();
};
FLYFI.prepareForm_NewGroove_NoMatch = function(nonMatchingArtists) {
    $('#new_groove_form').show();
    $('#groove_interstitial_dialog').hide();
    
    var dialog = $('#new_groove_dialog');
    dialog.find('.nomatch').show();
    dialog.find('.show').hide();
    dialog.find('.artists').val(nonMatchingArtists).focus();
};

FLYFI.askForNewGroove = function(formSelector) {
    var form = $(formSelector);
    var name = form.find('.groovename').val();
    var artists = form.find('.artists').val();
    
    if (!name && !artists) {
        alert('The new groove needs a name or list of artists.');
        return;
    }
    
    FLYFI.askServerForNewGroove(artists, name);
};

FLYFI.onSubmit_NewGroove = function(event, formSelector, interstitialDialogSelector) {
    event.preventDefault();
    FLYFI.askForNewGroove(formSelector);

    if (FLYFI.isLikeIPhone() || FLYFI.preferences.getBoolean('dontshow-newgrooveinterstitial', false)) {
        tb_remove();
    } else {
        $(formSelector).hide();
        $(interstitialDialogSelector).show();
    }
};

FLYFI.close_InterstitialDialog_Free = function(event) {
    FLYFI.updateListFilterControls(true, false, true);
    FLYFI.close_InterstitialDialog(event);
};

FLYFI.close_InterstitialDialog_YouTube = function(event) {
    FLYFI.updateListFilterControls(true, false, false);
    FLYFI.close_InterstitialDialog(event);
};

FLYFI.close_InterstitialDialog = function(event) {
    event.preventDefault();
    if ($('#groove_interstitial_dialog .dontshow:checked').length > 0) {
        FLYFI.preferences.setBoolean('dontshow-newgrooveinterstitial', true);
    }
    tb_remove();
};

FLYFI.askServerForNewGroove = function(artists, name) {
    var adventurousness = FLYFI.preferences.getFloat('default_adventurousness', 0.5);
    FLYFI.postJSONWithSpinner('/' + window.level + '/library/json/new/artists/', 
                                {artists: artists, name: name, adventurousness: adventurousness}, 
                                '.grooves_spinner', 
                                FLYFI.onServer_NewLibrary_Form, 
                                FLYFI.showJSONError);
};

FLYFI.click_NewLibNoMatch = function() {
    $('#grooves .newlibnomatch a').click();
};

FLYFI.onServer_NewLibrary_Form = function(json) {
    var libraryDict = json.libraryDict;
    var nonMatchingArtists = json.nonMatchingArtists;
    
    if (libraryDict) {
        FLYFI.playingTrack.pause(); // Stop whatever is playing so that the library will play when it loads.
        FLYFI.subsequentLibrarySelected = true; // Make sure that the library auto-plays.
        FLYFI.updateMyClouds(null, function() {FLYFI.selectLibraryByID(libraryDict.libraryID);}, true);
        FLYFI.setIfPostStart();
        if (nonMatchingArtists.length >= 1) {
            var artistString = null;
            if (nonMatchingArtists.length == 1) {
                artistString = "artist '" + nonMatchingArtists[0] + "' was";
            } else {
                artistString = "the artists '" + nonMatchingArtists.join("', '") + "' were";
            }
            alert("The Groove was created but " + artistString + " not found and will not be used to find tracks. Click on the Groove's 'Edit' link to adjust the artists.");
        }
    } else {
        FLYFI.prepareForm_NewGroove_NoMatch(nonMatchingArtists);
        setTimeout(FLYFI.click_NewLibNoMatch, 500); // give time for the old ThickBox to close
    }
};

// New Playlist Form

FLYFI.uniqueLibraryName = function(name) {
    // return a name for a new library, based on the supplied name, that does not match any existing library
    var newName = name;
    var number = null;
    while (true) {
        var found = false;
        var l = FLYFI.libraryDicts_MyClouds.length;
        for (var i = 0; i < l; ++i) {
            if (newName == FLYFI.libraryDicts_MyClouds[i].name) {
                found = true;
                break;
            }
        }
        if (!found) {
            l = FLYFI.libraryDicts_MyPlaylists.length;
            for (i = 0; i < l; ++i) {
                if (newName == FLYFI.libraryDicts_MyPlaylists[i].name) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                l = FLYFI.libraryDicts_MostsPlaylists.length;
                for (i = 0; i < l; ++i) {
                    if (newName == FLYFI.libraryDicts_MostsPlaylists[i].name) {
                        found = true;
                        break;
                    }
                }
            }
        }
        if (found) {
            if (number === null) {
                number = 1;
            } else {
                number += 1;
            }
            newName = name + ' ' + number;
        } else {
            return newName;
        }
    }
    return name; // should never get here - this is just for Lint
};


FLYFI.onServer_NewPlaylist = function(libraryDict, trackCount, artist, track) {
    // NYI - FLYFI.waitingForServer_newLibrary = false;
    // NYI - FLYFI.setLibrarySpinner();
    if (libraryDict) {
        FLYFI.playingTrack.pause(); // Stop whatever is playing so that the library will play when it loads.
        FLYFI.updateMyClouds(null, function() {FLYFI.selectLibraryByID(libraryDict.libraryID);}, true);
        FLYFI.setIfPostStart();
        if (artist && track && trackCount === 0) {
            alert("The playlist was created but we found no track '" + track + "' for artist '" + artist + "' in our database. Use the find (magnifying glass) button or the search page to find tracks for your playlist.");
        }
    }
};
FLYFI.onServer_NewContestCategory = function(categoryDict) {
    var existingDict = FLYFI.getDictForContestCategory(categoryDict.contestCategoryID);
    if (!existingDict) {
        window.json_contest_category_dicts.push(categoryDict);
        FLYFI.redisplayMyCloudList();
    }
    
    FLYFI.selectCategoryByID(categoryDict.contestCategoryID);
};
FLYFI.onSubmit_NewPlaylist = function(event) {
    var dialog;
    if (FLYFI.isContestCreation()) {
        dialog = $('#new_contestcategory_dialog');
    } else {
        dialog = $('#new_playlist_dialog');
    }
    var name = dialog.find('.playlistname').val();
    
    if (!name) {
        event.preventDefault();
        alert('The new ' + (FLYFI.isContestCreation() ? 'category' : 'playlist') + ' needs a name.');
        return;
    }
    
    if (FLYFI.isContestCreation()) {
        FLYFI.server.newContestCategory(FLYFI.contestID, name, '.playlists_spinner', 
                            FLYFI.onServer_NewContestCategory,
                            FLYFI.showJSONError);
    } else {
        FLYFI.server.newPlaylist(name, '.playlists_spinner', 
                            function (result) { FLYFI.onServer_NewPlaylist(result[0]); },
                            FLYFI.showJSONError);
    }
    tb_remove();
    event.preventDefault();
};

FLYFI.askServerForNewPlaylistWithTracks = function(artists, tracks) {
    var name = artists;
    if (!name) {
        name = tracks;
    }
    FLYFI.postJSONWithSpinner('/library/json/new/playlist/', 
                        {name: name, artists: artists, tracks: tracks},
                        '.playlists_spinner', 
                        function (result) { FLYFI.onServer_NewPlaylist(result[0], result[1], artists, tracks); },
                        FLYFI.showJSONError);
};

// Edit Groove Form

FLYFI.onClick_EditPlaylist = function (event, playlistDict) {
	if (event) {
		event.preventDefault();
	}
	if (!playlistDict) {
		playlistDict = FLYFI.currentPlaylistDict;
	}
    if (!playlistDict) { // user may have deleted the library
        return;
    }
    
    if (playlistDict.iscloud) {
        FLYFI.updateEditDialogSeedArtistsStringFromServer(playlistDict);
        $('#edit_groove_name').val(playlistDict.name);
        $('#edit_artists_field').attr('disabled', 'disabled'); // Disable - will be enabled when filled by server
        $('#edit_artists_field').val(''); // Blank out - will be filled by server
        $('#edit_artists_field').focus();
        $('#edit_groove_dialog_link').click();
    } else if (playlistDict.libraryID) {
        $('#edit_playlist_name').val(playlistDict.name);
        $('#edit_playlist_dialog_link').click();
    } else if (playlistDict.contestCategoryID) {
        $('#edit_contestcategory_name').val(playlistDict.name);
        $('#edit_contestcategory_dialog_link').click();
    }
};

FLYFI.updateEditDialogSeedArtistsStringFromServer = function(libraryDict) {
	if (!libraryDict) {
		libraryDict = FLYFI.currentPlaylistDict;
	}
    if (!libraryDict) { // user may have deleted the library
        return;
    }
    
    FLYFI.postJSONWithSpinner('/library/' + libraryDict.libraryID + '/json/seed_artist_names/',
                        {},
                        '#edit_groove_form .spinner',
                        FLYFI.onServer_SeedArtistNames, 
                        FLYFI.showJSONError);
};
FLYFI.onServer_SeedArtistNames = function(s) {
    var name = s ? s : '';
    $('#edit_artists_field').val(name);    
    $('#edit_artists_field').removeAttr('disabled');
};
    
FLYFI.onSubmit_EditGroove = function(event, libraryDict, UIcallback) {
    event.preventDefault();

    var name = $('#edit_groove_name').val();
    var artists = $('#edit_artists_field').val();
    
    if (!name && !artists) {
        alert('The groove needs a name or a list of artists.');
        return;
    }
    
    if (!libraryDict) {
        libraryDict = FLYFI.currentPlaylistDict;
    }
    if (libraryDict) {
        FLYFI.postJSONWithSpinner('/library/' + libraryDict.libraryID + '/json/edit/artists/',
                            {artists: artists, name: name},
                            '.grooves_spinner',
                            function (result) {
                                FLYFI.onServer_GrooveEdited(result, libraryDict, name, UIcallback);
                            },
                            FLYFI.showJSONError);
    }
    tb_remove();
};
FLYFI.onServer_GrooveEdited = function(json, libraryDict, newName, UIcallback) {
	var oldName = libraryDict.name;
    var nonMatchingArtists = json.nonMatchingArtists;
	libraryDict.name = newName;
    if (nonMatchingArtists.length >= 1) {
        var artistString = null;
        if (nonMatchingArtists.length == 1) {
            artistString = "artist '" + nonMatchingArtists[0] + "' was";
        } else {
            artistString = "artists '" + nonMatchingArtists.join("', '") + "' were";
        }
        alert("The " + artistString + " not found and were not added to the Groove. Click on the Groove's 'Edit' link again to adjust the artists.");
    }
    var callback = UIcallback ? UIcallback : FLYFI.onServer_GrooveEdited_UIcallback;
    callback(json, libraryDict, oldName);
};
FLYFI.onServer_GrooveEdited_UIcallback = function(json, libraryDict, oldName) {
    var seedsChanged = json.seedsChanged;
    // var nonMatchingArtists = json.nonMatchingArtists;
    if (seedsChanged) {
        FLYFI.refreshCloud();
    } 
    if (libraryDict.name != oldName) {
        FLYFI.updateMyClouds(null, null, true);
    }
};

FLYFI.onSubmit_EditPlaylist = function(event) {
    event.preventDefault();
    if (!FLYFI.currentPlaylistDict) { // user may have deleted the library
        return;
    }

    var name = $('#edit_playlist_name').val();
    
    if (!name) {
        alert('The playlist needs a name.');
        return;
    }
    
    FLYFI.postJSONWithSpinner('/library/' + FLYFI.currentPlaylistDict.libraryID + '/json/edit/',
                        {name: name},
                        '.playlists_spinner',
                        function (result) {
                            FLYFI.onServer_PlaylistEdited(result, name != FLYFI.currentPlaylistDict.name);
                        },
                        FLYFI.showJSONError);
    tb_remove();
};
FLYFI.onServer_PlaylistEdited = function(result, renaming) {
    if (result) {
        FLYFI.refreshCloud();
    } 
    if (renaming) {
        FLYFI.updateMyClouds(null, null, true);
    }
};


// Adventurousness

FLYFI.prepareForm_AdventurousnessDialog = function () {
    FLYFI.updateEditDialogSeedArtistsStringFromServer();
    var adventurousness = FLYFI.preferences.getFloat('default_adventurousness', 0.5);

    $('#adventurousness_field').val(adventurousness);
    $('#adventurousness_field').focus();
};

FLYFI.onOK_AdventurousnessDialog = function (event) {
    event.preventDefault();
    var adventurousness = $('#adventurousness_field').val();
    try {
        var adventurousnessFloat = parseFloat(adventurousness);
        if ((0.0 <= adventurousnessFloat) && (adventurousnessFloat <= 1.0)) {
            FLYFI.preferences.setFloat('default_adventurousness', adventurousness);
            tb_remove();
            return;
        } 
    } catch (error) {
        // do nothing, but fall through to the warning
    }
    alert('Adventurousness must be between 0.0 and 1.0, inclusive.');
};


// Find track dialog

FLYFI.focus_FindTrackData = function() {
    $('#findTrack_dialog').find('.findtrackdata').focus();
};

FLYFI.findTrack = function() {
	var myLib = FLYFI.currentPlaylistDict;
    if (!myLib || !myLib.writable) {
        return;
    }
    
    // first set up the dialog
    var dialog = $('#findTrack_dialog');
    dialog.find('.findtrackheader').text("...to add to \"" + myLib.name + "\"").show();
    dialog.find('.findtrackdata').val('');
    dialog.find('.findtrack_button').removeAttr("disabled");
    dialog.find('.TB_closeWindowButton').removeAttr("disabled");
    $('#findTrack_result').hide();
    $('#findResult_dialog').find('.addtrack_button').hide();
    // now show the dialog - the timeout pulls the focus to the input field after the panel displays
    setTimeout(FLYFI.focus_FindTrackData, 300);
    $('.findtrack_link').click();
	FLYFI.trackAjaxCall("requestFindTrackDialog");
};

FLYFI.onSubmit_FindTrack = function(event) {
	event.preventDefault();
    if (!FLYFI.currentPlaylistDict) { // user may have deleted the library
        return;
    }

    var dialog = $('#findTrack_dialog');
    dialog.find('.findtrack_button').attr("disabled", "disabled");
    dialog.find('.TB_closeWindowButton').attr("disabled", "disabled");
    $('#findTrack_result').hide();
    $('#findResult_dialog').find('.addtrack_button').hide();
    FLYFI.getJSONWithSpinner('/json/findtrack/' + FLYFI.currentPlaylistDict.libraryID + '/' + encodeURI(dialog.find('.findtrackdata').val()) + '/',
        '#findTrack_dialog .spinner',
        FLYFI.onServer_FindTrack);
};

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

	FLYFI.found_trackDict = trackDict;
    var findDialog = $('#findTrack_dialog');
    findDialog.find('.findtrack_button').removeAttr("disabled");
	findDialog.find('.TB_closeWindowButton').removeAttr("disabled");
    var dialog = $('#findTrack_result');
    var search_link = dialog.find('.search_link');
    search_link.click(function(event) {
        event.preventDefault();
        FLYFI.preferences.setFloat(FLYFI.ADD_TARGET_LIBRARY, FLYFI.currentPlaylistDict.libraryID);
        var searchURL = (window.level == 'live' ? '/' : '/' + window.level + '/') + 'search/';
        FLYFI.createCookie('search.criteria', encodeURI(findDialog.find('.findtrackdata').val()));
        window.location = searchURL;
    });
    dialog.show();
    if (trackDict) {
        dialog.find('.song').text("track found: " + trackDict.title).show();
        dialog.find('.moreinfo').text("from \"" + trackDict.album + "\" by " + trackDict.artist).show();
        search_link.text('Not what you were looking for? Try your search again, or click here for more results.');
        $('#findResult_dialog').find('.addtrack_button').show();
    } else {
        dialog.find('.song').hide();
        dialog.find('.moreinfo').hide();
        search_link.text('No track was found. Try again or click here for search window.');
        $('#findResult_dialog').find('.addtrack_button').hide();
    }
};

FLYFI.onSubmit_AddFoundTrack = function(event) {
	event.preventDefault();
    var libraryID = FLYFI.currentPlaylistDict ? FLYFI.currentPlaylistDict.libraryID : null;
	FLYFI.server_voteUp(FLYFI.found_trackDict, libraryID, FLYFI.onServer_foundTrackAdded, true);
};

FLYFI.onServer_foundTrackAdded = function(trackDict) {
	// Called after the server does the vote up.
	// 1) Set the added track as the current track for the current library
	// 2) Reselect the current library to refresh the track list and start playing the added track.
	var currentLibraryDict = FLYFI.currentPlaylistDict;
	FLYFI.preferences.setTrackForLibrary(currentLibraryDict.libraryID, trackDict.trackID);
	FLYFI.refreshCloud(function() { if (!FLYFI.playingTrack.playing && FLYFI.playerControls) { FLYFI.playerControls.play(); } });
    $('#findTrack_dialog').find('.TB_closeWindowButton').click();

};

FLYFI.onClick_newPlaylist = function(event) {
	event.preventDefault();
	$("body").addClass("makenewlist");
	$("#coldstartmain input" + (FLYFI.preferences.getBoolean('coldstart_smart', true) ? ".smart" : ".basic")).click();
	FLYFI.onClick_coldstartmain_playlist_type();
	FLYFI.trackAjaxCall("requestNewPlaylistDialog");
};

// Copy libraries

FLYFI.copy_library = function(libraryID, copyAsGroove) {
	var newType = copyAsGroove ? "groove" : "playlist";
    FLYFI.postJSONWithSpinner('/library/json/copy/library/',
            {fromLibraryID: libraryID, newType: newType},
            '.copy_' + newType + '_spinner', 
            function(newLibraryDict) {
                FLYFI.updateMyClouds(null, 
                                    function() { 
                                        FLYFI.selectLibraryByID(newLibraryDict.libraryID, 
                                                                    function() { alert("OK. " + newType +" '" + newLibraryDict.name + "' was copied to your playlists. It's now available in your main player and on your profile page.");
                                                                    }
                                                                ); 
                                    },
                                    true
                                    );
            },
            FLYFI.showJSONError);
};

// Bind events

$(document).ready(function() {
    var playerShellShell = $('#player_shell_shell');
    playerShellShell.find('#grooves .toggle').click(FLYFI.onMinimize_Grooves);
    playerShellShell.find('#sharedplaylists .toggle').click(FLYFI.onMinimize_SharedPlaylists);
    playerShellShell.find('#itunesgrooves .toggle').click(FLYFI.onMinimize_ITunesGrooves);
    playerShellShell.find('#playlists .toggle').click(FLYFI.onMinimize_Playlists);
    playerShellShell.find('#prefabs_free .toggle').click(FLYFI.onMinimize_Prefabs_free);
    playerShellShell.find('#prefabs_video .toggle').click(FLYFI.onMinimize_Prefabs_video);
    playerShellShell.find('.edit_cloud_btn a').click(FLYFI.onClick_EditPlaylist);
    playerShellShell.find('.newplaylist a').click(FLYFI.onClick_newPlaylist);
    
    $('#edit_groove_form').submit(FLYFI.onSubmit_EditGroove);
    $('#edit_playlist_form').submit(FLYFI.onSubmit_EditPlaylist);
    
    $('#new_groove_form').submit(function(event) { FLYFI.onSubmit_NewGroove(event, '#new_groove_form', '#groove_interstitial_dialog'); });
    var interstitialForm = $('#interstitial_form');
    interstitialForm.find('.listfilter_Free').click(FLYFI.close_InterstitialDialog_Free);
    interstitialForm.find('.listfilter_YouTube').click(FLYFI.close_InterstitialDialog_YouTube);
    
    $('#new_playlist_form, #new_contestcategory_form').submit(FLYFI.onSubmit_NewPlaylist);

    $('.adventurousness_link').click(FLYFI.prepareForm_AdventurousnessDialog);
    $('#adventurousness_form').submit(FLYFI.onOK_AdventurousnessDialog);
    $('#findtrack_form').submit(FLYFI.onSubmit_FindTrack);
    $('#addfoundtrack_form').submit(FLYFI.onSubmit_AddFoundTrack);
    
    if ($('#prefabs_free, #prefabs_video, #facebook_community_playlist, #addTrack_dialog').length > 0) { // Some "inside" pages suppress the player - don't load libraries in this case (except FB).
        $(window).bind(FLYFI.MSG_LoginUpdated, FLYFI.updateMyClouds);
    }
});

// in calling page, when $(document).ready: $(window).bind(FLYFI.MSG_Start, FLYFI.setPrefabsFromPage)

