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

FLYFI.trackDialog_trackDict = null; // global for the trackDict used in a dialog

FLYFI.videoPlayerID = function(trackDict, inDialog) {
    return (inDialog ? 'dialog' : '') + '_videoplayer_' + trackDict.trackID;
};

FLYFI.buildTrackCellWidget = function(trackDict, inDialog) {
    var art = trackDict.artist_art;
    if (!art) {
        art = FLYFI.defaultArtPath;
    }
    var voted = (trackDict.vote !== null) ? (trackDict.vote === 0 ? ' voteddown' : ' votedup') : '';
    var free = trackDict.free ? ' free' : ' nonfree';
    var owned = trackDict.owned ? ' owned' : '';
    var blacklisted = trackDict.blacklisted ? ' blacklisted' : '';
    var trackIDclass = ' track-' + trackDict.trackID;
    
    var a = [];
    a.push('<ul>');
    if (trackDict.free) {
        a.push('<li class="albumart artwork">');
          if (FLYFI.isLikeIPhone()) {
            a.push('<a class="download_btn" href="http://' + window.dev + 'files.flyfi.com/tracks/download/' + trackDict.trackID +'/"><img src="' + art + '" width="140" height="140" /></a>');
            } else {        
            a.push('<a class="logclick" href="/' + window.level + '/music/artist/' + trackDict.artist + '/#' + trackDict.album + '"><img src="' + art + '" width="140" height="140" /></a>');
            }
        a.push('</li>');
    } else {
        a.push('<li class="video artwork">');
        a.push('    <div id="' + FLYFI.videoPlayerID(trackDict, inDialog) + '"></div>');
        a.push('</li>');
    }
    a.push('<li style="float:none;" class="controls track' + trackIDclass + voted + free + owned + blacklisted + '">');
    if (trackDict.free) {
        a.push('    <ul>');
    } else {        
        a.push('    <ul class="ff_youtube_controls">');
        a.push('        <li class="prev_video_btn video_btn" style="display: list-item;">');
        a.push('            <a title="Play previous video for this Track" href="">Play Previous Video</a>');
        a.push('        </li>');
        a.push('        <li class="next_video_btn video_btn" style="display: list-item;">');
        a.push('            <a title="Play next video for this Track" href="">Play Next Video</a>');
        a.push('        </li>');
        a.push('    </ul>');
        a.push('    <ul>');                
    }
    if (FLYFI.isLikeIPhone()) {
        a.push('    <li><a class="download_btn" style="background:transparent url(http://www.flyfi.com/static/live/flyfi/images/ff_musicfri_playicon_16x32.gif) no-repeat scroll -16px 0;cursor:pointer;height:16px;position:absolute;text-indent:-99999px;width:16px;" href="http://' + window.dev + 'files.flyfi.com/tracks/download/' + trackDict.trackID +'/">Download Now</a></li>');        
    } else {
        a.push('        <li class="play" style="position:relative;">');
        a.push('            <div class="scrubber" style="position:absolute; top:16px; left:0;">');
        a.push('                <div class="progress_bars">');
        a.push('                    <div class="load_progress"></div>');
        a.push('                    <div class="play_progress"></div>');
        a.push('               </div>');
        a.push('               <div class="scrub_thumb"></div>');
        a.push('           </div>');
        a.push('           <span class="play_btn" style="position:absolute; top:0; left:0;">Play Song</span>');
        a.push('       </li>');        
        if (trackDict.free) {
            a.push('    <li class="downloads">');        
            a.push('        <a class="download_btn more" href="http://' + window.dev + 'files.flyfi.com/tracks/download/' + trackDict.trackID +'/">Download Options</a>');
            a.push('        <ul class="popmenu">');
            a.push('            <li>Free and LEGAL downloadable music</li>');
            a.push('            <li class="link"><a class="logclick" href="/help/#br_3">Find out more</a></li>');
            a.push('            <li class="link"><a class="download_btn" href="http://' + window.dev + 'files.flyfi.com/tracks/download/' + trackDict.trackID +'/">Download Now</a></li>');
            a.push('        </ul>');
            a.push('    </li>');
            }
            a.push('    <li class="share sharemenu">');
            a.push('        <a href="#" title="Share This Track" class="more">Share This</a>');        
            a.push('    </li>');        
        if (!inDialog) {
            a.push('    <li class="trackcell_menu_btn menu"><span class="options">Menu</span>');
            a.push('        <ul class="trackcellmenu trackcellmenulist popmenu">');
            a.push('            <li class="vote_up_btn link">VoteUp</li>');
            a.push('            <li class="vote_down_btn link">VoteDown</li>');
            a.push('            <li class="add_btn link">Add</li>');
            if (trackDict.free) {
                a.push('        <li class="download_btn link"><a class="download_btn" href="http://' + window.dev + 'files.flyfi.com/tracks/download/' + trackDict.trackID +'/">Download Now</a></li>');
            }
            a.push('            <li class="buy_btn link">Buy</li>');
            a.push('            <li class="email_btn link">Email</li>');
            a.push('        </ul>');
            a.push('    </li>');
         }
    }
    a.push('    </ul>');
    a.push('</li>');
    a.push('<li class="artistinfo">');
    a.push('    <ul style="clear:both; position:relative;">');
    a.push('        <li class="songname">' + FLYFI.textOrNbsp(trackDict.title) + '</li>');
    a.push('        <li class="artistname">by <a class="logclick" href="/' + window.level + '/music/artist/' + trackDict.artist + '/">' + FLYFI.textOrNbsp(trackDict.artist) + '</a></li>');
    if (trackDict.genre !== '') {
        a.push('    <li class="genre">(' + trackDict.genre + ')</li>');
    }
    a.push('    </ul>');
    a.push('</li>');
  a.push('</ul>');    

    return $(a.join('\n'));
};

