<?xml version="1.0" encoding="UTF-8"?>
<Module>
  <ModulePrefs
    title="The Daily Galaxy"
    description="Application for your Orkut profile that displays the latest stories from The Daily Galaxy - News from planet Earth and beyond, and allows you to share specific stories with your friends through Orkut Updates. The Daily Galaxy is an eclectic text and video presentation of news and original insights on science, space exploration, the environment and technology. The Daily Galaxy is built on the fundamental insight that science and space exploration and its expression in the news, film, video, and events will dominate popular culture in the 21st century - as the Internet has over the last decade of the past century."
    thumbnail="http://www.ljmsite.com/google/orkut/dailygalaxy/dailygalaxy_thumbnail.png"
    screenshot="http://www.ljmsite.com/google/orkut/dailygalaxy/dailygalaxy_screenshot.jpg"
    author="Jerome Mouton"
    author_email="igoogle_gadgets@ljmsite.com"
    author_location="Huntsville, AL, USA"
    author_affiliation="LjmSite"
    author_aboutme="Google API gadget and web application developer, tech project manager in globally dispersed team environment, computer geek on call, etc. Come check me out at LjmSite.com and contact me to discuss gadget projects or opportunities."
    author_link="http://www.ljmsite.com/"
    author_photo="http://www.ljmsite.com/google/gadgets/jerome.png"
  >
  <Require feature="opensocial-0.7" />
  <Require feature="dynamic-height" />
  <Locale lang="en" />
  </ModulePrefs>
