// jQuery function to display System Notices from EE notice management system.
// The GloVis main page has a messageIndicator span if there are messages
// and a messageDisplay div that displays the messages.
// We use buttons so they are keyboard-navigable. (Would anchors look cleaner?)
// Modified coding standard - 2 spaces for indent (too many levels otherwise)

// Main page must include jQuery, jQueryUI, jQueryUI CSS, and GloVis CSS.

(function($){
  var noticeUrl = 'https://earthexplorer.usgs.gov/notification/getall?callback=?';
  var gotResponse = 0; // gets updated by getJSON's callback

  // Driver function invoked by main page
  $.fn.displayNotices = function() {
      this.getNotices();     // Sets gotResponse if getJSON gets any response
                             // and populates messageIndicator & messageDisplay
      // Wait a moment for getJSON's callback to be invoked - if it
      // has not set gotResponse after two seconds, display an error
      setTimeout(this.defaultIfNoResponse, 2000);
      // (If the callback is later invoked, it will overwrite the error message)
  }

  // If we have not gotten a reply from getJSON, display an error message
  $.fn.defaultIfNoResponse = function() {
      //alert("in defaultIfNoResponse, gotResponse is: " + gotResponse);
      if (gotResponse == 0) {
          $('#messageIndicator').html('System notices unavailable.'
              + ' Shopping Cart may not function properly.');
      }
  };

  // Contact the EE notification system for any System Notices to display
  // In the callback, set gotResponse and populate messageIndicator
  // and messageDisplay and set up show/hide features
  $.fn.getNotices = function() {
    $.getJSON(noticeUrl, { node : 'glovis' }, function(data, textStatus) {
      gotResponse = 1;
      //alert("inside getJSON's callback, gotResponse is " + gotResponse);
      if (textStatus == 'success') {
        if (data.items && data.items.length) {
          var criticalCount = 0;
          var newMessageCount = 0;
          var aWeekAgo = new Date(); // starts with today
          aWeekAgo.setDate(aWeekAgo.getDate() - 7);

          // Add all the messages, flagging any 'Warning' messages as Critical
          $.each(data.items, function(i, item) {
            var message = item;
            var msgId = "msg" + i;
            var msgDate = new Date(message.NOTE_STARTDATE); // format MM/dd/yyyy
            if (msgDate > aWeekAgo) {
              newMessageCount++;
            }
            var msgCriticalNote = '';
            if (message.NOTE_TYPE == 'Warning') {
                criticalCount++;
                msgCriticalNote = 'CRITICAL MESSAGE: ';
            }
            $('#messageDisplay').append('<div id="' + msgId + '">'
              + '<button>' + msgCriticalNote + message.NOTE_TITLE + '</button>'
              + '<p>' + message.NOTE_STARTDATE + ' - ' + message.NOTE_MESSAGE
              + '<br /></p></div>');
          });

          // Hide message paragraphs and make their header-buttons toggle them
          $("#messageDisplay p").hide();
          $("#messageDisplay button").button(); // make them jQueryUI Buttons
          $("#messageDisplay button").click(function() {
            $(this).next().fadeToggle('fast');
            return false;
          });

          // Make sure any links in the messages open in another page
          // Otherwise when browser comes back to this page, it resets applet
          $("#messageDisplay a").each(function(i) {
            if (!$(this).attr("target")) {
              $(this).attr("target", "_blank");
            }
          });

          // Add something to the page for the user to click to show messages
          var messageLabel = 'System Notices (' + data.items.length + ')';
          if (newMessageCount && (newMessageCount < data.items.length)) {
            messageLabel += ', ' + newMessageCount + ' New';
          }
          if (criticalCount) {
            messageLabel += ', ' + criticalCount + ' Critical';
          }
          $('#messageIndicator').html('<button class="glovisbutton1">'
            + messageLabel + '</button>');

          // Make the messageIndicator button bring up the notices display
          $('#messageIndicator button').button(); // make it a jQueryUI Button
          $('#messageIndicator button').click(function() {
            $('#messageDisplay').fadeToggle('fast');
            return false;
          });
        }
        else {
          // Successful reply but no messages to display
          $('#messageIndicator').html('');
        }
      }
      else {
        // Did not get a 'success' reply from EE notification system
        $('#messageIndicator').html('<span class="glovistitle">System '
          + 'Notices unavailable. '
          + 'Shopping Cart may not function properly.</span>');
      }
    }); // end of getJSON callback definition
    //alert("after getJSON (before callback), gotResponse is " + gotResponse);
  };
})(jQuery);


