﻿function ZCastelWidget(tagName, qtdeFeeds) {
	this.widget = document.getElementById(tagName);
	this.qtdeFeeds = (qtdeFeeds > 0? ( qtdeFeeds <= 10 ? qtdeFeeds : 10 ): 10);
}

ZCastelWidget.prototype.criarElemento = function (tag, pai, id, conteudo) {
	var e = document.createElement(tag);
	
	if (id != null) e.id = id;		
	if (pai != null) pai.appendChild(e);
	if (conteudo != null) e.appendChild(conteudo);
	return e;		
}

ZCastelWidget.prototype.imagemRedim = function (imagem) {
	var largura = 176;
	
	var fator = largura / imagem.width;
	imagem.width = largura;
	imagem.height = imagem.height * fator;
}

ZCastelWidget.prototype.imagemDoPost = function (post) {
	var div = this.criarElemento('div');
	div.innerHTML = post.content;
	
	
	if (div.getElementsByTagName("img").length == 0)
		return null;
		
	var imagem = div.getElementsByTagName("img")[0];
	
	imagem.onload = function () {
		ZCastelWidget.prototype.imagemRedim(this);
	}
		
	return imagem;
}


ZCastelWidget.prototype.carregar = function (posts) {
	
	var ul = this.criarElemento('ul', this.widget); 
	
	for (var i = 0; i < posts.length && i < this.qtdeFeeds; i++) {
		post = posts[i];
		
		var li = this.criarElemento('li', ul, post.id);
		this.criarElemento('b', li, null, document.createTextNode(post.title));
		
		imagem = this.imagemDoPost(post);
		if (imagem != null)
			li.appendChild(imagem);
		
		this.criarElemento('spam', li, null, document.createTextNode(post.excerpt));
		var link = this.criarElemento('a', li, null, document.createTextNode("detalhes"));
		link.href = post.permalink;
		link.target = "_blank";
	}
}
