var PlayerProxy = Class.create({
  initialize: function() {
    // note: this variable is an optimization for multiple actions on the same
    // page. When the user navigates to another page this will go away so it
    // shouldn't be relied on.
    this.popup = null; 
  },

  // Queues a track in the player
  queue_track: function(track_id) {
    this.send_message_to_popup('/music_player?track_id=' + track_id, function(popup) { popup.queue_track('/songs/' + track_id + '.xml'); });
  },

  // Queues a playlist into the player. Refreshes the popup if already open so the player's queue is reloaded.
  queue_playlist: function(playlist_id) {
    this.send_message_to_popup('/music_player?playlist_id=' + playlist_id);
  },

  // Either opens a new popup window to the passed url, or runs the action
  // function in an existing popup window. The action function is passed the
  // popup window object as an argument. Will always load the url into the
  // popup window if action is null.
  send_message_to_popup: function(url, action) {
    if(this.popup == null || this.popup.closed) {
      this.popup = window.open('', 'music_player', 'width=330,height=600,menubar=no,status=no'); // try to recover an existing window
      this.popup.focus();
    } else {
      // this.popup.parent.blur();
      this.popup.focus();
    }

    var popup_is_newly_created = (this.popup.document.URL.indexOf("about") == 0 );
    if (popup_is_newly_created || action == null) {
      this.popup.location = url;
    }
    else {
      action(this.popup);
    }
  }
});

function show_add_to_playlist_dropdown(track_id) {
  var wrapper_id = 'add_to_playlist_wrapper_for_track_' + track_id;

  $(wrapper_id).immediateDescendants().each(function (e) {e.remove();});
  $(wrapper_id).addClassName('hover');
  window.hover_observer.startDelayedActivation($(wrapper_id));

  new Ajax.Updater(wrapper_id, '/playlists/add_to_playlist_dropdown', {parameters: {track_id: track_id}, method: 'get'});

  return false;
}

function toggle_watch_entity(url, method) {
  new Ajax.Request(url, {
    method: method,
    onSuccess: function(transport) {
      $('watch_this').innerHTML = transport.responseText;
    }
  });
  
}


