/////////////////////////////////////////////////////////////////////
// Load del.icio.us data

if (typeof(Delicious) == 'undefined') {
    document.getElementById('bookmarks').appendChild(document.createTextNode("Couldn't find JSON object 'Delicious'!"));
} else {
    var ul = createElement('ul');
    for (var i=0; i < Delicious.posts.length; i++) {
        var post = Delicious.posts[i];
        var li = createElement('li');
        var a = createElement('a');
        a.setAttribute('href', post.u);
        a.setAttribute('rel', 'external');
	a.setAttribute('title', post.n);
        appendText(a, post.d);
        li.appendChild(a);
        li.appendChild(document.createTextNode(" / "));
        var tags = " /";
        var small = createElement('span');
        small.className = 'small';
        for (tag in post.t) {
            var ta = createElement('a');
            ta.setAttribute('href', 'http://del.icio.us/catslaugh/' + post.t[tag]);
            ta.setAttribute('rel', 'external');
            appendText(ta, post.t[tag]);
            small.appendChild(ta);
            small.appendChild(document.createTextNode(" "));
        }
        li.appendChild(small);
        ul.appendChild(li);
    }
    document.getElementById('bookmarks').appendChild(ul);
}

/////////////////////////////////////////////////////////////////////
// Load LiveJournal data

if (typeof(LJ) == 'undefined') {
    document.getElementById('livejournal').appendChild(document.createTextNode("Couldn't find JSON object 'LJ'!"));
} else {
    var ul = createElement('ul');
    for (var i=0, post; i < 10 && (post = LJ.entries[i]); i++) {
        var li = createElement('li');
        var a = createElement('a');
        a.setAttribute('href', post.url);
        a.setAttribute('rel', 'external');
        appendText(a, post.subject);
        li.appendChild(a);
        li.appendChild(document.createTextNode(" / "));
        var small = createElement('span');
        small.className = 'small';
        for (var j=0, tag; tag = post.tags[j]; j++) {
            var ta = createElement('a');
            ta.setAttribute('href', tag.url);
            ta.setAttribute('rel', 'external');
            appendText(ta, tag.name);
            small.appendChild(ta);
            small.appendChild(document.createTextNode(" "));
        }
        li.appendChild(small);
        ul.appendChild(li);
    }
    document.getElementById('livejournal').appendChild(ul);
}

/////////////////////////////////////////////////////////////////////
// Create routines to be called by LibraryThing

function reading(results) {
    var books = results.books;
    if (books == null) return;
    var ul = createElement('ul');
    for (key in books) {
        var book = books[key];
        var li = createElement('li');
        li.appendChild(document.createTextNode(book.title + " by " + book.author_fl));
        ul.appendChild(li);
    }
    document.getElementById('reading').appendChild(ul);
}

function bookreview(results) {
    var books = results.books;
    if (books == null) return;
    for (key in books) {
        var book = books[key];
        var div = createElement('div');
//        div.setAttribute('class', 'flow');
        div.className='flow'; // .setAttribute() doesn't work on IE
        var anchor = createElement('a');
        anchor.setAttribute('href', 'http://www.librarything.com/work/book/' + book.book_id);
        if (book.cover) {
            var img = createElement('img');
            img.setAttribute('src', book.cover);
            img.setAttribute('title', convertText(book.title + ", by " + book.author_fl));
            anchor.setAttribute('rel', 'external');
            anchor.appendChild(img);
            div.appendChild(anchor);
            if (book.hasreview > 0) {
                div.appendChild(createElement('br'));
                var reviewlink = createElement('a');
                if (book.rating > 0) {
                    var stars = createElement('img');
                    // ss1 = 1/2; ss10 = 5 stars
                    stars.setAttribute('src', 'http://static.librarything.com/pics/ss' + (book.rating*2) + '.gif');
                    reviewlink.appendChild(stars);
                } else {
                    reviewlink.appendChild(document.createTextNode("(review)"));
                }
                reviewlink.setAttribute('href', 'http://www.librarything.com/review/' + book.book_id);
                reviewlink.setAttribute('rel', 'external');
                reviewlink.className = 'reviewlink';
                div.appendChild(reviewlink);
            }
        } else {
            anchor.appendChild(document.createTextNode(book.title));
            div.appendChild(anchor);
            div.appendChild(document.createTextNode(" by " + book.author_fl));
        }
        document.getElementById('reviews').appendChild(div);
    }
}

function acquisition(results) {
    var books = results.books;
    if (books == null) return;
    for (key in books) {
        var book = books[key];
        var div = createElement('div');
        div.className='flow'; // .setAttribute() doesn't work on IE
        var anchor = createElement('a');
        anchor.setAttribute('href', 'http://www.librarything.com/work/book/' + book.book_id);
        if (book.cover) {
            var img = createElement('img');
            img.setAttribute('src', book.cover);
            img.setAttribute('title', convertText(book.title + ", by " + book.author_fl));
            anchor.setAttribute('rel', 'external');
            anchor.appendChild(img);
            div.appendChild(anchor);
        } else {
            anchor.appendChild(document.createTextNode(book.title));
            div.appendChild(anchor);
            div.appendChild(document.createTextNode(" by " + book.author_fl));
        }
        document.getElementById('acquisitions').appendChild(div);
    }
}