FLYFI.TrackCell = function(trackDict) {    // TrackCell Class
    // the class for a single track display including playing (may be audio or video track)
    // trackDict is the information about the track
    
    var self = this;

    self.trackDict = trackDict;
    self.eventCallback = null;
    self.playerControls = null;
    self.widget = null;
    
    
    self.html = function (widgetCallback, eventCallback, playerControlsCallback) {
        /* Return the widget to display this cell. 
            - widgetCallback is called with (trackDict) and should return the widget for the cell.
                See the FLYFI.PlayerControls code for the elements that it can use.  The code here
                relies on .scrubber and .progress_bars.
            - eventCallback is called with (widget) after it has been saved, so that event handlers can be added
            - playerControlsCallback is called with (widget) after it has been saved and should return the playerControls for the widget
        */
        if (!self.widget) {
            if (!widgetCallback) {
                return $('<span>no widgetCallback set for trackcell</span>');
            }
            self.widget = widgetCallback(self.trackDict);
            self.eventCallback = eventCallback;
            if (playerControlsCallback) {
                self.playerControls = playerControlsCallback(self.widget);
                if (self.playerControls) {
                    self.playerControls.addTrackDictAndWidget(self.trackDict, self.widget);
                }
            }
            
            if (eventCallback) {
                eventCallback(self.widget);
            }
        }
        return self.widget;
    };
};

FLYFI.onMouseUp_scrubber = function(event, progressBars) {
    event.preventDefault();
    event.stopPropagation();
    if (!FLYFI.playingTrack.scrubbing) {
        return;
    }
    FLYFI.playingTrack.stopScrubbing(event, progressBars);
};

FLYFI.onMouseUp_Body_TrackCell = function(event) {
    var progress_bars =  $('.playingtrack .progress_bars');
    if (progress_bars.length > 0) {
        FLYFI.onMouseUp_scrubber(event, progress_bars[0]);
    }
};

FLYFI.videoYouTubeID = function(trackDict) {
    if (trackDict.free || !trackDict.videoYouTubeIDs || (typeof(trackDict.videoIndex) == 'undefined')) {
        return null;
    } else {
       return trackDict.videoYouTubeIDs[trackDict.videoIndex];
    }
};

