/*
* Author: simon.gilhooly
*/


function loadXMLDocument(fileName){
	var xmlDoc = window.ActiveXObject ? new ActiveXObject("MSXML2.DOMDocument.3.0")
	:
	
	document.implementation.createDocument("","",null);
	xmlDoc.async = false;
	xmlDoc.load(fileName);
	
	return xmlDoc;
}

function parseFeed(feedCategory, maxCount){
	var newsItem, newsCategory, resultHTML = "Sorry there are no entries in this section.", title, author, published, content;
	var count = 0, extract, required, truncPt;
	var atomDoc = loadXMLDocument("blog/atom.xml");

	var newsItems = atomDoc.getElementsByTagName("entry");		//get all the Atom feed entries
	
	if (newsItems.length > 0) {
		resultHTML = "";		//we have at least one entry so reset this variable to collect the output

		for (var i = 0; i < newsItems.length; i++) {
			newsCategory = "";
			matchId = "";
			required = false;
			newsItem = newsItems[i];
	
			newsItemCategories = newsItem.getElementsByTagName("category");		//test to see whether this is in the right category if so set 'required'
			if (newsItemCategories.length > 0){
				if (count < maxCount ){
					for (var j = 0; j < newsItemCategories.length; j++) {
	
						newsCategory = newsItem.getElementsByTagName("category")[j].getAttribute("term");
						if (newsCategory.toLowerCase() == feedCategory.toLowerCase()) {
							required = true;
							count = count + 1;
						}
					}
				}
				if (required) {
					title = newsItem.getElementsByTagName("title")[0].firstChild.nodeValue;
					author = newsItem.getElementsByTagName("name")[0].firstChild.nodeValue;
					published = newsItem.getElementsByTagName("published")[0].firstChild.nodeValue.slice(0,10);
					content = newsItem.getElementsByTagName("content")[0].firstChild.nodeValue;
					
					newsItemLinks = newsItem.getElementsByTagName("link");
					for (var k = 0; k < newsItemLinks.length; k++) {
						linkRel = newsItemLinks[k].getAttribute("rel");
						if (linkRel == "alternate") {
							matchReportURL = newsItemLinks[k].getAttribute("href");
						}
					}
					
					// should we stick the content into a documentFragment and then manipulate it? Need to lose <div class='blogger-post-footer'> ... </div>

					resultHTML = resultHTML + "<div class='newsitem'><h4><a href='" + matchReportURL + matchId + "'>" + title + "</a>" + " - <span class='date'>" + published + "</span></h4><p>" + content + "</p><p class='alignRight'>Submitted by: " + author + "</p></div>";
				}
			} else {
				// newsCategory = "undefined";
			}
		}
	}
	return resultHTML;
}

