﻿JN.Twitter = new (function() {
	var container = document.createElement("div", {id: "twitter"});
	var visible = false, to;
	JN.Events.Content.opening.listen( onContentOpen );
	JN.Events.Content.closed.listen( onContentClose );
	addLoadEvent( function() {
		to = setTimeout(function () {buildTwitterNodes([]);}, 2000);
		(new J2.ADIJ( {
			URL: "http://twitter.com/status/user_timeline/nortools.json?count=3",
			onSuccess: handleADIJ,
			isJSONP: true
		} )).send();
	} );
	
	function handleADIJ(adij) {
		clearTimeout(to);
		var data = adij.getResponseText();
		if (data && data.length && data.length > 0) {
			buildTwitterNodes(data);
		}
	}
	
	function onContentOpen() {
		container.animate( {
			opacity: {
				to: 0,
				time: 300
			}
		}, function() { container.remove() } );
	}
	
	function onContentClose() {
		document.body.appendChild(container);
		container.animate( {
			opacity: {
				to: 1,
				transition: J2.Transitions.Exp.easeIn
			}
		} );
	}
	
	function buildTwitterNodes(data) {
		var item, innerSpan;
		if (visible === false) {
			var h2 = container.appendChild( document.createElement("h2", {
					innerHTML: "My latest tweets"
				} ) );
			h2.appendChild( document.createElement("a", {
				href: "http://twitter.com/nortools",
				innerHTML: "view all"
			} ) );
			container.setStyle("opacity", 0);
		}
		for (var i = 0; i<data.length; i++) {
			item = document.createElement("p", {innerHTML: getText(data[i].text)});
			innerSpan = item.appendChild(document.createElement("span"));
			innerSpan.appendChild( document.createElement("a", {
				href: "http://twitter.com/nortools/status/" + data[i].id,
				innerHTML: "created: " + getDate(data[i].created_at)
			} ) );
			container.appendChild( item );
		}
		if (item) item.addCssClass("last");
		drawTwitterNodes(container);
	}
	
	function drawTwitterNodes(container) {
		if (JN.Content.visible) return;
		document.body.appendChild(container);
		if (visible === false) {
			container.animate( {
				opacity: 1
			} );
		}
		visible = true;
	}
	
	function getDate( d ) {
		var v = d.split(" ");
		d = new Date( Date.parse(v[1] + " " + v[2] + ", " + v[5] + " " + v[3]) );
		return	d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getFullYear() + 
				" " +
				padZeros(d.getHours()) + ":" + padZeros(d.getMinutes());
	}
	function getText(t) {
		return t.replace( /((https?):(\/\/)+[\w\d:#@%\/;$()~_?\+-=\\\.&]*)/gi, "<a href=\"$1\">$1</a>")
				.replace( /(@)([\w\.]+)/gi, "$1<a href=\"http://twitter.com/$2\">$2</a>");
	}
	function padZeros(n) {
		n = n + "";
		while (n.length < 2) {
			n = "0" + n;
		}
		return n;
	}
});