FLYFI.addTrack = function(trackDict, dialogSelector, dialogLink) {
    if (!trackDict) {
        return;
    }
    
    // first set up the dialog
    FLYFI.addDialog_trackDict = trackDict;
    var dialog = $(dialogSelector);
    FLYFI.updateAddTrackPlaylistList(dialog, trackDict);
    dialog.find('.title').text(trackDict.title);
    dialog.find('.artist').text(trackDict.artist);
    if (dialog.find('.playlists li').length > 0) {
        dialog.find('.targetPlaylistDiv').show();
        dialog.find('#addTrack_dialog_targetDiv ul.playlists').show();
        dialog.find('#addTrack_dialog_targetDiv h4').hide();
        dialog.find('.newCloudDiv .haveplaylists').show();
    } else {
        dialog.find('.targetPlaylistDiv').hide();
        dialog.find('#addTrack_dialog_targetDiv ul.playlists').hide();        
        dialog.find('#addTrack_dialog_targetDiv h4').show();
        dialog.find('.newCloudDiv .haveplaylists').hide();
    }
    dialog.find('.newPlaylistName').val('My Playlist');
    
    // now show the dialog
    $(dialogLink).click();
    
    // Wait till the dialog opens to select the current target library (otherwise will not find it).
    setTimeout(FLYFI._addTrack_scrollToTargetLibrary, 150);
};
FLYFI._addTrack_scrollToTargetLibrary = function() {
    // Scroll to the currently selected library if there is one
    var activeLib = $('#addTrack_dialog_targetDiv .playlists .active');
    if (activeLib.length) {
        FLYFI.scrollListToRow(activeLib.parents('.playlists'), activeLib.parents('li'), 10);
    }
};

FLYFI.buyTrack = function(trackDict, libraryID) {
    FLYFI.showBuyTrackDialog('#buyTrack_dialog', '.buytrack_link', trackDict, libraryID);
};

FLYFI.showBuyTrackDialog_libraryID = null;
FLYFI.showBuyTrackDialog = function(dialogSelector, dialogOpenLinkSelector, trackDict, libraryID) {
    if (!trackDict) {
        return;
    }
    FLYFI.showBuyTrackDialog_libraryID = libraryID;
    
    // set up the dialog
    FLYFI.trackDialog_trackDict = trackDict;
    var dialog = $(dialogSelector);
    dialog.find('.title').text(trackDict.title);
    dialog.find('.artist').text(trackDict.artist);
    
    var vendor = FLYFI.preferences.getString('buy-vendor', '');
    if (vendor) {
        dialog.find('.buyTrack_vendors li[vendor!=' + vendor + ']').removeClass('on');
        dialog.find('.buyTrack_vendors li[vendor=' + vendor + ']').addClass('on');
    }
    
    dialog.find('.buyTrack_vendors li').removeClass('available');
    var l = trackDict.vendors.length;
    for (var i = 0; i < l; ++i) {
        dialog.find('.buyTrack_vendors li[vendor=' + trackDict.vendors[i] + ']').addClass('available');
    }
    
    // now show the dialog
    $(dialogOpenLinkSelector).click();
};

FLYFI.voteUp_changableList = function(trackDict, libraryID, showDialog, callback) {
    // let the server know the user voted up the track in a list that will change (my-own-player)
    // callback gets the trackDict
    var dialogSelector = null;
    var dialogLink = null;
    if (showDialog) {
        dialogSelector = '#thickbox_voteUp_changing_dialog';
        dialogLink = '.voteUpChanging_link';
    }
    return FLYFI._voteUp(trackDict, libraryID, dialogSelector, dialogLink, showDialog, callback);
};

FLYFI.voteUp = function(trackDict, libraryID, showDialog, callback, isArtistPlayer) {
    // let the server know the user voted up the track in a list that will change (my-own-player)
    // callback gets the trackDict
    return FLYFI._voteUp(trackDict, libraryID, '#thickbox_voteUp_dialog', '.voteUp_link', showDialog, callback, isArtistPlayer);
};

