(function($){

	if (!window.google) {
		alert(l_feed_no_api);
	}    

	if (!google.feeds) {    
        google.load("feeds", "1");
    }

	$.fn.jfeeds = function(ops) {
		var defaults = {
			url : '',
			start : 0,
			limit : 5,
			itemClass : 'feed_item',
			titleClass : 'feed_title',
			slideshow : false,
			settings : {},
			tags	: 'title,link',
			template : '<a href="{link}">{title}</a><br />'
		};

		var depth = 0;
		var element = 'media';
		var entry, element_store = [];
		var options = $.extend(defaults, ops);
		var container = this;
		var tagsArray = options.tags.split(',');
		options.limit += (options.start > 0) ? options.start : 0;
	
		if (!options.url) {
			$(container).html(l_no_feed_found);
			return false;
		}

		if (!google.feeds) {
			$(container).html(l_feed_api_not_loaded);
			return false;
		}

		var feed = new google.feeds.Feed(options.url);
		feed.setNumEntries(options.limit);

		feed.load(function(result) {
			if (!result.error) {
				var data = [];
				var contents = '';
				//var attributes = options.template.match(/(title|author|link|content|contentSnippet|publishedDate|categories|media(:[0a-z]+)+)/img);

				$.each(result.feed.entries, function(key, resp) {
					var str = options.template;
					entry = resp;
					if (entry.mediaGroups) {
						var mentry = entry.mediaGroups;
						media_parser(mentry[0], 0);
					}

					$.each(resp, function(type, replace) {
						var replace = (type === 'title') ? '<span class="' + options.titleClass + '">' + replace + '</span>' : replace;

						str = str.replace('{'+type+'}', replace);			
					});

					/*for (j = 0; j < attributes.length; j++) {
						var type = attributes[j];
						var replace = (type === 'title') ? '<span class="' + options.titleClass + '">' + entry[type] + '</span>' : entry[type];

						str = str.replace('{'+type+'}', replace);			
					}
					*/

					contents += '<div class="' + options.itemClass + '">' + str + '</div>';
				});

				if (contents !== '') {
					container.html(contents);

					if (options.slideshow) {
						var s_def = {itemsClass: '.'+options.itemClass, titlesClass: '.'+options.titleClass};
						var s_ops = $.extend(s_def, options.settings);
                        container.jslideshow(s_ops);
					}
				}
			} else {
				container.html(result.error.message);
			}
		});

		var media_parser = function(data, depth) {
			if ($.type(data) === 'object' || $.isArray(data)) {
				$.each(data, function(attribute, value) {
					var path = element + ':' + attribute;
					entry[path] = value;
					if ($.type(value) === 'object' || $.isArray(value)) {
						element_store[depth] = element;
						element = path;

						media_parser(value, depth + 1);
					}
				});

				if (depth > 0 && element_store[depth - 1]) {
					element = element_store[depth - 1];
				}
			}
		};
	};
})(jQuery);
