<?xml version="1.0" encoding="UTF-8"?>
<Module>
  <ModulePrefs title="My Journal" description="Display the Owner's hi5 Journal" title_url="http://www.hi5.com" author="Shawn Shen" author_email="sxshen@gmail.com" author_affiliation="aa" author_location="Mountain View, CA">
    <Require feature="dynamic-height"/>
    <Require feature="opensocial-0.6"/>
  </ModulePrefs>
  <Content type="html">
    <![CDATA[

      <!-- Text fields go here -->
      <div id="journal" style="margin: 4px">
        <div id="user"></div>
        <div id="body"></div>
      </div>

      <script>

        var Hi5AuthToken = null;

        /**
         * Store the Hi5AuthToken and load the viewer when the page loads
         */
        var init = function() {

          var env = opensocial.getEnvironment();
          var p = env.getParams();
          Hi5AuthToken = p['Hi5AuthToken'];

          loadUsers();
        }

        // Call the init function onLoad
        _IG_RegisterOnloadHandler(init);

        /**
         * Fetch the Viewer with an opensocial dataRequest
         */
        function loadUsers() {
          var req = opensocial.newDataRequest();
          req.add(req.newFetchPersonRequest('OWNER'), 'owner');
          req.add(req.newFetchPersonRequest('VIEWER'), 'viewer');
          req.send(onLoadUsers);
        }

        /**
         * After the Owner is loaded, fetch their journal from the hi5 api server
         * _IG_FetchContent and _IG_FetchXmlContent should be used to fetch external
         * data until opensocial.makeRequest is available
         */
        function onLoadUsers(dataResponse) {
          var owner = dataResponse.get('owner').getData();
          var viewer = dataResponse.get('viewer').getData();
          var ownerId = owner.getField(opensocial.Person.Field.ID);

          // Create HTML for the user summary
          var userHtml = '<a href="' + owner.getField(opensocial.Person.Field.PROFILE_URL) + '"><img border="0" width="50" src="' + owner.getField('thumbnailUrl') + '"/></a> <a href="' + owner.getField('profileUrl') + '">' + owner.getField(opensocial.Person.Field.NAME) + '</a>: ' + owner.getField(opensocial.Person.Field.AGE) + ',' + owner.getField(opensocial.Person.Field.GENDER);
          document.getElementById('user').innerHTML = userHtml;

          // Fetch the journal feed and parse it
          _IG_FetchXmlContent('http://api.hi5.com/rest/feed/journal/'+ownerId, function (xmlDoc) {
            parseAtom(xmlDoc);
          });

          // Request an activity stream entry
          createActivity(viewer, owner);
        }

        /**
         * Request an activity stream entry, with links to owner and viewer and application canvas page
         */
        function createActivity(viewer, owner) {
          var activity = opensocial.newActivity("<a href='" + viewer.getField(opensocial.Person.Field.PROFILE_URL) + "'>" + viewer.getField(opensocial.Person.Field.NAME) + "</a> viewed <a href='" + owner.getField(opensocial.Person.Field.PROFILE_URL) + "'>" + owner.getField(opensocial.Person.Field.NAME) + "'s</a> journal with the <a href='/friend/apps/displayAppCanvas.do?appId=192&userid=" + owner.getField(opensocial.Person.Field.ID) + "'>MyJournal</a> application");
          activity.setField(opensocial.Activity.Field.STREAM_FAVICON_URL, 'http://images.hi5.com/images/icons/_/update_widget.png');

          var priority = opensocial.CreateActivityPriority['HIGH'];
          opensocial.requestCreateActivity(activity, priority);
        }

        /**
         * Naive parser, just get the titles and content and display the journal by setting innerHTML
         * of the 'journal' div created above
         */
        function parseAtom(xmlDoc) {
          var html = "";
          var titles = new Array();;

          // Get titles
          var items = xmlDoc.getElementsByTagName('title');
          for(var i = 0; i < items.length; i++) {
            if(i > 0) {
              var title = items.item(i).firstChild.nodeValue;
              titles[i-1] = title;
            }
          }

          // Get bodies
          items  = xmlDoc.getElementsByTagName('content');
          for(var i = 0; i < items.length; i++) {
            var body = items.item(i).firstChild.nodeValue;
            html += "<div style='margin-bottom:10px;font-weight: bold;'>" + titles[i] + "</div><div style='margin-bottom:10px;>" + body + "</div>";
          }

          // Set html and styles
          document.getElementById("body").innerHTML = html;
          document.getElementById("journal").style.backgroundColor = _args()["appBgColor"];
          document.getElementById("journal").style.backgroundImage = "url(" + _args()["appBgImg"] + ")";
          document.getElementById("journal").style.backgroundPosition = _args()["appBgPos"];
          document.getElementById("journal").style.backgroundRepeat = _args()["appBgRep"];
          document.getElementById("journal").style.color = _args()["appColor"];

          // Call this method to adjust the app's IFrame height if necessary
          _IG_AdjustIFrameHeight();
        }

      </script>

    ]]>

  </Content>
</Module>