FLYFI._voteUp = function(trackDict, libraryID, dialogSelector, dialogLinkSelector, showDialog, callback, isArtistPlayer) {
    // implementation of vote up.  callback gets the trackDict
    if (!trackDict) {
        return;
    }
    
    FLYFI.server_voteUp(trackDict, libraryID, callback, false, isArtistPlayer);

    if ($('#return_to_turk').length == 1) {
        if (FLYFI.playingTrack.playing && FLYFI.playingTrack.trackDict == trackDict) {
            alert("OK. Your video vote was recorded.");
        } else {
            alert("\n************************ NOTE ************************\n\nYour upvote will not actually do anything if the video is not playing.\n\n************************ NOTE ************************");
        }
        return;
    }
    
    if (FLYFI.preferences.getBoolean('dontshow-voteup', false)) {
        return;
    }
    
    if (showDialog && dialogSelector) {
        // set up the dialog
        FLYFI.trackDialog_trackDict = trackDict;
        var dialog = $(dialogSelector);
        dialog.find('.title').text(trackDict.title);
        dialog.find('.artist').text(trackDict.artist);

        // now show the dialog
        if (dialogLinkSelector) {
            $(dialogLinkSelector).click();
        }
    }
};

FLYFI.voteDown_changableList = function(trackDict, libraryID, callback) {
    // let the server know the user voted up the track in a list that will change (my-own-player)
    return FLYFI._voteDown(trackDict, libraryID, '#thickbox_voteDown_changing_dialog', '.voteDownChanging_link', callback);
};

FLYFI.voteDown = function(trackDict, libraryID, callback, isArtistPlayer) {
    // let the server know the user voted up the track in a list that will change (my-own-player)
    return FLYFI._voteDown(trackDict, libraryID, '#thickbox_voteDown_dialog', '.voteDown_link', callback, isArtistPlayer);
};

FLYFI._voteDown = function(trackDict, libraryID, dialogSelector, dialogLinkSelector, callback, isArtistPlayer) {
    if (!trackDict) {
        return;
    }

    FLYFI.server_voteDown(trackDict, libraryID, callback, isArtistPlayer);
    // Need to pause after sending the vote - we may need the video id
    if (trackDict == FLYFI.playingTrack.trackDict && FLYFI.playingTrack.playing) {
        FLYFI.playingTrack.pause();
    }

    if (FLYFI.preferences.getBoolean('dontshow-votedown', false)) {
        return;
    }

    // set up the dialog
    FLYFI.trackDialog_trackDict = trackDict;
    var dialog = $(dialogSelector);
    dialog.find('.title').text(trackDict.title);
    dialog.find('.artist').text(trackDict.artist);

    // now show the dialog
    $(dialogLinkSelector).click();
};

FLYFI.updateAddTrackPlaylistList = function(dialog, track, selectCurrentLibraryAsTarget) {
    // set the list of playlists in the 'Add' dialog
    var list = dialog.find('.playlists');
    var newList = list.clone(true);
    newList.empty();
    if ((selectCurrentLibraryAsTarget || !FLYFI.preferences.getFloat(FLYFI.ADD_TARGET_LIBRARY)) && FLYFI.currentPlaylistDict) {
        // Set the current library as the add target if requested or if there is no current target.
        FLYFI.preferences.setFloat(FLYFI.ADD_TARGET_LIBRARY, FLYFI.currentPlaylistDict.libraryID);
    }
    
    var currentTargetLibraryID = FLYFI.preferences.getFloat(FLYFI.ADD_TARGET_LIBRARY);
    var onClick = function(event) { FLYFI.onClick_addTrackLibrary(event, dialog); };
    if (FLYFI.libraryDicts_MyPlaylists.length > 0) {
        newList.append( $('<li><b>My Playlists</b></li>') );
        var l = FLYFI.libraryDicts_MyPlaylists.length;
        for (var i = 0; i < l; ++i) {
            var libraryDict = FLYFI.libraryDicts_MyPlaylists[i];
            if (!libraryDict.writable) {
                continue;
            }
            
            var row = $('<li><a href="#" libraryid=' + libraryDict.libraryID + '>' + libraryDict.name + '</a></li>');
            row.appendTo(newList)
                .find('a').click(onClick);
            if (libraryDict.libraryID == currentTargetLibraryID) {
                FLYFI.doClick_addTrackLibrary(row.find('a'), dialog);
            }
        }
    }
    
    if (!FLYFI.isCustomRadioPlayer() && FLYFI.libraryDicts_MyClouds.length > 0) {
        newList.append( $('<li><b>My Grooves</b></li>') );
        var ll = FLYFI.libraryDicts_MyClouds.length;
        for (var j = 0; j < ll; ++j) {
            var libraryDict2 = FLYFI.libraryDicts_MyClouds[j];
            var row2 = $('<li><a href="#" libraryid=' + libraryDict2.libraryID + '>' + libraryDict2.name + '</a></li>');
            row2.appendTo(newList)
                .find('a').click(onClick);
            if (libraryDict2.libraryID == currentTargetLibraryID) {
                FLYFI.doClick_addTrackLibrary(row2.find('a'), dialog);
            }
        }
    }
    var oldList = list.replaceWith(newList);
    oldList = null;
};
FLYFI.onClick_addTrackLibrary = function (event, dialog) { 
    event.preventDefault();
    FLYFI.doClick_addTrackLibrary($(event.target), dialog);
};
FLYFI.doClick_addTrackLibrary = function (link, dialog) { 
    dialog.find('.targetPlaylist').text(link.text());
    dialog.find('.ok').show();
    dialog.find('.cancel').show();
    FLYFI.preferences.setFloat(FLYFI.ADD_TARGET_LIBRARY, link.attr('libraryid'));
    dialog.find('.playlists a').removeClass('active');
    link.addClass('active');
};

