/**
 * A function that creates an RSSFeed object encapsulating all functionality
 */
function RSSFeed(mId) {
	var me = this;
	var p = this.prefs = new _IG_Prefs(mId);
	this.title = p.getString('title');
	this.titlelink = p.getString('titlelink');
	this.group = p.getString('group');
	this.groupurl = "http://groups.google.com/group/" + this.group;
	this.url = p.getString('url');
	this.filter = p.getString('filter');
	this.hideregexobj = null;
	if (this.filter) { this.hideregexobj = new RegExp(this.filter,"i"); }
	this.interval = null;
	this.allowclear = p.getBool('allowclear');
	this.unordered = p.getBool('unordered');
	this.hideseen = p.getBool('hideseen');
	this.hideempty = p.getBool('hideempty');
	this.lastseen = p.getString('lastseen');
	this.firstlink = null;
	this.num = p.getInt('num');
	this.icon = p.getBool('icon');
	this.bullet = p.getString('bullet');
	this.rewritegoogle = p.getBool('rewritegoogle');
	this.regexfind = p.getString('regexfind');
	this.regexreplace = p.getString('regexreplace');

	this.groupbysubject = p.getBool('groupbysubject');
	this.expandbydefault = p.getBool('expandbydefault');
	this.subjectlist = [];
	this.subjects = {};

	this.TPL_entry = p.getString('format');
	if (!this.TPL_entry || this.TPL_entry=="custom") {
		this.TPL_entry = p.getString('customformat');
	}	

	this.itemList={};
	this.highlightNewItemsTimeout=null;
	this.loaded=false;
	
	this.msg = function(txt) {
		_gel("FEED"+mId+"msg").innerHTML = txt;
		_gel("FEED"+mId+"status").style.display = "block";
		_gel("FEED"+mId+"display").style.display = "none";
	};
	
	this.startRefresh = function() {
		this.interval = setInterval(function(){me.refresh()}, (60000 * p.getInt('refresh')));
	};
	
	this.clearRefresh = function() { clearInterval(this.interval); };
	
	this.init = function() { 
		this.startRefresh();
		this.load();
	};
	
	this.load = function() {
		if (!this.url && this.group) {
			this.url = this.groupurl + "/feed/rss_v2_0_msgs.xml?num="+this.num;
		}
		var url = this.url;
		if(p.getBool('cachefix')) {
			url += (url.indexOf("?")>-1)?"&":"?";
			url += "random="+new Date().getTime();
		}
		_IG_FetchFeedAsJSON(url,function(){me.render.apply(me,arguments)},this.num,p.getBool('summary'));
	};
	
	this.refresh = function() {
		_gel("m_"+mId+"_h").style.backgroundColor = _gel("FEED"+mId+"msg").style.backgroundColor = p.getString("refreshcolor");
		if (this.highlightNewItemsTimeout!=null) {
			clearTimeout(this.highlightNewItemsTimeout);
		}
		this.load();
	};
	
	this.addEntry = function(index, url, title, summary, date, alternate) {
		var tpl = this.TPL_entry;

		if (this.regexfind && this.regexfind!=" ") {
			title = title.replace(new RegExp(this.regexfind),this.regexreplace);
		}

		// Re-write google url's to go directory to the news story url
		if (this.rewritegoogle && url.search(/news\.google\.com.*\&url=([^\&]+)/)>=0) {
			url = unescape(RegExp.$1);
		}

		tpl = tpl.replace(/\%INDEX\%/g, index).replace(/\%ID\%/g, mId).replace(/\%URL\%/g, _hesc(url));
		var title = _hesc(title);
		var classname = "rsslink"+mId;
		if (this.loaded && !this.itemList[title]) {
			classname += " newrsslink"+mId;
		}
		// Need to do this next part up top so alternate logic can be correct
		if (this.groupbysubject) {
			var sub = title.replace(/^\s*re\s*:\s*/i,"");
			if (!this.subjects[sub]) {
				this.subjects[sub] = [];
				this.subjectlist.push(sub);
			}
			if (!!(this.subjects[sub].length%2==1)) {
				classname += " alternate"+mId;
			}
		}
		else if (alternate) {
			classname += " alternate"+mId;
		}
		this.itemList[title] = true;

		if (this.bullet=="arrow") { tpl = tpl.replace(/\%BULLET\%/g,"&#187;&nbsp;"); }
		else if (this.bullet=="bullet") { tpl = tpl.replace(/\%BULLET\%/g,"&#8226;&nbsp;"); }
		else if (this.bullet=="favicon") { 
			if (url.search(/^(https?:\/\/[^\/]+)/)>=0) {
				var favicon = '<img src="'+RegExp.$1+'/favicon.ico" border="0" align="absmiddle" style="height:16px;width:16px;" onerror="this.style.visibility=\'hidden\'">&nbsp;';
				tpl = tpl.replace(/\%BULLET\%/g,favicon); 
			}
			else {
				tpl = tpl.replace(/\%BULLET\%/g,"");
			}
		}
		else { tpl = tpl.replace(/\%BULLET\%/g,""); }
		
		tpl = tpl.replace(/\%A_CLASSNAME\%/g, classname);
		tpl = tpl.replace(/\%TITLE\%/g, title);
		tpl = tpl.replace(/\%TARGET\%/g, (p.getBool('newwindow')?"_blank":"") );
		if (summary) {
			summary = summary.replace(/\<br\>/gi,"\n").replace(/\<[^\>]*\>/gi,"");
			tpl = tpl.replace(/\%SUMMARY\%/g, _hesc(summary));
		}
		else {
			tpl = tpl.replace(/\%SUMMARY\%/g, '');
		}
		if (date) {
			var d = new Date(date*1000);
			tpl = tpl.replace(/\%N\%/g, ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][d.getDay()]);
			tpl = tpl.replace(/\%D\%/g, d.getDate());
			tpl = tpl.replace(/\%M\%/g, d.getMonth()+1);
			tpl = tpl.replace(/\%Y\%/g, d.getFullYear());
			tpl = tpl.replace(/\%h\%/g, d.getHours());
			tpl = tpl.replace(/\%m\%/g, d.getMinutes());
			tpl = tpl.replace(/\%s\%/g, d.getSeconds());
		}
		if (this.groupbysubject) {
			this.subjects[sub].push(tpl);
		}
		else {
			_gel("FEED"+mId+"entries").innerHTML += tpl;
		}
		return tpl;
	};
	
	this.setTitle = function(title) {
		var t = _gel("m_"+mId+"_title");
		if (title && title != "") {
			t.innerHTML = _hesc(title);
		}
	};
	
	this.render = function(obj) {
		_gel("m_"+mId+"_h").style.backgroundColor = "";
		_gel("FEED"+mId+"msg").style.backgroundColor = "";
		if (!this.loaded && !obj) {this.retry("Information is temporarily unavailable.");return;}
		if (!this.loaded && obj.ErrorMsg && obj.ErrorMsg != "") {this.retry(obj.ErrorMsg);return;}
		if (!this.loaded && (!obj.Entry || obj.Entry.length == 0)) {
			this.retry("Information is temporarily unavailable.");return;
		}
		if (!this.title) {
			this.setTitle(obj.Title,obj.Link);
		}
		this.subjectlist = [];
		this.subjects = {};
		_gel("FEED"+mId+"status").style.display = "none";
		if (obj.Entry) {
			_gel("FEED"+mId+"entries").innerHTML = "";
			if (this.allowclear && !this.group) {
				_gel("FEED"+mId+"clear").style.display="block";
			}
			var hideAll = false;
			var count = 0;
			// For ordered feeds, only need to store the latest url seen
			if (!this.unordered) {
				this.firstlink = obj.Entry[0].Link;
			}
			else {
				this.firstlink = "";
			}
			for (var i = 0; i < obj.Entry.length; i++) {
				var hide = false;
				if (this.unordered) {
					this.firstlink += (i==0?"":";") + obj.Entry[i].Title;
				}
				if (!this.unordered && this.hideseen && !hideAll && obj.Entry[i].Link==this.lastseen) {
					hideAll = true;
				}
				if (this.unordered && this.hideseen && !hide && this.lastseen.indexOf(obj.Entry[i].Title)>-1) {
					hide = true;
				}
				if (!hideAll && !hide) {
					if (this.hideregexobj!=null && obj.Entry[i].Title && obj.Entry[i].Title.search(this.hideregexobj)>=0) {
						continue;
					}
					if (count==0) {
						_gel("FEED"+mId+"display").style.display = "block";
					}
					this.addEntry(i,obj.Entry[i].Link,obj.Entry[i].Title,obj.Entry[i].Summary,obj.Entry[i].Date,!!(count++%2==1));
				}
			}
			if (hideAll && this.hideempty) {
				_gel("m_"+mId).style.display='none';
			}
			else {
				_gel("m_"+mId).style.display='';
			}
			if (count==0) {
				if (this.allowclear && !this.group) {
					_gel("FEED"+mId+"clear").style.display="none";
				}
			}
			else if (this.groupbysubject) {
				var el = _gel("FEED"+mId+"entries");
				var c = "";
				for (var i=0; i<this.subjectlist.length; i++) {
					var s = this.subjectlist[i];
					// If there is only one entry in a thread, show it without the thread header
					if (this.subjects[s].length==1) {
						c += this.subjects[s][0];
					}
					else {
						c += '<div class="mc group_subject_'+mId+'" onclick="_toggle(document.getElementById(\'group_thread_posts_'+mId+'_'+i+'\'))" title="Click to toggle thread posts">'+s+'&nbsp;&nbsp;('+ this.subjects[s].length +')</div>';
						c += '<div class="group_thread_posts_'+mId+'" id="group_thread_posts_'+mId+'_'+i+'" style="display:'+ (this.expandbydefault?'block':'none') +';">';
						for (var j=0; j<this.subjects[s].length; j++) {
							c += this.subjects[s][j];
						}
						c += '</div>';
					}
				}
				el.innerHTML += c;
			}
		}
		this.loaded = true;
		setTimeout(function(){me.unhighlightNewItems();}, p.getInt("newitemduration") * 1000);
	};
	
	this.unhighlightNewItems = function() {
		if (this.highlightNewItemsTimeout!=null) {
			clearTimeout(this.highlightNewItemsTimeout);
		}
		var entries = _gel('FEED'+mId+'entries').getElementsByTagName('A');
		if (entries) {
			for (var i=0; entries && i<entries.length; i++) {
				var a = entries[i];
				if (a && typeof(a.className)=="string") {
					a.className = a.className.replace(new RegExp("\s*newrsslink"+mId),'');
				}
			}
		}
	};
	
	this.retry = function(msg) {
		if (msg) {
			this.msg(msg);
		}
		this.clearRefresh();
		setTimeout(function(){me.refresh()},p.getInt("retryduration") *1000);
	};
	
	this.clear = function() {
		p.set('lastseen',this.firstlink);
		this.lastseen = this.firstlink;
		if (!this.group) {
			_gel("FEED"+mId+"clear").style.display = "none";
		}
		_gel("FEED"+mId+"display").style.display = "none";
		this.clearRefresh();
		this.startRefresh();
		this.refresh();
	};
	
	this.post = function() {
		var url = this.groupurl + "/post";
		window.open(url);
	};

	this.grouphome = function() {
		var url = this.groupurl;
		window.open(url);
	};

	this.msgs = function() {
		var url = this.groupurl + "/topics";
		window.open(url);
	};

	_IG_RegisterOnloadHandler(function(){me.init()});
}

