// This is a subclass of the RSSBadge class, which in turn is a
// subclass of the RSSViewer class.

/**
*
*  UTF-8 data encode / decode
*  http://www.webtoolkit.info/
*
**/

var BadgeUtf8 = {
    // public method for url decoding
    decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
};

function SyndicationBadge() {};

SyndicationBadge.prototype = {

	initialize: function(uniqueId, channel, options) {
		this.uniqueId = uniqueId;
		this.options = {
			decode: false
		};
		jQuery.extend(this.options, options || {});
	},
	
	initWithData: function(items, channel) {
		this.items = items;
		this.channel = channel;
	},

	decode: function(text) {
		if (this.options && this.options.decode) {
			return BadgeUtf8.decode(text);
		} else {
			return text;
		}
	},
	
	render: function() {

		// update the title
		if (this.channel) {
			jQuery('#'+this.uniqueId+'-title').html(this.decode(this.channel.title));
		}
		
		// grab the body
		var body = jQuery('#'+this.uniqueId + "-body");
		if (!body.length) {
			//console.log("Couldn't find body for displaying items");
			return;
		}
		
		// grab the template
		var template = jQuery('#'+this.uniqueId + "-template");
		if (!template.length) {
			//console.log("Couldn't find template for displaying items");
		}
		
		var keys = ["rssName", "rssDescription", "rssAuthor"];
		
		body.html(""); // blank out the Loading... message if there is one
	    for(var n=0; n < this.items.length; n++) {

			var newItem = template.clone();
			
			// would be better to rewrite the template so we find it's components
			// by class rather than by id
			for (var ki=0; ki<keys.length; ki++) {
				var k = keys[ki];
				newItem.find('#'+this.uniqueId + "-" + k).html(this.decode(this.items[n][k]));	
			}
			
			var d = new Date();
			d.setTime(Date.parse(this.items[n]['rssPublishDate']));
			newItem.find('#'+this.uniqueId + "-rssPubDate").html(d.toLocaleString());					
			newItem.find('#'+this.uniqueId + "-rssViewUrlInContext").attr("href" , this.items[n]['rssViewUrlInContext']);					
			body.append(newItem);
			newItem.show();
		}
	}
};