FLYFI.onClickOK_AddKeeper = function(event, dialog) {
    event.preventDefault();
    
    var playlistNameField = dialog.find('.newPlaylistName');
    if (playlistNameField.val() != 'My Playlist') {
        FLYFI.onClickCreate_AddKeeper(event, dialog);
        return;
    }
    var currentTargetLibraryID = FLYFI.preferences.getFloat(FLYFI.ADD_TARGET_LIBRARY);
    if (currentTargetLibraryID === null) {
        alert('Please choose cloud or click the Create button');
        return;
    }
    if (FLYFI.isCustomRadioPlayer() && !FLYFI.playlistInRadioPlayer(currentTargetLibraryID)) {
        if (confirm('The playlist is not yet part of the widget. Add this playlist to the widget?')) {
            FLYFI.addPlaylistToRadioPlayer(currentTargetLibraryID);
        } else {
            return;
        }
    }

    FLYFI._doAddKeeper(currentTargetLibraryID, true);
    tb_remove(); // close the dialog
};

FLYFI._doAddKeeper = function(libraryID, playIfNothingPlaying) {
    var isCurrentLibrary = (FLYFI.currentPlaylistDict && libraryID == FLYFI.currentPlaylistDict.libraryID);
    FLYFI.server_voteUp(FLYFI.addDialog_trackDict, libraryID, 
                            isCurrentLibrary ? function(trackDict) {FLYFI.preferences.setTrackForLibrary(libraryID, trackDict.trackID); FLYFI.refreshCloud(); return true;} : null);
    FLYFI.addDialog_trackDict.vote = 1;
    // Make this library the default target of the next add
    FLYFI.preferences.setFloat(FLYFI.ADD_TARGET_LIBRARY, libraryID);
    var dialog = $('#addTrack_dialog_targetDiv');
    var activeLib = dialog.find('.playlists .active');
    if (activeLib) {
        activeLib.removeClass('active');
    }

};

FLYFI.server_add = function(track, libraryid, callback) {
    var url = "/library/" + libraryid + "/append/";
    if (FLYFI.currentPlaylistDict) {
        url += "sourcelibrary/" + FLYFI.currentPlaylistDict.libraryID + '/';
    }
    FLYFI.post_NoResponse(url,
                        {'track_id': track.trackID},
                        function() {
                            if (libraryid == FLYFI.currentPlaylistDict.libraryID) {
                                FLYFI.refreshCloud(callback); // library changed, so update it
                            } else {
                                if (callback) {
                                    callback();
                                }
                            }
                        }
                    );
};

