////////////////////////////////////////////////////////////////////////////////
//  HANG WIRE JAVASCRIPT RSS READER
//  Currently uses MagicParser on the server side to translate XML to delimited text
//

function HW_rss_read() {
	// Cycle through the records
	var recs = this.records.split(":|||END_RECORD|||\n");
	for(var i=0; i<recs.length; i++) {
		if(recs[i].length > 0) {
			var rec = new Object();
			var fields = recs[i].split(':|||:');
			for(var j=0; j<fields.length; j++) {
				var field = fields[j].split(':|=>|:');
				rec[field[0]] = field[1];
			}
			this.record_handler(rec);
		}
	}
}

function HW_rss_process_feed(txt) {
	// Add the text to the object
	this.records = this.records + txt;
}

function HW_rss_add_feed(feed, limit) {
	// Gets a feed from asyncio and parses it
//	this.h.clear_values();
//	this.h.add_value('rss2delim', HangWire.urlencode(feed)); alert(HangWire.urlencode(feed));			//why didn't this work??
	if(limit) {
		this.h.add_value('limit', limit);
	}
	this.h.add_header_value('Pragma', 'no-cache');
	this.h.add_header_value('Cache-Control', 'no-cache');

	// For reasons that I don't understand, probably having to do with the URL-encoded feed URL that has to be passed, the this.h.add_value() function doesn't work to add GET variables to the request.  But, passing the URL to this.h.request() complete with a GET string seems to work.  So, we do it that way.  We build a request string based on the parameters that are needed.  We have to add the _ parameter manually -- which is there to prevent browser caching -- and we have to add the limit parameter manually if applicable.
	var url_request = 'http://www.hang-wire.com/cmp/async_io.php?rss2delim=' + HangWire.urlencode(feed);		// that's the feed URL
	url_request = url_request + '&_=' + HangWire.unique_string();					// this prevents browser caching

	if(limit) {
		url_request = url_request + '&limit=' + limit;								// add the limit parameter if applicable
	}

	this.h.get_variable_override = true;								// tell this.h (the HW_HTTP object) to ignore any previously defined variables and use the URL only
	this.h.request(url_request);													// make the request
}

window.HW_RSS_Reader = function () {
	var t = this;
	this.h = new HW_HTTP();
	this.h.async = false;
	this.h.on_response = function (txt) { t.process_feed(txt); }
	this.records = '';

	// User-set function to do what with each record.  Record passed as JS object (associative array).
	this.record_handler = function (rec) {}

	this.add_feed = HW_rss_add_feed;
	this.process_feed = HW_rss_process_feed;
	this.read = HW_rss_read;
}



///////////////////////////////////////////////////////////////////////////////
//  ORDERED DIV RSS LIST DISPLAY
//  use the class names in CSS to style the feed

function HW_rss_layout_article_list() {
	// Article list layout
	var recordcounter = 0;
	while(this.records[recordcounter] && (!this.limit || recordcounter<this.limit)) {
		// Cycle through the records
		var article_div = this.w.document.createElement('div');
		article_div.className = 'HW_rss_article_div';
		var title_div = this.w.document.createElement('div');
		title_div.className = 'HW_rss_title_div';
		if(this.records[recordcounter].link) {
			var a = this.w.document.createElement('a');
			a.setAttribute('href', this.records[recordcounter].link);
			a.setAttribute('target', '_blank');
			a.appendChild(this.w.document.createTextNode(this.records[recordcounter].title || 'Untitled'));
			title_div.appendChild(a);
		} else {
			title_div.appendChild(this.w.document.createTextNode(this.records[recordcounter].title || 'Untitled'));
		}
		article_div.appendChild(title_div);
		if(this.records[recordcounter].pubdate) {
			var date_div = this.w.document.createElement('div');
			date_div.className = 'HW_rss_date_div';
			date_div.appendChild(this.w.document.createTextNode(this.get_date_string(this.records[recordcounter].pubdate)));
			article_div.appendChild(date_div);
		}
		if(this.records[recordcounter].description) {
			var description_div = this.w.document.createElement('div');
			description_div.className = 'HW_rss_description_div';
//			description_div.appendChild(this.w.document.createTextNode(this.records[recordcounter].description));
			description_div.innerHTML = this.records[recordcounter].description;
			article_div.appendChild(description_div);
		}
		
		this.main_div.appendChild(article_div);
		recordcounter++;
	}
}

