/*
 * jQuery OPMLit Plugin
 * version: 0.1
 * @requires jQuery v1.4.2 or later
 *
 * @author  James Pyrich <james at pyrich dot com> http://james.pyrich.com/
 */

(function($) {
	$.fn.opmlit = function(options) {
		options = $.extend({
			url: null,
			opml : null,
			autoload : null
		},
		options || {});

		var $opmlit = this;
		var $opmlarray = [];
		var $opmlheader, $opmlbody, $opmlfeeds, $opmlfeeddata, $opmlfeedheader, $opmlfeedlist, $opmlfeeditem;
		var $feeddoc;

		var onFeedHeaderClick = function() {
			$('.itemSelected').removeClass('itemSelected');
			$(this).addClass('itemSelected');

			var feedUrl = $(this).find('a').attr('href');

			var loadingHtml = '<div class="opmlit-feedheader-title"><span class="title">Loading feed...</span></div>';
			$opmlfeedheader.html(loadingHtml);
			$opmlfeedlist.empty();
			$opmlfeeditem.empty();
			$.ajax({
				url : options.url,
				data : {
					'feedUrl' : feedUrl,
					'opmlUrl' : options.opml
				},
				success : function(data) {
					$feeddoc = data;

					var channel = $($feeddoc).find('rss channel');
					if (channel.length == 0)
						return false;

					var title = channel.children('title').text();
					var description = channel.children('description').text();

					var html = '<div class="opmlit-feedheader-title">';
					//html += '<span class="title">' + title + '</span>';
					html += '<span class="desc">' + description + '</span>';
					html += '</div>';
					$opmlfeedheader.html(html);

					var itemList = $feeddoc.getElementsByTagName("item");
					for (var idx = 0; idx < itemList.length; idx++) {
						var itemEle = itemList[idx];
						var itemTitle = itemEle.getElementsByTagName('title')[0].childNodes[0].nodeValue;
						var itemUrl = itemEle.getElementsByTagName('guid')[0].childNodes[0].nodeValue;

						var html = '<div class="opmlit-feedlistitem';
						if (idx % 2 == 1)
							html += ' opmlit-altline';
						html += '">';
						html += '<a href="' + itemUrl + '" id="opmlit-feeditem-' + idx + '">';
						html += itemTitle;
						html += '</a>';
						html += '</div>';

						$opmlfeedlist.append(html);
					}

					$opmlfeedlist.find('.opmlit-feedlistitem').click(onFeedItemClick);
					$opmlfeedlist.find('.opmlit-feedlistitem:first-child').click();
				},
				dataType : 'xml'
			});

			return false;
		};

		var onFeedItemClick = function() {
			$('.opmlit-feedlistitem.itemSelected').removeClass('itemSelected');
			$(this).addClass('itemSelected');

			var feeditem = $(this).find('a');
			var feeditemid = feeditem.attr('id').replace(/^opmlit-feeditem-/, '');
			var feedIdx = -1;
			var zeMatch = feeditemid.match(/^[0-9]+$/);
			if (zeMatch.length == 0)
				return true;

			$opmlfeeditem.empty();
			feedIdx = zeMatch[0];

			var itemList = $feeddoc.getElementsByTagName("item");
			var item = itemList[feedIdx];

			if (typeof(item) == 'undefined' || item == null) {
				return true;
			}

			var itemTitle = item.getElementsByTagName('title')[0].childNodes[0].nodeValue;
			var itemUrl = item.getElementsByTagName('guid')[0].childNodes[0].nodeValue;
			var itemDesc = item.getElementsByTagName('description')[0].childNodes[0].nodeValue;
			var gmtDate = item.getElementsByTagName('pubDate')[0].childNodes[0].nodeValue;

			var pubDate = new Date(gmtDate);
			pubDate = pubDate.toLocaleDateString() + ' ' + pubDate.toLocaleTimeString();

			var html = '<div class="itemTitle">' + itemTitle + '</div>';
			html += '<div class="itemDate">' + pubDate + '</div>';
			html += '<div class="itemDescription">' + itemDesc + '</div>';

			html += '<div class="podplayer">';

			html += '<div class="audio_wrap html5audio">';
			html += '<div style="display:none;">';
			html += '<a href="' + itemUrl + '" title="Click to open" id="f-html5audio-0">Audio MP3</a>';
			html += '<script type="text/javascript">';
			html += 'AudioPlayer.embed("f-html5audio-0", {soundFile: "' + itemUrl + '"});';
			html += '</script>';
			html += '</div>';
			html += '<audio controls autobuffer id="html5audio-0" class="html5audio">';
			html += '<source src="' + itemUrl + '" type="audio/mpeg" />';
			html += '<a href="' + itemUrl + '" title="Click to open" id="f-html5audio-0">Audio MP3</a>';
			html += '<script type="text/javascript">';
			html += 'AudioPlayer.embed("f-html5audio-0", {soundFile: "' + itemUrl + '"});';
			html += '</script>';
			html += '</audio>';
			html += '</div>';
			html += '<script type="text/javascript">';
			html += 'if (jQuery.browser.mozilla) {';
			html += 'tempaud=document.getElementsByTagName("audio")[0];';
			html += 'jQuery(tempaud).remove();';
			html += 'jQuery("div.audio_wrap div").show();';
			html += '} else {';
			html += 'jQuery("div.audio_wrap div *").remove();';
			html += ' }';
			html += '</script>';

			html += '<div class="fileDownload"><a href="' + itemUrl + '">Download MP3</a></div>';

			html += '</div>';

			$opmlfeeditem.html(html);
			$opmlfeeditem.find('.feedflare').remove();

			return false;
		};

		var setValue = function(value) {
			$second.val(value).change();
		};

		var removeValues = function() {
			$($secondid + " option").remove();
		};

		var autoloadfeed = function() {
			var feednum = options.autoload;

			var anchor = document.location.hash;
			if (typeof(anchor) != 'undefined' && anchor != null && anchor.length > 0) {
				var matches = anchor.match(/^#feed-([0-9]+)$/);
				feednum = matches[1];
				if (typeof(feednum) == 'undefined' || feednum == null)
					return;
			}

			feednum--;
			if (feednum < 0 || feednum >= $opmlarray.length)
				return;

			var autofeed = $opmlarray[feednum];
			$opmlfeeds.find('a[href="' + autofeed + '"]').click();
		};

		$(this).change(function() {
			removeValues();
			$current = this.options[this.selectedIndex].value;
			if ($current != '') {
				$.each(values,
				function(k, v) {
					var bestk;
					if ($current == v.key) {
						$.each(v.values,
						function(k, v2) {
							if (!bestk && (v.defaultvalue !== null && v2 == v.defaultvalue)) {
								bestk = k;
							}
							if (options.preselectSecond !== null && v2 == options.preselectSecond) {
								bestk = k;
							}
						});
						$.each(v.values,
						function(k, v2) {
						  var o = $("<option>").html(k).attr('value', v2);
						  if (options.preselectSecond) {
							$.each(options.preselectSecond,
							  function(index, selected) {
								if (v2 == selected) o.html(k).attr("selected", "selected");
							  }
							);
						  }
						  o.appendTo($second);
						});
					}
				});

			} else {
				setValue(options.emptyValue);
			}
		});

		return this.each(function() {
			$opmlit.children().remove();
			$opmlit.addClass('opml-container');

			if (options.opml == null) {
				$opmlit.html("OPML URL required!");
				return;
			}

			var html = '';
			//html += '<div class="opmlit-header"></div>';
			html += '<div class="opmlit-body">';
			//html += '<div class="opmlit-feeds-header">Browse Freedomain Radio Feeds</div>';
			html += '<div class="opmlit-feeds"></div>';
			html += '<div class="opmlit-feeddata">';
			html += '<div class="opmlit-feedheader"><div class="opmlit-feedheader-title"><span class="title">Please select a feed above...</span></div></div>';
			html += '<div class="opmlit-feedlist"></div>';
			html += '<div class="opmlit-feeditem"></div>';
			html += '</div>';
			html += '<div class="opmlit-clear"></div>';
			html += '</div>';

			$opmlit.append(html);

			$opmlheader = $opmlit.find('.opmlit-header');
			$opmlbody = $opmlit.find('.opmlit-body');
			$opmlfeeds = $opmlit.find('.opmlit-feeds');
			$opmlfeeddata = $opmlit.find('.opmlit-feeddata');
			$opmlfeedheader = $opmlit.find('.opmlit-feedheader');
			$opmlfeedlist = $opmlit.find('.opmlit-feedlist');
			$opmlfeeditem = $opmlit.find('.opmlit-feeditem');

			$.ajax({
				url : options.opml,
				success : function(data) {
					var titleList = data.getElementsByTagName("title");
					var title = '';
					if (titleList.length > 0)
						title = titleList[0].childNodes[0].nodeValue;

					$opmlheader.html(title);

					var outlineList = data.getElementsByTagName("outline");
					for (var idx = 0; idx < outlineList.length; idx++) {
						var outlineEle = outlineList[idx];
						var html = '<div class="opmlit-feedlink">';
						html += '<a href="' + outlineEle.getAttribute('xmlUrl') + '">';
						html += outlineEle.getAttribute('text');
						html += '</a>';
						html += '</div>';
						$opmlfeeds.append(html);
						$opmlarray.push(outlineEle.getAttribute('xmlUrl'));
					}

					$opmlfeeds.find('.opmlit-feedlink').click(onFeedHeaderClick);

					autoloadfeed();
				},
				dataType : 'xml'
			});
		});
	};
})(jQuery);