FLYFI.server_voteUp = function(trackDict, libraryid, callback, noVideoVote, isArtistPlayer) {
    // callback gets the trackDict
    // Even if no library send the vote - will be used to manage videos
    
    var url = "/library/" + (!libraryid || libraryid === 0 ? "none" : libraryid) + "/vote_up/";
    if (trackDict.library_id && (trackDict.library_id != libraryid || !trackDict.approved)) {
        url += "sourcelibrary/" + trackDict.library_id + '/';
    }
    // NOTE: The following call will register a video preference at the server as well as a track vote if the video_id is specified.
    //       We only want to register video prferences if the track is actually playing - since if it is not the user has 
    //       probably not vetted the default video.
    var isVideoPlaying = trackDict == FLYFI.playingTrack.trackDict && FLYFI.playingTrack.playing;
    FLYFI.post_NoResponse(url,
                        {'track_id': trackDict.trackID, 'vet_artist' : isArtistPlayer ? true : false,
                         'video_id': (noVideoVote || trackDict.free || !trackDict.videoYouTubeIDs || !isVideoPlaying) ? '' : trackDict.videoYouTubeIDs[trackDict.videoIndex]},
                        function () { var bypassEnsure = false;
                                      if(callback) { bypassEnsure = callback(trackDict); } // Some callbacks do their own refresh
                                      if (!bypassEnsure) { FLYFI.ensureEnoughRecs(libraryid, false); } }
                    );
};

FLYFI.server_voteDown = function(trackDict, libraryid, callback, isArtistPlayer) {
    if (!libraryid && !isArtistPlayer) {    // can't record a vote if no library, so just process it as if it succeeded
        if(callback) { callback(); }
        return;
    }

    // NYI - this call will change the recommendations, so stop the timer until the server responds
    var isVideoPlaying = trackDict == FLYFI.playingTrack.trackDict && FLYFI.playingTrack.playing;
    FLYFI.post_NoResponse("/library/" + ((libraryid && libraryid !== 0) ? libraryid : "none" ) + "/vote_down/",
                        {'track_id': trackDict.trackID, 'vet_artist' : isArtistPlayer ? true : false,
                            'video_id': (trackDict.free || !trackDict.videoYouTubeIDs || !isVideoPlaying) ? '' : trackDict.videoYouTubeIDs[trackDict.videoIndex]},
                        function () { var bypassEnsure = false;
                                      if(callback) { bypassEnsure = callback(); } // Some callbacks do their own refresh
                                      if (!bypassEnsure) { FLYFI.ensureEnoughRecs(libraryid, false); } }
                    );
};

FLYFI.onClickCancel_AddKeeper = function() {
    tb_remove(); // close the dialog
};

FLYFI.onClickCreate_AddKeeper = function(event, dialog) {
    event.preventDefault();
    var playlistNameField = dialog.find('.newPlaylistName');
    FLYFI.ensureMyPlaylist( playlistNameField.val(), FLYFI.onCallback_AddKeeper_EnsureMyPlaylist);
};
FLYFI.onCallback_AddKeeper_EnsureMyPlaylist = function(libraryDict) {
    FLYFI._doAddKeeper(libraryDict.libraryID, true);
    tb_remove(); // close the dialog
};

FLYFI.onClickOK_BuyTrack = function(event, dialogSelector) {
    event.preventDefault();
    var dialog = $(dialogSelector);
    var vendor = FLYFI.preferences.getString('buy-vendor', '');
    if (!vendor) {
        vendor = dialog.find('.buyTrack_vendors li:first]').attr('vendor');
        FLYFI.preferences.setString('buy-vendor', vendor);
    }
    dialog.find('.buyTrack_vendors li[vendor=' + vendor + ']').click();
};

FLYFI.onClick_LI_BuyTrack = function(event, li, dialogSelector) {
    event.preventDefault();
    var vendor = $(li).attr('vendor');
    var libraryID = FLYFI.showBuyTrackDialog_libraryID;
    if (typeof(libraryID) == 'undefined') {
        libraryID = 0;
    }
    FLYFI.preferences.setString('buy-vendor', vendor);
    var dialog = $(dialogSelector);
    dialog.find('.buyTrack_vendors li[vendor!=' + vendor + ']').removeClass('on');
    dialog.find('.buyTrack_vendors li[vendor=' + vendor + ']').addClass('on');
    window.open('/' + window.level + '/library/' + libraryID + '/track/' + FLYFI.trackDialog_trackDict.trackID + '/buy/vendor/' + vendor + '/', 'flyfiBuyWindow');
    tb_remove(); // close the dialog
};


