////////////////////////////////////////////////////////////////////////////////
//  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 async_io 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
	}
//window.alert("feed = " + url_request);
	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) {
			
			//this.records[recordcounter].description = encodeURIComponent(this.records[recordcounter].description);
			
			// UTF-8 encoding issues create funny characters, need to decode UTF-8 into web friendly character
			//window.alert("before = " + this.records[recordcounter].description);
			//window.alert( "after = " + decodeURIComponent( escape(this.records[recordcounter].description) ) );

			var description_div = this.w.document.createElement('div');
			description_div.className = 'HW_rss_description_div';
			description_div.innerHTML = this.records[recordcounter].description;
			article_div.appendChild(description_div);

		}
		
		this.main_div.appendChild(article_div);
		recordcounter++;
	}
}

function willow_rss_layout_blog() {
	// Article list layout
	var recordcounter = 0;
	
	while(this.records[recordcounter] && (!this.limit || recordcounter < this.limit)) {
		
		// Cycle through the records
		var full_description_string = "";
		var image_string = "";
		var img_regex = /<img[^>]+>/i;
		var width_regex = /width=\"\d+?\"/i;
		var height_regex = /height=\"\d+?\"/i;
		var image_formatting = "width=\"100\" align=\"left\" style=\"margin-top: 5px; margin-right: 10px; border: 1px solid #ccc;\""


		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);
		}
		
		// full html description - but tweaked it to use an excerpt instead
		for ( x in this.records[recordcounter] )
		{
			//window.alert("key => " + x + "\nvalue => " + this.records[recordcounter][x]);
			//if( x == 'content:encoded' ){
			if( x == 'description' ){
				
				//window.alert("key => " + x + "\nvalue => " + this.records[recordcounter][x]);
				
				// create the new image string
				image_string = this.records[recordcounter][x].match(img_regex);
				
				if( image_string != null ){
					
					image_string = (""+image_string).replace(width_regex, image_formatting);
					image_string = (""+image_string).replace(height_regex, "");
					
					//window.alert("image_string = " + image_string);
					// create the content
					full_description_string = this.records[recordcounter][x].replace(img_regex, "");
				
					this.records[recordcounter].full_description = "<div>" + image_string + full_description_string + "</div>";
				
				}else{
				
					this.records[recordcounter].full_description = "<div>" + this.records[recordcounter][x] + "</div>";
				
				}
				
				var full_description_div = this.w.document.createElement('div');
				full_description_div.className = 'HW_rss_description_div';
				full_description_div.innerHTML = this.records[recordcounter].full_description;
				article_div.appendChild(full_description_div);
			}
		}

		
		this.main_div.appendChild(article_div);
		recordcounter++;
	}
}

function ATKINSIP_rss_layout_blog() {
	// 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';
			
			var days = ['Sun.', 'Mon.', 'Tue.', 'Wed.', 'Thu.', 'Fri.', 'Sat.'];
			var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
			pubdate = this.records[recordcounter].pubdate;
			//window.alert(pubdate);
			var d = new Date();
			d.setTime(Date.parse(pubdate));
			var str = months[d.getMonth()] + ' ' + d.getDate() + ', ' + d.getFullYear();
			date_div.appendChild(this.w.document.createTextNode(str));
			//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.innerHTML = this.records[recordcounter].description;
			article_div.appendChild(description_div);

		}
		
		this.main_div.appendChild(article_div);
		recordcounter++;
	}
}

