<?xml version="1.0" encoding="UTF-8" ?>
<Module>
	<!--
		This module needs to be rendered inline because it requires access to the Google SID cookie in order to access
		information from the Google Reader Application.

		It also needs to be run on the www.google.com/ domain (not www.google.com.au/ig for instance) for the same reason.
	-->
	<ModulePrefs title="Reader (Beta)"
  			title_url="http://reader.google.com"
  			description="Module to display entries from Google Reader"
  			directory_title="Module for Google Reader"
  			author="Nick Lothian"
  			author_email="nicklothian.feedback+readermodule@gmail.com"
  			author_affiliation="www.mackmo.com/nick/blog/"
  			author_location="Adelaide, Australia"
  			render_inline="optional"
  			screenshot="http://www.mackmo.com/ig/reader/1.0/ig-reader-dir.png"
  			scrolling="true"  />
	<UserPref name="sortOrder" display_name="Sort By" default_value="DATE" datatype="enum" >
	   <EnumValue display_value="Date" value="DATE" />
	   <EnumValue display_value="Relevance" value="REL" />
	</UserPref>
	<UserPref name="numEntriesToDisplay" display_name="Number of entries to display" default_value="5" datatype="enum" >
	   <EnumValue value="1" />
	   <EnumValue value="2" />
	   <EnumValue value="3" />
	   <EnumValue value="4" />
	   <EnumValue value="5" />
	   <EnumValue value="6" />
	   <EnumValue value="7" />
	   <EnumValue value="8" />
	   <EnumValue value="9" />
	   <EnumValue value="10" />
	</UserPref>
	<UserPref name="markAsRead" display_name="Mark Items Read When Viewed?" datatype="bool" default_value="true" />
	<Content type="html">
     <![CDATA[
     	<script src="http://www.mackmo.com/includes/fixed/fixed.js" type="text/javascript"></script>

		<style type="text/css">
			.content__MODULE_ID__ {
				border: none;
				display: none;
				width: 99%;
				overflow: auto;
				padding-top: 1px;
				visibility: hidden;
			}

			.short-summary__MODULE_ID__ {
				border: none;
				display: block;
				width: 99%;
				overflow: auto;
				padding-top: 1px;
			}

			.entry__MODULE_ID__ {
				padding-bottom: 2px;
			}

			a.titleLink__MODULE_ID__ {
				font-weight: bold;
			}

			a.titleLink-read__MODULE_ID__ {
				font-weight: normal;
			}


			a.originalLink {
				color: green;
			}

			.source__MODULE_ID__ {
				color: #6f6f6f;
			}

			.message__MODULE_ID__ {
				display: none;
				font-size: smaller;
				margin-top: 5px;
				padding: 2px;
				border: thin solid black;
				background-color: #FFCCCC;
			}

			#nodisplay__MODULE_ID__ {
				width: 99%;
				height: 250px;
				text-align: center;
				padding-top: 30px;
			}

			#readerbox__MODULE_ID__ {
				position: fixed;
				left: 200px;
				top: 150px;
				width: 300px;
				height: 200px;
				background-color: #dddddd;
				border: solid 1px #000000;
				z-index:10;
				display: none;
			}

			#readerContents__MODULE_ID__ {
				overflow: scroll;
				padding: 2px;
				height: 99%;
				width: 99%;
				text-align: left;
				font-size:82%;
			}

		</style>

		<script src="http://www.mackmo.com/includes/scriptaculous-js-1.5.1/lib/prototype.js" type="text/javascript"></script>
		<script src="http://www.mackmo.com/includes/scriptaculous-js-1.5.1/src/scriptaculous.js" type="text/javascript"></script>

		<script>

		var _MSG_NO_TOKEN__MODULE_ID__ = "Due to a problem communicating with the server, entries will not be marked as read when viewed.";
		var _MSG_WRONG_BROWSER__MODULE_ID__ = "Your browser is not compatible with this module.";

		var entryCount__MODULE_ID__;
		var uid__MODULE_ID__ = null;
		var commandToken__MODULE_ID__ = null;
		var errorMsg__MODULE_ID__ = null;

		var subscriptions__MODULE_ID__ = null;
		var subsLoaded__MODULE_ID__ = false;

		var feedEntries__MODULE_ID__ = null;

		function getXMLHttpRequest__MODULE_ID__() {
			var xmlhttp = null
			if (window.XMLHttpRequest) {
				xmlhttp = new XMLHttpRequest();
			} else if (window.ActiveXObject) {
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}

			if (xmlhttp != null) {
				return xmlhttp;
			} else {
				window.errorMsg__MODULE_ID__ = _MSG_WRONG_BROWSER__MODULE_ID__;
				throw new Exception(_MSG_WRONG_BROWSER__MODULE_ID__);
			}
		}

		function clearElement__MODULE_ID__(targetNode) {
			var children = targetNode.childNodes;
			for (var i=0; i < children.length; i++) {
				targetNode.removeChild(children[i]);
			}
			targetNode.innerHTML ="";

		}

		function displayEntry__MODULE_ID__(entryToDisplayNum, entryID, googleLink) {
			var prefs = new _IG_Prefs(__MODULE_ID__);
			var markAsRead = prefs.getBool("markAsRead");

			for(var i=0; i < entryCount; i++) {
				if (i == entryToDisplayNum) {
					// show this entry

					_gel("l" + i).setAttribute("href", "javascript:hideEntry__MODULE_ID__('" + i + "', '" + entryID + "', '" + googleLink + "');");
					_gel("l" + i).className = "titleLink-read__MODULE_ID__";

					_gel("readerContents__MODULE_ID__").innerHTML = window.feedEntries__MODULE_ID__[entryID].content;

					var title = "";
					if (window.feedEntries__MODULE_ID__[entryID].source) {
						title = window.feedEntries__MODULE_ID__[entryID].source + ": " + window.feedEntries__MODULE_ID__[entryID].title;
					} else {
						title = window.feedEntries__MODULE_ID__[entryID].title;
					}
					title = "<a href='" + window.feedEntries__MODULE_ID__[entryID].originalLink + "'>" + title + "</a>";
					_gel("readerTitle__MODULE_ID__").innerHTML = title;

					_gel("readerbox__MODULE_ID__").style.display="block";

					if (markAsRead && (window.commandToken__MODULE_ID__ != null)) {
						//var xmlhttp = new XMLHttpRequest();
						var xmlhttp = getXMLHttpRequest__MODULE_ID__();
						xmlhttp.open("POST", "http://www.google.com/reader/api/0/edit-tag",true);
						xmlhttp.onreadystatechange=function() {
							//alert("Marked as read. Status = " + xmlhttp.status);
						}
						var readTag = encodeURIComponent("user/-/state/com.google/read");
						var unreadTag = encodeURIComponent("user/-/state/com.google/kept-unread");

						xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
						xmlhttp.send("s=" + encodeURIComponent(googleLink) + "&i=" + encodeURIComponent(entryID) + "&ac=edit-tags&a=" + readTag + "&r=" + unreadTag + "&T=" + window.commandToken__MODULE_ID__);
					}
				} else {
					// hide this entry
					//_gel("readerbox__MODULE_ID__").style.display="none";
				}
			}
		}

		function hideEntry__MODULE_ID__(entryToDisplayNum, entryID, googleLink) {
			_gel("l" + entryToDisplayNum).setAttribute("href", "javascript:displayEntry__MODULE_ID__('" + entryToDisplayNum + "', '" + entryID + "', '" + googleLink + "');");
			_gel("readerbox__MODULE_ID__").style.display="none";
		}

		function getToken__MODULE_ID__() {
			// get the CommandToken

			var xmlhttp = getXMLHttpRequest__MODULE_ID__();
			xmlhttp.open("GET", "http://www.google.com/reader/api/0/token",true);
			xmlhttp.setRequestHeader('Cache-Control','no-cache, must-revalidate');
			xmlhttp.setRequestHeader('Pragma','no-cache');
			xmlhttp.onreadystatechange=function() {
				if (xmlhttp.readyState==4) {
					window.commandToken__MODULE_ID__ = xmlhttp.responseText;
					loadFeeds__MODULE_ID__();
				}
			}
			xmlhttp.send(null);
		}

		function displayErrorMessage__MODULE_ID__() {
			var msgEl = _gel("msg__MODULE_ID__");
			if (errorMsg__MODULE_ID__ != null) {
				msgEl.innerHTML = "";
				msgEl.appendChild(document.createTextNode(errorMsg__MODULE_ID__));
				showElement__MODULE_ID__(msgEl);
			} else {
				hideElement__MODULE_ID__(msgEl);
			}
		}

		function hideElement__MODULE_ID__(element) {
			element.style.visibility = "hidden";
			element.style.display = "none";
		}

		function showElement__MODULE_ID__(element) {
			element.style.visibility = "visible";
			element.style.display = "block";
		}

		function getSubscriptions__MODULE_ID__() {
			window.subscriptions__MODULE_ID__ = new Object();
			window.subsLoaded__MODULE_ID__ = false;

			var xmlhttp = getXMLHttpRequest__MODULE_ID__();
			// "-" can be substituted for the current user's _USER_ID
			xmlhttp.open("GET", "http://www.google.com/reader/atom/user/-/pref/com.google/subscriptions?complete=true",true);
			xmlhttp.onreadystatechange=function() {
				if (xmlhttp.readyState == 4) {
					var entries = xmlhttp.responseXML.getElementsByTagName("entry");
					for(var i=0; i < entries.length; i++) {
						var feedID = entries[i].getElementsByTagName("id")[0].childNodes[0].nodeValue;
						var title = entries[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;

						window.subscriptions__MODULE_ID__[feedID]=[title];
					}
					window.subsLoaded__MODULE_ID__ = true;
				}
			}
			xmlhttp.send(null);
		}

		function loadFeeds__MODULE_ID__() {
			window.feedEntries__MODULE_ID__ = new Object();

			var prefs = new _IG_Prefs(__MODULE_ID__);

			var entriesToDisplay = prefs.getInt("numEntriesToDisplay");
			var sort = prefs.getString("sortOrder");

			showElement__MODULE_ID__(_gel('ron__MODULE_ID__'));
			hideElement__MODULE_ID__(_gel('nodisplay__MODULE_ID__'));


			var targetNode = _gel('ron__MODULE_ID__');
			clearElement__MODULE_ID__(targetNode);

/*			var xmlDoc = null;
			if (window.ActiveXObject) {
				xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
			} else {
				xmlDoc=document.implementation.createDocument("","",null);
			}

			xmlDoc.async=false;
*/
	
			var target = "http://www.google.com/reader/atom/user/-/state/com.google/reading-list?xt=user/-/state/com.google/read&n=50";
			if  (sort == "REL") {
				// add &r=m to turn on relevence sorting
				target = target + "&r=m";
			}

			/* xmlDoc.load(target); */

if (document.implementation && document.implementation.hasFeature &&
    document.implementation.hasFeature('LS', '3.0')) {
			var domDoc = null; // will hold our XML
			var parser = document.implementation.createLSParser(document.implementation.MODE_SYNCHRONOUS,'http://www.w3.org/TR/REC-xml');
			try {
				var xmlDoc =parser.parseURI(target);
			} catch (e) {
			window.alert('parser.parseURI: Errorcode ' + e.code);
}			
	
} else {
	/* no support for DOM3 */
	window.alert('createLSParser not supported by your browser')
}

			var entries = xmlDoc.getElementsByTagName("entry");
			entryCount = entries.length;
			if (entries.length > entriesToDisplay) {
				entryCount = entriesToDisplay;
			}

			for(var i=0; i < entryCount; i++) {
				var entryObj = new Object();

				var entry = entries[i];
				var entryID = entry.getElementsByTagName("id")[0].childNodes[0].nodeValue;
				var title = "No title";
				if (entry.getElementsByTagName("title")[0]) {
					title = entry.getElementsByTagName("title")[0].childNodes[0].nodeValue;
				} else {
					title = entryID;
				}

				entryObj.id = entryID;
				entryObj.title = title;

				// find the link to the original item and the google link
				var links = entry.getElementsByTagName("link");
				var originalLink = "";
				var googleLink = "";
				for (var j=0; j < links.length; j++) {
					var rel=links[j].getAttribute("rel");
					if (rel == "alternate") {
						originalLink = links[j].getAttribute("href");
					} else if (rel == "http://www.google.com/reader/atom/relation/parent") {
						googleLink = links[j].getAttribute("href");
					}
				}

				entryObj.originalLink = originalLink;
				entryObj.googleLink = googleLink;

				var content;
				if (entry.getElementsByTagName("content")[0]) {
					content = entry.getElementsByTagName("content")[0].childNodes[0].nodeValue;
				} else {
					content = entry.getElementsByTagName("summary")[0].childNodes[0].nodeValue;
				}

				entryObj.content = content;

				var divEl = document.createElement("div");
				divEl.setAttribute("id", "entry__MODULE_ID__" + i);
				divEl.className="entry__MODULE_ID__ mc";


				var link = document.createElement("a");
				link.innerHTML=title;
				link.className="titleLink__MODULE_ID__";
				link.setAttribute("id", "l" + i);
				link.setAttribute("href", "javascript:displayEntry__MODULE_ID__('" + i + "', '" + entryID + "', '" + googleLink + "');");
				divEl.appendChild(link);
				var shortSummarySpan = document.createElement("div")
				shortSummarySpan.className="short-summary__MODULE_ID__";
				shortSummarySpan.setAttribute("id", "s" + i);
				shortSummarySpan.appendChild(document.createTextNode(" " + content.replace(/(<([^>]+)>)/ig,"").substring(0, 50) + "..."));

				divEl.appendChild(shortSummarySpan);
				if (subsLoaded__MODULE_ID__) {
					var source = document.createElement("span");
					source.className="source__MODULE_ID__";
					source.appendChild(document.createTextNode(window.subscriptions__MODULE_ID__[decodeURIComponent(googleLink)][0] + " - "));
					divEl.appendChild(source);

					entryObj.source = window.subscriptions__MODULE_ID__[decodeURIComponent(googleLink)][0];
				}

				var linkToOrig = document.createElement("a");
				linkToOrig.className ="originalLink";

				linkToOrig.setAttribute("href", originalLink);
				var noBR = document.createElement("nobr");
				noBR.appendChild(document.createTextNode("Original >>"));
				linkToOrig.appendChild(noBR);
				divEl.appendChild(linkToOrig);


				targetNode.appendChild(divEl);

				window.feedEntries__MODULE_ID__[entryID] = entryObj;

			}

			displayErrorMessage__MODULE_ID__();
		}

		function checkPreConditions__MODULE_ID__() {
			// make sure we are running inline
			if (window.location.href.indexOf("http://www.google.com/ig") < 0) {
				errorMsg__MODULE_ID__ = "This module must be run in-line and on the site www.google.com/ig";
				hideElement__MODULE_ID__(_gel('ron__MODULE_ID__'));
				hideElement__MODULE_ID__(_gel('nodisplay__MODULE_ID__'));
				displayErrorMessage__MODULE_ID__();

				return false;
			} else {
				return true;
			}
		}

		function setupReaderWindow__MODULE_ID__() {
			var myEl = _gel('readerbox__MODULE_ID__');
			_gel('modules_sub__MODULE_ID__').removeChild(myEl);

			var width =  screen.width - 300;
			var height =  screen.height - 300;
			if (self.innerWidth) {
				width = self.innerWidth;
				height = self.innerHeight;
			} else if (document.documentElement && document.documentElement.clientWidth) {
				width = document.documentElement.clientWidth;
				height = document.documentElement.clientHeight;
			} else if (document.body) {
				width = document.body.clientWidth;
				height = document.body.clientHeight;
			}

			myEl.style.width = width - 600;
			myEl.style.height = height - 300;
			myEl.style.display = "none";

			var targetNode = _gel('modules');
			targetNode.appendChild(myEl);

			new Draggable('readerbox__MODULE_ID__',{handle:'readerboxHandle__MODULE_ID__',revert:function(element){return false;}});

		}

		function doit__MODULE_ID__() {
			if (checkPreConditions__MODULE_ID__()) {
				try {
					var readerBox = _gel('readerbox__MODULE_ID__');
					if (readerBox) {
						readerBox.style.display="none";
					}

					hideElement__MODULE_ID__(_gel('ron__MODULE_ID__'));
					showElement__MODULE_ID__(_gel('nodisplay__MODULE_ID__'));
					getSubscriptions__MODULE_ID__();
					//give the subscriptions a chance to load
					setTimeout("getToken__MODULE_ID__()", 1000);

				} catch(e) {
					displayErrorMessage__MODULE_ID__();
				}
			}
		}

		function closeReaderWindow__MODULE_ID__() {
			var reader = _gel('readerbox__MODULE_ID__');
			reader.style.display = "none";

			return;
		}

		_IG_RegisterOnloadHandler(doit__MODULE_ID__);
		_IG_RegisterOnloadHandler(setupReaderWindow__MODULE_ID__);

		</script>
		<div id="msg__MODULE_ID__" class="message__MODULE_ID__">
		</div>
		<div id="ron__MODULE_ID__">
		</div>
		<div id="nodisplay__MODULE_ID__">
			Loading....
		</div>
		<div id="controls__MODULE_ID__">
			<input type="button" onClick="doit__MODULE_ID__()" value="Refresh" />
		</div>

		<div id="modules_sub__MODULE_ID__">
			<div id="readerbox__MODULE_ID__" >
				<span class="readerboxHandle__MODULE_ID__">
					<table class="mhdr" cellpadding="0" cellspacing="0">
						<tbody>
							<tr>
								<td class="mttl"><font color="#000088"><span id="readerTitle__MODULE_ID__">Reader</span></font></td>
								<td class="medit"><a href="#" onclick="closeReaderWindow__MODULE_ID__();"><img alt="delete" src="/ig/images/x.gif" class="mdel"></a></td>
							</tr>
						</tbody>
					</table>
				</span>
				<div id="readerContents__MODULE_ID__" />
			</div>
		</div>
     ]]>
	</Content>
</Module>