FLYFI.onClickOK_VoteUp = function(event) {
    if ($('#voteUp_dialog .dontshow:checked, #voteUp_changing_dialog .dontshow:checked').length > 0) {
        FLYFI.preferences.setBoolean('dontshow-voteup', true);
    }
    tb_remove();
};

FLYFI.onClickOK_VoteDown = function(event) {
    if ($('#voteDown_dialog .dontshow:checked, #voteDown_changing_dialog .dontshow:checked').length > 0) {
        FLYFI.preferences.setBoolean('dontshow-votedown', true);
    }
    tb_remove();
};

// server

FLYFI.lastReportedPlay_TrackID = null;  // the TrackID of the last track play reported to the server (so we don't report the same one twice)
FLYFI.lastReportedDownload_TrackID = null;  // the TrackID of the last track download reported to the server (so we don't report the same one twice)

FLYFI.server_ReportPlay = function(trackID, libraryID) {
    if (trackID == FLYFI.lastReportedPlay_TrackID) {
        return; // don't report the same track twice in a row
    }
    FLYFI.lastReportedPlay_TrackID = trackID;
    var participantID = "";
    if (FLYFI.current_user) {
        participantID = FLYFI.current_user.id;
    }
    FLYFI.post_NoResponse("/log/play/" + participantID + "/" + trackID + "/" + (libraryID ? libraryID + "/" : ""),
                                {},
                                function() {
                                    FLYFI.trackAjaxCall("loggedPlay");
                                },
                                FLYFI.ignorePostError);
};

FLYFI.server_ReportDownload = function(trackID, libraryID) {
    if (trackID == FLYFI.lastReportedDownload_TrackID) {
        return; // don't report the same track twice in a row
    }
    FLYFI.lastReportedDownload_TrackID = trackID;
    var participantID = "";
    if (FLYFI.current_user) {
        participantID = FLYFI.current_user.id;
    }
    FLYFI.post_NoResponse("/log/download/" + participantID + "/" + trackID + "/" + (libraryID ? libraryID + "/" : ""), 
                            {},
                            function() {
                                FLYFI.trackAjaxCall("loggedDownload");
                            },
                            function(request, textStatus, errorThrown) { FLYFI.lastReportedDownload_TrackID = null;
                                                                         FLYFI.consoleLog_FireFox('>>>>> ERROR in logging download for track: ' + trackID + ': status=' + textStatus + '; error=' + errorThrown + '; request=' + request);
                                                                         }
                        );
};

$(document).ready(function() {
    var addTrackDialog = $('#addTrack_dialog');
    addTrackDialog.find('.ok').click(function(event) { FLYFI.onClickOK_AddKeeper(event, addTrackDialog); } );
    addTrackDialog.find('.create').click(function(event) { FLYFI.onClickCreate_AddKeeper(event, addTrackDialog); } );
    addTrackDialog.find('.cancel').click(FLYFI.onClickCancel_AddKeeper);
    addTrackDialog.find('.addKeeper_dialog_NewCloudNameForm').submit(function(event) { FLYFI.onClickCreate_AddKeeper(event, addTrackDialog); });
    
    var buyTrackDialog = $('#buyTrack_dialog');
    buyTrackDialog.find('.ok').click(function (event) { FLYFI.onClickOK_BuyTrack(event, '#buyTrack_dialog'); } );
    buyTrackDialog.find('.buyTrack_vendors li').click(function (event) { FLYFI.onClick_LI_BuyTrack(event, this, '#buyTrack_dialog'); } );
    
    $('#voteUp_dialog .ok, #voteUp_changing_dialog .ok').click(FLYFI.onClickOK_VoteUp);
    $('#voteDown_dialog .ok, #voteDown_changing_dialog .ok').click(FLYFI.onClickOK_VoteDown);
    $('body').mouseup(FLYFI.onMouseUp_Body_TrackCell);
});


