<?xml version="1.0" encoding="UTF-8"?>
<Module>
  <ModulePrefs title="Hug Me" description="What" title_url="http://www.hi5.com" author="Pauline Amin" author_email="aminoassets@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='main'>
        <div id='give'>
        <form id='gift_form'>
        Give <div id='gifts'></div> to <span id='friends'></span>. <a href="javascript:void(0);" onclick='giveGift();'>Give!</a>
        </form>
        </div>
        <div id='given'></div>
        </div>
      </div>

      <script>

        var Hi5AuthToken = null;
        var givenGifts = {};
        var globalViewer = {};
        var globalFriends = {};

        function postActivity(nut, friend) {
          var options = ['a cashew nut', 'a peanut', 'a hazelnut', 'a red pistachio nut'];

          var title = globalViewer.getDisplayName() + ' gave ' + globalFriends[friend] + ' ' + options[nut];
          var params = {};
          params[opensocial.Activity.Field.TITLE] = title;
          var activity = opensocial.newActivity(params);
          opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH, function() {});
        }


        /**
         * 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();
          loadFriends();

          var url = "http://www.cinsh.com/freehug/images/img_list.php";
          var params = {};
          var postdata_array = {}; 
          postdata_array["t"]="json";
          var postdata = gadgets.io.encodeValues(postdata_array);
          params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
          params[gadgets.io.RequestParameters.POST_DATA]= postdata;
          params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
          makeCachedRequest(url, getGiftImages, params, 0); 

          //makeOptionsMenu();
        }

        // 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);
          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>: ';
          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);
        }

        function loadFriends() {
          var req = opensocial.newDataRequest();
          req.add(req.newFetchPersonRequest('VIEWER'), 'viewer');
          req.add(req.newFetchPeopleRequest('VIEWER_FRIENDS'), 'viewerFriends');
          req.add(req.newFetchPersonAppDataRequest('VIEWER', 'gifts'), 'data');
          req.add(req.newFetchPersonAppDataRequest('VIEWER_FRIENDS', 'gifts'), 'viewerFriendData');
          req.send(onLoadFriends);
        }

        function onLoadFriends(data) {
          var viewer = globalViewer = data.get('viewer').getData();
          var viewerFriends = data.get('viewerFriends').getData();
          var giftData = data.get('data').getData();
          var viewerFriendData = data.get('viewerFriendData').getData();
          var friends = new Array();

          html = new Array();
          html.push('<select id="person">');
          viewerFriends.each(function(person) {
             html.push('<option value="' + person.getId() + '">' + person.getDisplayName() + "</option>");
             friends[person.getId()] = person.getDisplayName();
          });

          html.push('</select>');
          document.getElementById('friends').innerHTML = html.join('');

          globalFriends = friends;
          updateGiftList(viewer, giftData, friends);
          updateReceivedList(viewer, viewerFriendData, viewerFriends);
        }

        function updateGiftList(viewer, data, friends) {
          var json = data[viewer.getId()]['gifts'];

          if (!json) {
            givenGifts = {};
          }
          try {
            givenGifts = gadgets.json.parse(gadgets.util.unescapeString(json));
          } catch (e) {
            givenGifts = {};
          }

          var options = ['a cashew nut', 'a peanut', 'a hazelnut', 'a red pistachio nut'];

          var html = new Array();
          html.push('You have given:');
          html.push('<ul>');
          for (i in givenGifts) {
            if (+(i) > 0) {
             html.push('<li>' + friends[i] + ' received ' + options[givenGifts[i]] + '</li>');
            }
          }
          html.push('</ul>');
          document.getElementById('given').innerHTML = html.join('');
        }

        function updateReceivedList(viewer, data, friends) {
          var viewerId = viewer.getId();
          var options = ['a cashew nut', 'a peanut', 'a hazelnut', 'a red pistachio nut'];

          var html = new Array();
          html.push('You have received:<ul>');
          friends.each(function(person) {
             var personData = data[person.getId()];
             if (personData) {
                var json = data[person.getId()]['gifts'];

                var gifts = {}
                if (!json) {
                   gifts = {};
                }
                try {
                   gifts = gadgets.json.parse(gadgets.util.unescapeString(json));
                } catch (e) {
                   gifts = {};
                }

                for (i in gifts) {
                   if (+(i) > 0 && i == viewerId) {
                     html.push('<li>' + options[gifts[i]] + ' from ' + person.getDisplayName() + '</li>');
                   }
                }
             }
           });
           html.push('</ul>');
           document.getElementById('received').innerHTML = html.join('');
        }

        function makeOptionsMenu() {
          var options = ['a cashew nut', 'a peanut', 'a hazelnut', 'a red pistachio nut'];

          var html = new Array();
          html.push('<select id="nut">');
          for (var i = 0; i < options.length; i++) {
            html.push('<option value="' + i + '">' + options[i] + '</option>');
          }
          html.push('</select>');
          document.getElementById('gifts').innerHTML = html.join('');
        }


        function giveGift() {
          var nut = document.getElementById('nut').value;
          var friend = document.getElementById('person').value;

          givenGifts[friend] = nut;
          var json = gadgets.json.stringify(givenGifts);

          var req = opensocial.newDataRequest();
          req.add(req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER, 'gifts', json));
          req.add(req.newFetchPersonRequest('VIEWER'), 'viewer');
          req.add(req.newFetchPeopleRequest('VIEWER_FRIENDS'), 'viewerFriends');
          req.add(req.newFetchPersonAppDataRequest('VIEWER', 'gifts'), 'data');
          req.add(req.newFetchPersonAppDataRequest('VIEWER_FRIENDS', 'gifts'), 'viewerFriendData');
          req.send(onLoadFriends);

//var messageParams = {}; 
//messageParams[opensocial.Message.Field.TYPE] = opensocial.Message.Type.EMAIL; 
//messageParams[opensocial.Message.Field.TITLE = 'Subject of email'; 
//var message = opensocial.newMessage('Body of email', params); 
//opensocial.requestSendMessage(opensocial.DataRequest.PersonId.OWNER, message);
//opensocial.requestSendMessage(opensocial.[wiki:DataRequest].[wiki:PersonId].OWNER, message);


          //postActivity(nut, friend);

        }

        /**
         * 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();
        }

        function makeCachedRequest(url, response, params, refreshInterval) {
          var ts = new Date().getTime();
          var sep = "?";
          if (refreshInterval && refreshInterval > 0) {
             ts = Math.floor(ts / (refreshInterval * 1000));
          }
          if (url.indexOf("?") > -1) {
             sep = "&";
          }
          url = [ url, sep, "nocache=", ts ].join("");
          gadgets.io.makeRequest(url, response, params);
        }

        function getGiftImages(obj) {
          //alert(obj.data[0] + " " + obj.data[2]);
          var imgs = obj.data;
          //alert(imgs.length);

          var html = new Array();
          //for (var i = 0; i < obj.data.length; i++) {
          html.push('<div style="width:800px; margin:5px; padding:5px;">');
          for (var i = 0; i < 50; i++) {
            //alert('<img src="http://www.cinsh.com/freehug/images/' + obj.data[i] + '">');
            html.push('<div style="float:left;">');
            html.push('<img src="http://www.cinsh.com/freehug/images/' + obj.data[i] + '"><br>');
            html.push('<input type="radio" name="gid" value="' + i + '">' + obj.data[i]);
            html.push('</div>');
          }
          html.push('</div>');
          document.getElementById('gifts').innerHTML = html.join('');
        }

      </script>

    ]]>

  </Content>
</Module>

