/**
 * required http://www.google.com/jsapi
 * step1: set options
 * step2: initialize
 * step3: load
 * e.g.
	var options = [{
	'div_id': 'officialFeed', 
	'url': 'http://www.blogger.com/feeds/3563220197025694580/posts/summary?max-results=3', 
	'num_entries': 3, 
	'link_target': 'self'
	}};
	var rsFeedFetch = new RSFeedFetch();
	rsFeedFetch.initialize(options);
	rsFeedFetch.load();  
 */
var RSFeedFetch = function() {};
RSFeedFetch.prototype = {
	options: {}, 
	initialize: function(options) {
		this.options = options || {}
	}, 
	load: function() {
		var o = this.options;
		google.load("feeds", "1");
		google.setOnLoadCallback(function() {
			for (var i = 0; i < o.length; i++) {
				var rsFeedFetcher = new RSFeedFetcher();
				var option = {};
				option['url'] = o[i]['url'];
				option['div_id'] = o[i]['div_id'];
				option['num_entries'] = o[i]['num_entries'];
				option['link_target'] = o[i]['link_target'];
				option['try_count'] = o[i]['try_count'];
				option['no_cache'] = o[i]['no_cache'];
				option['thumb'] = o[i]['thumb'];
				option['thumb_width'] = o[i]['thumb_width'];
				option['thumb_height'] = o[i]['thumb_height'];
				option['truncate_length'] = o[i]['truncate_length'];

				rsFeedFetcher.initialize(option);
				rsFeedFetcher.load();
			}
		});
	}
}
var RSFeedFetcher = function() {};
RSFeedFetcher.prototype = {
	url: null, 
	feed: null,
	div_id: null,
	num_entries: null,
	link_target: null,
	try_count: null,
	no_cache: false,
	no_entry_is_faild: true,
	thumb: false,
	thumb_width: 0,
	thumb_height: 0,
	truncate_length: 0,

	initialize: function(option) {
		this.url = option['url'] || '';
		this.div_id = option['div_id'] || '';
		this.num_entries = option['num_entries'] || 5;
		if (option['link_target'] == 'blank') {
			this.link_target = google.feeds.LINK_TARGET_BLANK;
		} else if (option['link_target'] == 'self') {
			this.link_target = google.feeds.LINK_TARGET_SELF;
		} else {
			this.link_target = google.feeds.LINK_TARGET_SELF;
		}
		this.try_count = option['try_count'] || 10;
		this.no_cache = option['no_cache'] || false;
		this.thumb = option['thumb'] || false;
		this.thumb_width = option['thumb_width'] || 64;
		this.thumb_height = option['thumb_height'] || 64;
		this.truncate_length = option['truncate_length'] || 60;
	}, 
	load: function() {
		if (this.no_cache) {
			if (this.url.search(/www\.blogger\.com\/feeds/) != -1) { // blogger API
				if (this.url.search(/max-results=(\d+)/) != -1) {
					this.url = this.url.replace(/max-results=(\d+)/, "max-results=" + (parseInt(RegExp.$1) + 1));
				} else {
					if (this.url.search(/\?/) != -1) {
						this.url += "&max-results=" + this.num_entries;
					} else {
						this.url += "?max-results=" + this.num_entries;
					}
				}
				this.feed = new google.feeds.Feed(this.url);			
			} else {
				if (this.url.search(/\?/) != -1) {
					this.feed = new google.feeds.Feed(this.url + "&" + new Date().getTime());
				} else {
					this.feed = new google.feeds.Feed(this.url + "?" + new Date().getTime());
				}
			}
		} else {
			this.feed = new google.feeds.Feed(this.url);		
		}

		this.feed.setNumEntries(this.num_entries);
		this.feed.load(getFeedFunc(this));
		function getFeedFunc(rsFeedFetcher) {
			return function (result) {createFeed(result, rsFeedFetcher)};
		}
	}
}
function createFeed(result, rsFeedFetcher) {
	//alert(rsFeedFetcher.url);
	var elm = document.getElementById(rsFeedFetcher.div_id);
	try {
		if (rsFeedFetcher.try_count > 0) {
			if (!result.error) {
				var gfc_control = document.createElement("div");
				gfc_control.className = "gfc-control";
					var gfc_resultsRoot = document.createElement("div");
					gfc_resultsRoot.className = "gfc-resultsRoot";

					var gfc_resultsHeader = document.createElement("div");
					gfc_resultsHeader.className = "gfc-resultsHeader";
						var gfc_title = document.createElement("div");
						gfc_title.className = "gfc-title";
							var gfc_link = document.createElement("a");
							gfc_link.className = "gfc-title";
							gfc_link.href = result.feed.link;
							gfc_link.target = rsFeedFetcher.link_target;
							gfc_link.appendChild(document.createTextNode(result.feed.title));
						gfc_title.appendChild(gfc_link);
					gfc_resultsHeader.appendChild(gfc_title);

				gfc_resultsRoot.appendChild(gfc_resultsHeader);

					var gfc_results = document.createElement("div");
					gfc_results.className = "gfc-results";

					/* no entry check -> reload feed */
					if (rsFeedFetcher.no_entry_is_faild && result.feed.entries.length <= 0) {
						rsFeedFetcher.no_cache = true;
						rsFeedFetcher.try_count--;
						if (rsFeedFetcher.try_count > 0) {
							//failedHandle(elm, " Reloading...[" + rsFeedFetcher.try_count + "]");
							setTimeout(function() {rsFeedFetcher.load()}, 250);
						} else {
							failedHandle(elm);
						}
						return;
					}
					for (var i = 0; i < result.feed.entries.length; i++) {
						var entry = result.feed.entries[i];
						var gf_result = document.createElement("div");
						gf_result.className = "gf-result";

							if (rsFeedFetcher.thumb) {
								var thumbnail = document.createElement("div");
								thumbnail.className = "gf-thumbnail";
								var img = getFirstImage(entry.content, rsFeedFetcher.thumb_width, rsFeedFetcher.thumb_height, result.feed.link);
								if (img) {
									thumbnail.appendChild(img);
								}
							gf_result.appendChild(thumbnail);
							}

							var gf_title = document.createElement("div");
							gf_title.className = "gf-title";
								var gf_link = document.createElement("a");
								gf_link.className = "gf-title";
								gf_link.href = entry.link;
								gf_link.target = rsFeedFetcher.link_target;
								gf_link.appendChild(document.createTextNode(entry.title));
							gf_title.appendChild(gf_link);
						gf_result.appendChild(gf_title);
							var gf_author = document.createElement("div");
							gf_author.className = "gf-author";
							gf_author.appendChild(document.createTextNode(' by '+entry.author));
						gf_result.appendChild(gf_author);
							var gf_relativePublishedDate = document.createElement("div");
							gf_relativePublishedDate.className = "gf-relativePublishedDate";
							var d = new Date(entry.publishedDate);
							var yy = d.getFullYear();
							var mm = d.getMonth() + 1;
							var dd = d.getDate();
							var h = d.getHours();
							var m = d.getMinutes();
							if (mm < 10) mm = '0'+mm;
							if (dd < 10) dd = '0'+dd;
							if (h < 10) h = '0'+h;
							if (m < 10) m = '0'+m;
							gf_relativePublishedDate.appendChild(document.createTextNode(yy+"/"+mm+"/"+dd+" "+h+":"+m));
						gf_result.appendChild(gf_relativePublishedDate);
							var gf_snippet = document.createElement("div");
							gf_snippet.className = "gf-snippet";
							//gf_snippet.innerHTML = entry.content;
							if (rsFeedFetcher.truncate_length > 0) {
								gf_snippet.appendChild(document.createTextNode(truncate(stripTags(entry.content), rsFeedFetcher.truncate_length)));
							} else {
								gf_snippet.appendChild(document.createTextNode(stripTags(entry.content)));
							}
						gf_result.appendChild(gf_snippet);

						gfc_results.appendChild(gf_result);
					}

				gfc_resultsRoot.appendChild(gfc_results);

				gfc_control.appendChild(gfc_resultsRoot);
				elm.innerHTML = gfc_control.innerHTML;

			} else {
				rsFeedFetcher.no_cache = false;
				rsFeedFetcher.try_count--;
				if (rsFeedFetcher.try_count > 0) {
					//failedHandle(elm, "status:" + result.error.code + " " + result.error.message + " Reloading...[" + rsFeedFetcher.try_count + "]");
					setTimeout(function() {rsFeedFetcher.load()}, 1000);
				} else {
					failedHandle(elm, "status:" + result.error.code + " " + result.error.message);
				}
			}
		}
	} catch(e) {
		failedHandle(elm, e);
	}

	function failedHandle(elm, e) {
		var root = document.createElement("div");
		var resultError = document.createElement("div");
		resultError.className = "feed-result-error";

		resultError.appendChild(document.createTextNode("  Feedの取得に失敗しました。"));

		var reload_link = document.createElement("a");
		reload_link.href = "javascript:location.reload();";
		reload_link.appendChild(document.createTextNode("再読み込み"));
		resultError.appendChild(reload_link);

		resultError.appendChild(document.createTextNode(""));

		if (e) {
			var p = document.createElement("p");
			p.appendChild(document.createTextNode(e));
			resultError.appendChild(p);
		}
		root.appendChild(resultError);

		elm.innerHTML = root.innerHTML;
	}

	function getFirstImage(content, w, h, feed_link) {
		imgHTML = content.match(/<img\/?[^>]+>|<embed\ssrc=["|']?http:\/\/www\.youtube\.co\/?[^>]+>/i);
		img = null;
		if (imgHTML) {
			if (imgHTML.toString().match(/<embed\ssrc=["|']?http:\/\/www\.youtube\.co\/?[^>]+>/i)) {
				// youtube
				var videoId = imgHTML.toString().match(/v\/(\w+)/i)[1];
				if (videoId) {
					imgHTML = '<img src="http://i.ytimg.com/vi/' + videoId + '/default.jpg" />';
				}
			}
			img = document.createElement("img");
			img.src = "";
			//img.style.cssText = "width: 64px; height: auto;";
			if (isNumeric(w)) {
				w = w + "px";
			}
			if (isNumeric(h)) {
				h = h + "px";
			}
			img.style.cssText = "width: " + w + "; height: " + h + ";";
			img.border = 0;

			var div = document.createElement("div");
			div.innerHTML = imgHTML;
			var i = div.childNodes[0];
			img_src = "";
			if (i.src.match(/\.(jpe?g|png|gif)$/i)) {
				img_src = i.src;
			} else {
				return null;
			}
			if (img_src.match(/^file:\/\/\//i)) {
				img_src = img_src.replace('file:///', feed_link);;
			}
			img.src = img_src;

			/*
			if ((i.width > 10 && i.height > 10) || (i.style.width || i.style.height)) {
				img.src = i.src;
			} else {
				img = null;
			}*/
		}
		return img;
	}

	function isNumeric(num) {
		num = num + "";
		return (num - 0) == num && num.length > 0;
	}

	/*
	 * code from prototype.js
	 */
	function truncate(str, length, truncation) {
		length = length || 30;
		truncation = truncation === undefined ? '...' : truncation;
		return str.length > length ?
			str.slice(0, length - truncation.length) + truncation : str;
	}
	function stripTags(str) {
		return str.replace(/<\/?[^>]+>/gi, '');
	}
}