function GFTL_rss_layout_news_list() { // www.h1unlimited.com feed for Go Fast Turn Left
	// Article list layout
	var recordcounter = 0;	

	// Cycle through the records
	while(this.records[recordcounter] && (!this.limit || recordcounter < this.limit)) {
		
		/* Use the following to determine what XML data the feed provided, Also changing the key value for content:encoded to full_description */
		var image_string = "";
		var img_regex = /<img[^>]+>/i;
		var width_regex = /width=\"\d+?\"/i;
		var height_regex = /height=\"\d+?\"/i;
		var image_formatting = "width=\"100\" align=\"left\" style=\"margin-top: 5px; margin-right: 5px; border: 1px solid #ccc;\""

		var category_purge_regex = /tuesday\stalk/i;
		
		for ( x in this.records[recordcounter] )
		{
			//window.alert("key => " + x + "\nvalue => " + this.records[recordcounter][x]);
			if( x == 'content:encoded' ){	// used to display an image from the H1 Unlimited Feed	
				
				//window.alert("key => " + x + "\nvalue => " + this.records[recordcounter][x]);
				image_string = this.records[recordcounter][x].match(img_regex);
				image_string = (""+image_string).replace(width_regex, image_formatting);
				image_string = (""+image_string).replace(height_regex, "");
				//window.alert("image_string = " + image_string);
				this.records[recordcounter].full_description = image_string;
				
			}else if( x == 'thumbnail_url' ){	// display an image from the the Bossanova News Feed
				
				//window.alert("key => " + x + "\nvalue => " + this.records[recordcounter][x]);
				image_string = '<img src="' + this.records[recordcounter][x] + '" ' + image_formatting + ' />';
				this.records[recordcounter].full_description = image_string;
			
			}else if( x == 'category' && this.records[recordcounter][x].match(category_purge_regex) ){	// filter out CATEGORIES from this fee: eg Tuesday Talk category
				
				//window.alert('category = ' + this.records[recordcounter][x]);
				recordcounter++;
				continue;
			}
		}
		//window.alert("full_description => " + this.records[recordcounter].full_description);
		
		// Create the Divs
		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');
			
			try{
				
				a.appendChild(this.w.document.createTextNode( decodeURIComponent( escape(this.records[recordcounter].title) ) || 'Untitled'));	
			
			}catch(err){
			
				a.appendChild(this.w.document.createTextNode(this.records[recordcounter].title || 'Untitled'));
			}

			title_div.appendChild(a);
		
		} else {
			
			try{
				title_div.appendChild(this.w.document.createTextNode( decodeURIComponent( escape(this.records[recordcounter].title) ) || 'Untitled'));
			
			}catch(err){
			
				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].full_description) {
		
			var description_div = this.w.document.createElement('div');
			description_div.className = 'HW_rss_description_div';
			description_div.innerHTML = this.records[recordcounter].full_description;
			
			try{
				
				description_div.innerHTML += decodeURIComponent( escape(this.records[recordcounter].description) );

			}catch(err){

				description_div.innerHTML += this.records[recordcounter].description;
			}

			article_div.appendChild(description_div);

		}else if(this.records[recordcounter].description) {
			
			// UTF-8 encoding issues create funny characters, need to decode UTF-8 into web friendly character
			//window.alert("before = " + this.records[recordcounter].description);
			//window.alert( "after = " + decodeURIComponent( escape(this.records[recordcounter].description) ) );

			var description_div = this.w.document.createElement('div');
			description_div.className = 'HW_rss_description_div';
			description_div.innerHTML = decodeURIComponent( escape(this.records[recordcounter].description) + "<br>");
			//description_div.innerHTML = this.records[recordcounter].description;
			article_div.appendChild(description_div);

		}
		
	
		var end_div = this.w.document.createElement('div'); // creates a new record by allowing you to create a style for the div & then clear: both
		end_div.className = 'HW_rss_end_div';
		article_div.appendChild(end_div);

		this.main_div.appendChild(article_div);
		recordcounter++;
	}
}

function GFTL_rss_layout_race_results() { // race results feed for Go Fast Turn Left
	// 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';
		
		//title_div.innerHTML = '<img src="http://www.gofastturnleftracing.net/files/checkered-flags.gif" width="30" alt="Go Fast, Turn Left Racing Results" title="Go Fast, Turn Left Racing Results" align="left" style="margin-right: 5px;" />';
		
		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);
		}

		var description_div = this.w.document.createElement('div');
		description_div.className = 'HW_rss_description_div';
		description_div.innerHTML = '<img src="http://www.gofastturnleftracing.net/files/checkered-flags.gif" width="30" alt="Go Fast, Turn Left Racing Results" title="Go Fast, Turn Left Racing Results" align="left" style="margin-top: 5px; margin-right: 5px;" />';
		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.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.atkinsip_blog_list = ATKINSIP_rss_layout_blog;
	this.layouts.gftl_news_list = GFTL_rss_layout_news_list;
	this.layouts.gftl_race_results = GFTL_rss_layout_race_results;
	this.layouts.willow_blog_list = willow_rss_layout_blog;
	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++) {
			
			if( t.order == 'pubdate' ){	// convert pubdate to unix timestamp for proper ordering
				
				var date = new Date(rec[t.order[i]]);
				var timestamp = Math.round(date.getTime()/1000);
				orderkey = orderkey + (timestamp || '0');
				//alert("orderkey = " + orderkey);	

			}else{
				orderkey = orderkey + (rec[t.order[i]] || '0');
				//alert("orderkey = " + orderkey);
			}
		}

		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); // sorts the records array by t.order (multiple feeds are then sorted as one array)

	/*
	// debugging the records array
	var recordcounter = 0;
	while(this.records[recordcounter] && (!this.limit || recordcounter < this.limit)) {	
		
		//window.alert('this records = ' + this.records[recordcounter].title);

		for ( x in this.records[recordcounter] )
		{
			//window.alert("key => " + x + "\nvalue => " + this.records[recordcounter][x]);
			if( x == 'title' ){
				
				window.alert("key => " + x + "\nvalue => " + this.records[recordcounter][x] + "\ntitle => " + this.records[recordcounter].title);
				//image_string = this.records[recordcounter][x].match(img_regex);
				//image_string = (""+image_string).replace(width_regex, "width=\"100\" align=\"left\" style=\"margin-top: 5px; margin-right: 5px; border: 1px solid #ccc;\"");
				//image_string = (""+image_string).replace(height_regex, "");
				//window.alert("image_string = " + image_string);
				//this.records[recordcounter].full_description = image_string;
				
			}
		}

		recordcounter++;

	}
	*/
	
}