function HW_rss_layout_article_list_headline_and_source_google() {
	// Article list layout
	var recordcounter = 0;
	while(this.records[recordcounter] && (!this.limit || recordcounter<this.limit)) {
		// Parse out title and source
		this.records[recordcounter].title = this.parse_text_for_google(this.records[recordcounter].title);
		var pos = false;
		if(pos = this.records[recordcounter].title.search(/\-\s+[^\-]+$/)) {
			var title = '<b>' + this.records[recordcounter].title.substring(0, pos) + '</b>';
			var source = '<br />Source: ' + this.records[recordcounter].title.substring(pos + 2);
		} else {
			var title = this.records[recordcounter].title || "Untitled";
			var source = '';
		}

		// Cycle through the records
		var article_div = this.w.document.createElement('div');
		article_div.className = 'HW_rss_article_div';
		var title_div = this.w.document.createElement('p');
		title_div.className = 'HW_rss_title_div';
		if(this.records[recordcounter].link) {
			var a = this.w.document.createElement('a');
			a.setAttribute('href', this.records[recordcounter].link);
			a.setAttribute('target', '_blank');
			a.innerHTML = title + source;
			title_div.appendChild(a);
		} else {
			title_div.innerHTML = title + source;
		}
		article_div.appendChild(title_div);
		this.main_div.appendChild(article_div);
		recordcounter++;
	}
}

function HW_rss_parse_text_for_google(txt)
{
	var str = '';
	var tx = txt.replace(/�/g, "'");
	for(i=0; i<tx.length; i++)
	{
		if(tx.charCodeAt(i) < 128)			// omit characters above 128
		{
			str = str + tx.charAt(i);
		}
	}
	return str;
}

function HW_rss_layout_article_list_google() {
	// Article list layout
	var recordcounter = 0;
	while(this.records[recordcounter] && (!this.limit || recordcounter<this.limit)) {
		// Cycle through the records
		var article_div = this.w.document.createElement('div');
		article_div.className = 'HW_rss_article_div';
		if(this.records[recordcounter].description) {
			var description_div = this.w.document.createElement('div');
			description_div.className = 'HW_rss_description_div';
//			description_div.appendChild(this.w.document.createTextNode(this.records[recordcounter].description));
//			description_div.innerHTML = this.records[recordcounter].description.replace(/�/g, '"').replace(/�/g, '').replace(/�/g, '');
/*			var str = '';
			var descrip = this.records[recordcounter].description.replace(/�/g, '"');
			for(i=0; i<descrip.length; i++)
			{
				if(descrip.charCodeAt(i) < 128)			// omit characters above 128
				{
					str = str + descrip.charAt(i);
				}
			}
			description_div.innerHTML = str;
*/			description_div.innerHTML = this.parse_text_for_google(this.records[recordcounter].description);
			article_div.appendChild(description_div);
		}
		this.main_div.appendChild(article_div);
		recordcounter++;
	}
}

function HW_rss_get_date_string(pubdate) {

	// Gets a date string from a pubdate
	var days = ['Sun.', 'Mon.', 'Tue.', 'Wed.', 'Thu.', 'Fri.', 'Sat.'];
	var months = ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May', 'Jun.', 'Jul.', 'Aug.', 'Sep.', 'Oct.', 'Nov.', 'Dec.'];
	var d = new Date();
	d.setTime(Date.parse(pubdate));
	var str = days[d.getDay()] + ', ' + months[d.getMonth()] + ' ' + d.getDate() + ', ' + d.getFullYear();
	var h = d.getHours();
	var m = d.getMinutes();
//window.alert("pubdate = " + pubdate + "\nstr = " + str + "\nh = " + h + "\nm = " +m);
	if(h>0 && m>0) {
		str = str + ', ' + (h%12>0 ? h%12 : 12) + ':' + (m<10 ? '0' : '') + m + (h>=12 ? ' pm' : ' am'); //+ ' ' + d.getTimezoneOffset();  // this method gives you the offset from GMT
	}

//window.alert(str);

	return str;
}

window.HW_RSS_List_Display = function (div, rss_reader, limit, asc, order, w) {

	// Parameters
	this.main_div = div;
	this.rss_reader = rss_reader;
	this.order = order ? order.split(',') : ['pubdate'];		//   /--- Default sort is by
	this.asc = asc || false;									//   \--- date, descending
	this.limit = limit || false;
	this.w = w || window;

	// Properties
	var t = this;
	this.records = new Array();

	// Methods
	this.get_date_string = HW_rss_get_date_string;
	this.parse_text_for_google = HW_rss_parse_text_for_google;
	this.do_layout = function () {}

	// Layout libraries
	this.layouts = new Object();
	this.layouts.article_list = HW_rss_layout_article_list;
	this.layouts.article_list_google = HW_rss_layout_article_list_google;
	this.layouts.headline_and_source_google = HW_rss_layout_article_list_headline_and_source_google;
	this.select_layout = function (layout) { this.do_layout = this.layouts[layout]; }
	this.select_layout('article_list');

	// Read all RSS articles into array
	this.rss_reader.record_handler = function (rec) {
		t.records.push(rec);
	}
	this.rss_reader.read();

	// Order key generator function
	function orderkey(rec) {
		var orderkey = '';
		for(i=0; i<t.order.length; i++) {
			orderkey = orderkey + (rec[t.order[i]] || '0');
		}
		return orderkey;
	}
	
	// Sort the array
	function sortrecs(rec1, rec2) {
		var o1 = orderkey(rec1);
		var o2 = orderkey(rec2);
		return o1==o2 ? 0 : (t.asc ? (o1<o2 ? -1 : 1) : (o1<o2 ? 1 : -1));
	}
	this.records.sort(sortrecs);
}