// Inline information from Flickr
function jsonFlickrApi(rsp) {
    if (rsp.stat != "ok") {
	var error = document.createTextNode(rsp.stat + " (error " + rsp.code +
					    "):  " + rsp.message);
	document.getElementById('flickr').appendChild(error);
	return;
    }
    var pix = rsp.photos.photo;
    if (pix == null) {
	document.getElementById('flickr').appendChild(document.createTextNode("no pix!"));
	return;
    }
    for (var i = 0; i < pix.length; i++) {
	if (i > 0) {
	    document.getElementById('flickr')
		.appendChild(document.createTextNode(" "));
	}

	var pic = pix[i];
	var title = document.createTextNode(pic["id"]);
	var url_img = "http://farm" + pic["farm"] + ".static.flickr.com/"
	    + pic["server"] + "/" + pic["id"] + "_" + pic["secret"]
	    + "_t.jpg";
	var img = createElement('img');
	img.setAttribute('src', url_img);
	img.setAttribute('title', pic["title"]);
	var anchor = createElement('a');
	var url_page = 'http://flickr.com/photos/catslaugh/' +
	    pic["id"] + "/";
	anchor.setAttribute('href', url_page);
	anchor.setAttribute('rel', 'external');
	anchor.appendChild(img);
	document.getElementById('flickr').appendChild(anchor);
    }
}

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

// Handle the Twitter callback
function tweet(tweets)
{
    var debug = 5;
    var pattern = / ?((https?:\/\/[^ >]+)|([@#][-A-Za-z0-9_]+))/g;
    var ul = createElement('ul');
    for (var i = 0; i < tweets.length; ++i) {
        var tweet = tweets[i];
        var li = createElement('li');
	// text does not quote for HTML.
	var text = tweet.text.replace("&", "&amp;");
	var begin = 0;
	while (text != "") {
	    var matches = pattern.exec(text);
	    if (matches == null) {
		appendText(li, text.substr(begin) + " ");
		                          // add a space before the timestamp
		text = "";
		break;
	    }
	    if (matches.length == 4) {
		var hypertext = matches[1];
		var leading = (pattern.lastIndex - hypertext.length) - begin;
		if (leading > 0) {
		    appendText(li, text.substr(begin, leading));
		}
		var anchor = createElement('a');
		var hyperlink = hypertext;
		if (hyperlink.substr(0,1) == "@") {
		    hyperlink = 'http://twitter.com/' + hyperlink.substr(1);
		} else if (hyperlink.substr(0,1) == "#") {
		    hyperlink = 'http://twitter.com/search?q=%23' + hyperlink.substr(1);
		}
		anchor.setAttribute('href', hyperlink);
		anchor.setAttribute('rel', 'external');
		appendText(anchor, hypertext);
		li.appendChild(anchor);
		begin = pattern.lastIndex;
	    }
	}

        var a = createElement('a');
	a.className = 'small';
	a.setAttribute('href', 'http://twitter.com/mithriltabby/statuses/' + tweet.id);
	a.setAttribute('rel', 'external');
	// IE 8 can't just handle "new Date(tweet.created_at)".
	var values = tweet.created_at.split(" ");
	var date = new Date(values[1] + " " + values[2] + ", " + values[5] + " " + values[3] +" " + values[4]);
	a.setAttribute('title', date);
	var now = new Date();
	var delta = now.getTime() - date.getTime();
	var dateText = "moments ago"
	if (delta > 24*60*60*1000) {
	    // Just give the date as HH:MM mmm dd
	    dateText = date.getHours() + ":" + (date.getMinutes() < 10 ? "0" : "") + date.getMinutes() + " "
                       + months[date.getMonth()] + " " + date.getDate();
            switch (date.getDate() % 10) {
		case 1:	dateText += "st"; break;
		case 2: dateText += "nd"; break;
		case 3: dateText += "rd"; break;
		default: dateText += "th"; break;
            }
	} else if (delta > 3600000) {
	    dateText = "about ";
	    var hours = Math.round(delta / 3600000);
	    dateText += hours + (hours == 1 ? " hour ago" : " hours ago");
	} else if (delta > 60*1000) {
	    var minutes = Math.round(delta / 60000);
	    dateText = minutes
		+ (minutes == 1 ? " minute ago" : " minutes ago");
	}
        appendText(a, dateText);
        li.appendChild(a);

	if (tweet.in_reply_to_user_id != null) {
	    appendText(li, " ");
	    // Link to user
	    var reply = createElement('a');
	    reply.className = 'small';
	    reply.setAttribute('rel', 'external');
	    appendText(reply, "in reply to " + tweet.in_reply_to_screen_name);
	    if (tweet.in_reply_to_status_id != null) {
		// Link to particular status
		reply.setAttribute('href', 'http://twitter.com/' + tweet.in_reply_to_screen_name + '/statuses/' + tweet.in_reply_to_status_id);
	    }
	    li.appendChild(reply);
	}
	if (tweet.geo != null && tweet.geo.type == "Point") {
	    appendText(li, " ");
	    var location = createElement('a');
	    location.className = 'small';
	    location.setAttribute('rel', 'external');
	    appendText(location, "\u203b");
	    location.setAttribute('href', 'http://maps.google.com/?sll=' + tweet.geo.coordinates[0] + ',' + tweet.geo.coordinates[1]);
	    li.appendChild(location);
        }
        ul.appendChild(li);
    }
    document.getElementById('twitter').appendChild(ul);
}
