// Retrieve the currently selected gallery from the cdm workspace drop-down list
function getWorkspaceGallery() {
  return $('#cdm_workspace_gallery :selected').val();
}

function showSpinner() {
  $('#ajax-spinner').fadeIn(100);
}

function hideSpinner() {
  $('#ajax-spinner').fadeOut(400);
}

// Add a single item to the favorites
function addItemFav(the_collection, the_id) {
  showSpinner();
  $.post("/cdm4/extensions/add_to_my_workspace.php", {collection:the_collection, cdm_id:the_id, gallery:getWorkspaceGallery()},
    function(data, textStatus){
      if (textStatus == 'success') {
        refreshFavorites();
      }
      hideSpinner();
      alert(data);
    });
}

// Add multiple items to the favorites
function addItemsFav(form) {
  var the_collections = new Array();
  var the_ids = new Array();

  $(':checkbox:checked').map(function() {
    var parts = $(this).val().split('|');
    the_collections.push(parts[0]);
    the_ids.push(parts[1]);
  })
  
  if (the_ids.length > 0) {
    showSpinner();

    $.post("/cdm4/extensions/add_to_my_workspace.php", {collections:the_collections.toString(), cdm_ids:the_ids.toString(), gallery:getWorkspaceGallery()},
      function(data, textStatus){
        if (textStatus == 'success') {
          $('input:checked').click();
          refreshFavorites();
        }
        hideSpinner();
        alert(data);
      });
  }
}

// Add a single page of a compound object to the favorites
function addPageFav() {
  addItemFav(PageCisoRoot(), citationUrl().substring(','))
}

var favoritesWindow = '';

// Open the favorites window. Code from http://www.quirksmode.org/js/croswin.html
function openFavorites(url) {
  // Check to see if the window is already open
	if (!favoritesWindow.closed && favoritesWindow.location) {
	  // If it's open, change the page
		favoritesWindow.location.href = url;
	} else {
	  // If it's not open, open it
		favoritesWindow = window.open('/cdm4/extensions/login.php', 'cdm_workspace');
		// Makes Netscape happy
		if (!favoritesWindow.opener) favoritesWindow.opener = self;
	}
	// Switch to the new window if we're not already there
	if (window.focus) favoritesWindow.focus();
}

// Refresh the favorites window
function refreshFavorites() {
  openFavorites('http://cdm-workspace.reed.edu/workspace');
}

// Open a window with a full size view of the given image
function openFullSizeView(alias, pointer) {
  // Open the window
	fullSizeWindow = window.open('/cdm4/extensions/full_size.php?CISOROOT=' + alias + '&CISOPTR=' + pointer, 'cdm_full_size');
	// Makes Netscape happy
	if (!fullSizeWindow.opener) fullSizeWindow.opener = self;
	// Switch to the new window if we're not already there
	if (window.focus) fullSizeWindow.focus();
}