
dojo.require("dojox.data.dom");
dojo.require("dojo.date.locale");

var displayFeed=function(divId, rssUrl, showLimit) {
	this.divObj=dojo.byId(divId);
	if(this.divObj==null || rssUrl=="") return false;
	this.showLimit=showLimit || 10;
	this.url=rssUrl;

	this.handleResponse=function(response, ioArgs) {
        if(response instanceof Error) {
            if(response.dojoType == "cancel") {
				//The request was canceled by some other JavaScript code
                this.divObj.innetHTML="canceled...";
                this.divObj.className="rssError";
            }
			else if(response.dojoType == "timeout") {
            	//The request took over 5 seconds to complete.
                this.divObj.innetHTML="time out...";
                this.divObj.className="rssError";
            }
			else {
               	//Some other error happened.
                this.divObj.innetHTML=response;
                this.divObj.className="rssError";
            }
        }
		else {
			resultDom = dojox.data.dom.createDocument(response);
			articles=atomReaderUtils.getArticles(resultDom);
			atomReaderUtils.displayArticles(articles, this.divObj);
		}
	}
	
	var deferred = dojo.xhrGet({
		url: this.url,
        handleAs: "text",
        divObj: this.divObj,
        timeout: 15000, //Time in milliseconds
        handle: this.handleResponse
	});
	
}



atomReaderUtils = {

	displayArticles: function(articles, divObj) {

		contents='<table class="rssTable">';
		
		for(i=0; i<articles.length; i++) {
			contents+='<tr class="'+(i%2==0?'rowAlt2':'rowAlt1')+'">';

			entryDate=articles[i]['date']!=""?dojo.date.locale.format(articles[i]['date'], {selector:"date"}):"";
			entryTitle=articles[i]['title'];
			entryTitleLink='<a href="/'+articles[i]['alt_link']+'" target="_blank">'+entryTitle+'</a>';
			entryDateLink='<a href="/'+articles[i]['alt_link']+'" target="_blank">'+entryDate+'</a>';
			
			contents+='<td class="rssEntryDate">'+entryDate+'</td>';
			contents+='<td class="rssEntryTitle">'+entryTitleLink+'</td>';
			
			contents+='</tr>';
		}
		contents+='</table>';
		divObj.innerHTML=contents;
	},
	
	// Updates the page content according the feed xml
	getArticles: function(feedDom) {
		// Reset articles list
		mArticlesData = [];
        
		// Get all atricle entries
		var entries = feedDom.getElementsByTagName("entry");
		for(var i = 0; i < entries.length; i++) 
		{
			mArticlesData[i] = {};
			mArticlesData[i]["Id"] = i;
			mArticlesData[i]["title"] = this.getEntryTagValue(entries[i], "title"); 
			
			aDate=this.getEntryTagValue(entries[i], "td:modified");
			if(aDate=="") aDate=this.getEntryTagValue(entries[i], "published");
			if(aDate=="") aDate=this.getEntryTagValue(entries[i], "td:created");
			
			mArticlesData[i]["date"] = this.getDateFromXML(aDate); 
			mArticlesData[i]["summary"] = this.getEntryTagValue(entries[i], "summary");
//			mArticlesData[i]["html_content"] = this.getHTMLContent(entries[i]);
//			mArticlesData[i]["xhtml_content"] = this.getXHTMLContent(entries[i]);
			mArticlesData[i]["link"] = this.getEntryLink(entries[i]);
			mArticlesData[i]["alt_link"] = this.getEntryAltLink(entries[i]);
		}
		
		return mArticlesData;
	},	
	
	// Get title of the feed
	getFeedTitle: function(feedDom) {
		var feedTitles = feedDom.getElementsByTagName("title");
		
		if (feedTitles.length > 0)
			this.mCurrentFeedTitle = feedTitles[0].firstChild.nodeValue;
	},
	
	// Returns the value of the nested element of the given element
	getEntryTagValue: function(entry, tagName) {
		var elements = entry.getElementsByTagName(tagName);
		
		if (elements.length > 0)
		{
			// If element with the given name exists - return it text value 
			return elements[0].firstChild.nodeValue;
		}
		// No element with this name - return an empty string
		return "";
	},
	
	getXHTMLContent: function(entry) {
		var elements = entry.getElementsByTagName("content");
		
		for (var i=0; i<elements.length; i++) {
			if (elements[i].getAttribute("type") == "xhtml") {
				// Content presented as xml sub-tree
				return elements[i].firstChild;
			}
		}

		// No content with html type
		return "";
	},

	getHTMLContent: function(entry) {
		var elements = entry.getElementsByTagName("content");
		
		for (var i=0; i<elements.length; i++) {
			if (elements[i].getAttribute("type") == "html") {
				// Content presented in the nested text child node
				return elements[i].firstChild.nodeValue;
			}
		}

		// No content with html type
		return "";
	},
	
	// Returns the value of href attribute of a nested <link> element 
	// when ref attribute is not defined
	getEntryLink: function(entry) {
		// Get all link elements
		var linkElements = entry.getElementsByTagName("link");
			
		// Entry may contain multiple link elements - get link element with rel="alternate"
		for (i=0; i<linkElements.length; i++)
		{
			if (!linkElements[i].attributes["rel"] != "undefined")
			{
				// Link without ref attribute wasd found - return it href attribute
				return linkElements[i].getAttribute("href");
			}
		}
		// No link without rel attribute was found - return an empty string
		return "";
	},
	
	// Returns the value of href attribute of a nested <link> element 
	// when ref='alternate' and type='text/html'
	getEntryAltLink: function(entry) {
		// Get all link nested elements
		var linkElements = entry.getElementsByTagName("link");
			
		// Entry may contain multiple link elements - get link element with rel="alternate"
		for (i=0; i<linkElements.length; i++)
		{
			if (linkElements[i].getAttribute("rel") == "alternate")
			{
				return linkElements[i].getAttribute("href");
			}
		}
		// No link with rel="alternate" and type="text/html" was found
		return "";
	},

	getDateFromXML: function (string) {

		if(string==null || string=="") return "";
		
	    var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
	        "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
	        "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
	    var d = string.match(new RegExp(regexp));
	
	    var offset = 0;
	    var date = new Date(d[1], 0, 1);
	
	    if (d[3]) { date.setMonth(d[3] - 1); }
	    if (d[5]) { date.setDate(d[5]); }
	    if (d[7]) { date.setHours(d[7]); }
	    if (d[8]) { date.setMinutes(d[8]); }
	    if (d[10]) { date.setSeconds(d[10]); }
	    if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
	    if (d[14]) {
	        offset = (Number(d[16]) * 60) + Number(d[17]);
	        offset *= ((d[15] == '-') ? 1 : -1);
	    }
	
	    offset -= date.getTimezoneOffset();
	    time = (Number(date) + (offset * 60 * 1000));
	    date.setTime(Number(time));
	    
	    return date;
	}

}


