var config = new Object();
var start = 0;
var all_posts = [];
var total_posts = 0;
var tag_filter = false;

/*
function glc(el)
{
    return (el.lastChild && el.lastChild.nodeName != '#text') ? glc(el.lastChild) : el
}

var params = glc(document.lastChild).getAttribute('src').replace(/.*\?/, '');
*/

var scripts = document.getElementsByTagName('script');
var params = scripts[scripts.length-1].src.replace(/.*\?/, '');

params = params.split("&");

for(var i=0; i<params.length; i++)
{
    var tmp = params[i].split("=");
    config[tmp[0]] = unescape(tmp[1]);
}

if(typeof(config.num) == 'undefined') config.num = 30; //arbitrary limit, sorry
if(typeof(config.tagged) != 'undefined') tag_filter = true;

var url_base = ((typeof(config.url) == 'undefined') ?
    ('http://' + document.domain + '/') : ('http://' + config.url + '/'));

document.write(
    '<div id="recent_posts">' + 
        '<div id="loading_recent_posts">Loading Recent Posts...</div>' +
        '<ul id="recent_posts_list"></ul>' + 
    '</div>'
);

$(document).ready(function()
{    
    function getPosts() {
        $.getJSON(url_base+'api/read/json?callback=?&num=50&filter=text&start='+start, function(data)
        {
            $(data.posts).each(function(i, post)
            {
				if (total_posts==config.num) return;
				if (tag_filter) {
					tagged = false;
					$(post.tags).each(function(i, tag)
					{
						if((typeof(tag) == 'string') && (config.tagged==tag)) {
							tagged=true;
						}
					});
					if (!tagged) return;
				}
				title = post['regular-title'];
				if (!title) {
					title = post[post['type']+'-caption'] || post[post['type']+'-text'];
				}
				all_posts.push([title,post.url]);
				total_posts++;
            });
            if ((start+50 < data['posts-total']) && (total_posts<config.num))
            {
                start = start + 50;
                getPosts();
            }
            else 
            {
                showPosts();
            }
        });
    }
    
    function showPosts()
    {
		count = 0;
        $(all_posts).each(function(i, post)
        {
			count++;
            if(typeof(config.limit) != 'undefined' && 
                    config.limit != 'none' && 
                    count > config.limit) {
                return;
            }
			link = '<li><a href="'+post[1]+'" title="'+post[0]+'">'+post[0]+'</a></li>';
            $("#recent_posts_list").append(link);
        });
		
        $("#loading_recent_posts").html('');
    }
    
    getPosts();
    
});