/*
 * JavaScript code to support the GAIA summary browser.
 *
 * This file should contain only code to support the GAI "summary
 * browser A". Core code to support any implmementation should be
 * included in gaia_viewer.js.
 *
 */


// Provide a link to the current page
function updateLinkToThisPage() {
  var elem = document.getElementById('link-to-this-page');
  if (!elem)
    return false;
  
  elem.style.visibility = "visible";
  elem.href = "?" + gaiaViewer.stateToQueryString();
}

function updatePageTitle() {
  gaiaViewer.windowlist.viewer.document.title
    = gaiaViewer.state.time.UTCstrftime('GAIA: %Y-%m-%d');
}

function paletteOnClick (elem) {
  var p = gaiaWS.getPaletteByDbid(elem.value);
  if (!p) {
    console.warn('Unknown palette DBID: ' + elem.value);
    return false;
  }
  
  gaiaViewer.updateState({"palette": p});
  return true;
}


function updateCredits (stateChange) {
  var cdiv = gaiaViewer.windowlist.viewer.document.getElementById("credits-div");
  if (!cdiv)
    return false;

  if (stateChange['mode']) {
    switch (stateChange.mode) {
    case "overview":
      cdiv.style.display = "none";
      break;
      
    case "detailedView":
      cdiv.style.display = "block";
      break;
      
    default:
      console.warn("Unknown mode: " + gaiaViewer.state.mode);
      break;
    }
  }

  if (stateChange['selectedChannel']) {
    doc = gaiaViewer.windowlist.viewer.document;
    gaiaViewer.removeAllDescendents(cdiv);
    
    cdiv.appendChild(doc.createTextNode(gaiaViewer.state.selectedChannel.getLabel() + ' credits'));
    cdiv.appendChild(gaiaViewer.state.selectedChannel.getProject().getCreditsTable(doc));
    
  }
  
  return true;
}

// Initialise the webpage. Do this only after the webpage which
// included gaia_viewer.js has finished loading.
function bodyOnLoad () {
  // Initialise the web services
  gaiaWS.init();
  gaiaViewer.init();

  // Create a date control
  var dcOpts = { 
    "utc": true,
    "immediateUpdate": false,
    "callback": function (t) { gaiaViewer.updateState({"time": t.getDate()}) },
    "date": gaiaViewer.state.time,
    "earliestDate": gaiaDate.getUTCStartOfDay(gaiaWS.earliestDate),
    "latestDate": gaiaDate.getUTCTomorrow(),
    "disabled": true
  };
  
  var dc = new gaiaDate.dateControl(dcOpts);

  // Add the date controls.
  document.getElementById('date-year').appendChild(dc.yearControl());
  document.getElementById('date-month').appendChild(dc.monthControl());
  document.getElementById('date-dom').appendChild(dc.domControl());
  document.getElementById('date-doy').appendChild(dc.doyControl("%03d"));
  document.getElementById('date-hour').appendChild(dc.hourControl());
  document.getElementById('date-minute').appendChild(dc.minuteControl());
  // document.getElementById('date-second').appendChild(dc.secondControl());

  document.getElementById('date-prev-day').appendChild(dc.incrementControl('-1 day', -86400e3, true));
  document.getElementById('date-next-day').appendChild(dc.incrementControl('+1 day', +86400e3, true));
  document.getElementById('date-prev-5minute').appendChild(dc.incrementControl('-5', -300e3, true));
  document.getElementById('date-next-5minute').appendChild(dc.incrementControl('+5', +300e3, true));
  document.getElementById('date-prev-minute').appendChild(dc.incrementControl('-1', -60e3, true));
  document.getElementById('date-next-minute').appendChild(dc.incrementControl('+1', +60e3, true));
  document.getElementById('date-go').appendChild(dc.submitControl('Go'));

  // Create the project control
  var projContainer = document.getElementById("project-container");
  var projControl = gaiaViewer.projectControl(document);
  projControl.onclick = function() { 
    gaiaViewer.projectControlOnChange(this); };
  projContainer.appendChild(projControl);
  gaiaViewer.registerCallback(window,
			      function () {
				gaiaViewer.projectControlRefresh(projControl, gaiaViewer.state.channels); },
			      ["channels"], 
			      "gaiaViewer.projectControlRefresh");
  
 
  // Create the palette controls
  var palContainer = document.getElementById("palette-container");
  var pal = gaiaViewer.getPaletteButtons(document);
  
  // Set callbacks and insert buttons the container. Space with &nbsp;
  for (var i = 0; i < pal.length; ++i) {
    pal[i].onclick = function () { return paletteOnClick(this); };
    if (i)
      palContainer.appendChild(document.createTextNode("\u00a0")); // &nbsp;
    palContainer.appendChild(pal[i]);
  }



  // Create the structure for the overview mode
  // gaiaViewer.createOverviewStructure();

  gaiaViewer.createOverviewStructure();
  gaiaViewer.createDetailedStructure();
  
  // register the callbacks which are associated with page elements
  var updateDateControl 
    = function () {dc.setDate(gaiaViewer.state.time, false); };
  gaiaViewer.registerCallback(window,
			      updateDateControl, ["time"], 
			      "updateDateControl");
  gaiaViewer.registerCallback(window,
			      gaiaViewer.gaiaModeCB, [ "mode" ],
			      "gaiaViewer.gaiaModeCB");
  gaiaViewer.registerCallback(window,
			      gaiaViewer.chooseProjectCB, [ "channels" ],
			      "gaiaViewer.chooseProjectCB");
  gaiaViewer.registerCallback(window,
			      updateLinkToThisPage, [ ],
			      "updateLinkToThisPage");
  gaiaViewer.registerCallback(window,
			      updatePageTitle, [ "date" ],
			      "updatePageTitle");
  
  gaiaViewer.registerCallback(window,
			      gaiaViewer.refreshOverviewContentCB,
			      [ "date", "channels", "palette", "orientation",
				"channelOrder", "mode" ], 
			      "gaiaViewer.refreshOverviewContentCB");
  gaiaViewer.registerCallback(window,
			      gaiaViewer.refreshDetailedViewContentCB,
			      [ "time", "channels", "palette", "orientation",
				"mode"], 
			      "gaiaViewer.refreshDetailedViewContentCB");
  gaiaViewer.registerCallback(window,
			      updateCredits,
			      [ "mode", "selectedChannel" ],
			      "updateCredits");

  // Register a callback to do speculative downloading of data
  // availability. This is least important so should be put last
  gaiaViewer.registerCallback(window,
			      function () { 
				gaiaViewer.prefetchDataAvailability(200) }, 
			      [ "date" ], 
			      'gaiaViewer.prefetchDataAvailability');

  
  // Enable the controls
  dc.setDisabled(false);

  // force everything to be refreshed
  gaiaViewer.updateState(gaiaViewer.state);
  return true;
};

function bodyOnUnload () {
  // Clear up when the viewer is closed

  // Close toolboxes
  for (var win in gaiaViewer.gaiaToolbox.windowlist) {
    if (!gaiaViewer.gaiaToolbox.windowlist[win].closed)
      gaiaViewer.gaiaToolbox.windowlist[win].close();
  }
  
  // Close toolbox window
  if (gaiaViewer.toolboxWindow && !gaiaViewer.toolboxWindow.closed)
    gaiaViewer.toolboxWindow.close();
  return true;
};