<Content type="html">
<![CDATA[

<style type="text/css">
* {
  font-family:Verdana,Arial,sans-serif;
  text-align:left;
  vertical-align:top;
  font-size:12px;
  color:#000000;
  background-color:#ffffff;
}
a {
  color:#02679C;
  text-decoration:none;
}
a:link {
  color:#02679C;
  text-decoration:none;
}
a:visited {
  color:#02679C;
  text-decoration:none;
}
a:hover {
  color:#02679C;
  text-decoration:underline;
}
.smallLink {
  font-size:10px;
}
</style>

<div id="message"></div>
<div id="content"></div>

<script type="text/javascript">

// Global variables to track the success of fetching the feed
var fetchSuccessfull = false;
var titles = Array();
var urls = Array();
var imgs = Array();

function getSubstring(data, pre, post) {
        var val = '';
        if(data) {
          var start = data.indexOf(pre);
          if(start != -1) {
            start += pre.length;
            var data2 = data.substring(start);
            var end = data2.indexOf(post);
            if(end != -1) {
              val = data2.substring(0, end);
            }
          }
        }
        return val;
}

function getWidth() {
        var w;
        if(self.innerHeight) {
                w = self.innerWidth;
        }
        else if(document.documentElement && document.documentElement.clientHeight) {
                w = document.documentElement.clientWidth;
        }
        else if(document.body) {
                w = document.body.clientWidth;
        }
        return w;
}


// Activity stream posting functions
function postActivity(id) {
  document.getElementById("message").innerHTML = "Posting an update, please wait..." ;

  var params = {};
  params[opensocial.Activity.Field.TITLE] = 'read an interesting story on DailyGalaxy.com:';
  params[opensocial.Activity.Field.BODY] = '<table border=0><tr><td><img src="' + imgs[id]
                                         + '" border="0" width="70" alt="' + titles[id] + '" />'
                                         + '</a></td><td><div><a href="' + urls[id]
                                         + '" target="_blank">' + titles[id] + '</a>'
                                         + '</td></tr></table>';
  var activity = opensocial.newActivity(params);
  opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH, callback);
};        

function callback(data) {
  // Show visual clue that the news has been sent
  document.getElementById("message").innerHTML = "Your update to share the DailyGalaxy.com story with your friends has been sent.";

  // and clearing the message after 30 seconds
  setTimeout('document.getElementById("message").innerHTML = "";', 30000);
};

// Presentation functions
function getHtmlOneStory(id, title, url, imageUrl, imageWidth) {
        var storyHtml = '<td><a href="' + url + '" target="_blank">'
                      + '<img src="' + imageUrl + '" border="0" width="' + imageWidth + '" alt="' + title + '" />'
                      + '</a></td><td><div><a href="' + url + '" target="_blank">' + title + '</a></div>'
                      + '<div class="smallLink"> - <a class="smallLink" href="javascript:postActivity(' + id + ');">'
                      + 'share this story</a></div>'
                      + '</td>';

        return storyHtml;
}

function storyFilter(title) {
  if((title.indexOf('Daily Galaxy') != -1) ||
     (title.indexOf('Create Your Own') != -1) ||
     (title.indexOf('Grab the New "Galaxy"') != -1) ||
     (title.indexOf('Announcing "GalaxyExtra!"') != -1) ||
     (title.indexOf('Sign Up for Our') != -1) ||
     (title == '')) {
    return true;
  }
  return false;
}

function displayStories(xml) {
  var entries = xml.getElementsByTagName("entry");
  var storiesHtml = '<table border=0>';

  // Set the thumbnail size to 1/3 of the gadget width, but no bigger than 70 pixels
  var imageWidth = getWidth() / 3;
  if(imageWidth > 70) {
          imageWidth = 70;
  }

  // Determine the number if stories and presentation to display based on the width
  var nbRows = 5;
  var nbCols = 1;
  if(getWidth() > 600) {
    nbCols = 3;
  }
  else if(getWidth() > 400) {
    nbCols = 2;
  }

  var storyId = 0;

  for(var i = 0; i < entries.length && storyId < nbRows*nbCols; i++) {
    var title = '';
    var href = '';
    var img = '';
    var date = '';

    // Get child nodes for the current <entry> note
    var nodeList = entries.item(i).childNodes;

    // Loop through child nodes. Extract data from the text nodes that are
    // the children of the associated title, link, etc.
    for (var j = 0; j < nodeList.length ; j++) {
      var node = nodeList.item(j);

      if(node.nodeName == 'title' && node.firstChild) {
        title = node.firstChild.nodeValue.replace(/"/g, '&quot;');
        title = title.replace(/'/g, '&#39;');
      }
      else if(node.nodeName == 'link') {
        if(node.getAttribute('rel') == 'alternate') {
          href = node.getAttribute('href');
        }
      }
      else if(node.nodeName == 'published' && node.firstChild) {
        date = node.firstChild.nodeValue;
      }
      else if(node.nodeName == 'content' && node.firstChild) {
        img = getSubstring(node.firstChild.nodeValue, 'src="', '"');
      }
    }

    // If the option to filter non-stories is on and the post is not a story, skip
    if(storyFilter(title)) {
      continue;
    }

    // The 'Best of' posts do not have a good thumbnail, so use a default one instead
    if((img == '') || img.indexOf('.swf') != -1 || title.indexOf('Best of The Daily Galaxy') != -1) {
      img = 'http://www.ljmsite.com/google/orkut/dailygalaxy/bestoff.jpg';
    }

    // Get the image cached
    img = gadgets.io.getProxyUrl(img);

    if(nbCols == 1 || storyId % nbCols == 0) {
      storiesHtml += '<tr>';
    }

    titles[storyId] = title;
    urls[storyId] = href;
    imgs[storyId] = img;
    storiesHtml += getHtmlOneStory(storyId, title, href, img, imageWidth);

    storyId++;
    
    if(nbCols == 1 || (storyId ) % nbCols == 0) {
      storiesHtml += '</tr>';
    }

  }

  storiesHtml += '</table>';
  document.getElementById("content").innerHTML = storiesHtml;

  // Adjust height but do it again in 5 seconds in case some image are slow to come
  if(gadgets.window) {
    setTimeout('gadgets.window.adjustHeight();', 5000);
    gadgets.window.adjustHeight();
  }
}

// Top level fetcher which initiate the assynchronous function
function fetchStories() {
  var params = {};
  params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM;
  params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 1800;
	gadgets.io.makeRequest('http://www.dailygalaxy.com/my_weblog/atom.xml', function (response) {
    if(response == null || response.data == null || typeof(response.data) != "object" || response.data.firstChild == null) {
      document.getElementById("content").innerHTML = "<i>An error occured while getting the lastest stories from the Daily Galaxy.<br />Please stand by as we retry...</i>";
    }
    else {
      fetchSuccessfull = true;
      displayStories(response.data);
    }
    return;
  }, params);
}

// Wrapper to the fetchStories function which manage the retries
// every 15 seconds in case makeRequest() fails
function fetchStoriesWrapper() {
  if(!fetchSuccessfull) {
    fetchStories();
    setTimeout('fetchStoriesWrapper()', 15000);
  }
  return;
}

function init() {
  document.getElementById("content").innerHTML = "<i>Getting latest stories...</i>";
  fetchStoriesWrapper();
  //_IG_Analytics("UA-2959282-1", "/iGoogleGadget/1");
  //setTimeout('_IG_Analytics("UA-1189083-1", "/DailyGalaxy/1")', 10000);
}

gadgets.util.registerOnLoadHandler(init);

</script>

]]> 
  </Content>
</Module>
