var _my;
var curProj = 0;

pageState = function() {
	var msg = '';
	var msgCleared = false;
	var msgAlertShown = false;
	var msgInProgress = false;
};

function init() {

	_my = new pageState();

/*
	Bubblify script
*/

$(".tt .tooltip").wrap('<span class="mytooltip"></div>');
$(".tt .tooltip").before('<span class="top"/>');
$(".tt .tooltip").after('<span class="bottom"/>');

$("#twitter").hide();

/*
	Projects browser
*/

// Initial view
//showProj(0);

// Set navigation buttons
$("div#projects a#projPrev").click(function() { return showProj(1); });
$("div#projects a#projNext").click(function() { return showProj(-1); });

// Projects can be a drag
var showmsgdrag = true;
var projectcolors = [];
nextdraghandler = function(e, el) {
	if (!projectcolors.length)
		projectcolors = ["#BA2C22","#99905A","#687F50","#AA9B61","#396640","#231E4C","#E5DB9E","#615A99","#E5A08F","#FEE89F","#8FC2E5","#9AcEA8","#A77FBC"];
	var nextdrag = $(el).css("background-color", projectcolors.pop()).next();
	if (nextdrag.length == 1) {
		if (nextdrag.attr("id") == null)
			nextdrag.easydrag().ondrop(nextdraghandler);
	} else if (showmsgdrag) {
		twalert("Well done, LEGO apprentice &nbsp;&gt;:)\\\-[&nbsp; May the force be with you");
		showmsgdrag = false;
	}
}
$("#projects .project:first").easydrag().ondrop(nextdraghandler);

/*
	Oneliner script
*/

$("input")[0].value = "Enter your message here and type 'EOF' at the end to send it.";

$("input").bind("click", function() { 
	if (!_my.msgCleared) {
		this.value = ""; 
		this.style.backgroundColor = '#fff';
		_my.msgCleared = true;
	}
});

$("input").bind("keyup", function(data) {
	if (_my.msgInProgress) return;
	// Check for enter
	if (data != null) {
		if (data.charCode == 0 && data.keyCode == 13 && !_my.msgAlertShown) {
			_my.msgAlertShown = true;
			twalert("Please type 'EOF' (without quotes) at the end of your message, and it will be sent (promise..!)");
			return false;
		}
	}
	// Check message
	_my.msg = this.value;
	if (_my.msg.length > 10) {
		var secretWord = 'EOF';
		if (_my.msg.substr(_my.msg.length-secretWord.length) == secretWord) {
			this.value = _my.msg.substr(0, _my.msg.length-secretWord.length);
			if (confirm('Are you ready to send your message?'))
			{
				_my.msgInProgress = true;
				$.post('res/oneliner.php', 
					{ msg: this.value }, function(response) {
						_my.msgInProgress = false;
						if (response == 'OK') {
							twalert('Thanks, your message has been sent');
							$("input")[0].style.backgroundColor = '#afa';
							$("input")[0].disabled = 'disabled';
							_my.msgCleared = false;
						} else {
							twalert('Sorry, there must have been some mistake :( Please try again later!');
						}
					});
			}
		}
	}
});

$(document).ajaxError(function() {
    if (window.console && window.console.error) console.error(arguments);
});

/*
	Twitter feed
*/

$.getJSON("res/twitter.php", function(data) {
	if (!data) return;
	$("#twitter").hide().find("li").remove(); // remove "loader"
	$.each(data, function(i, tweet) {
		$("#twitter ul").append("<li>"
			+ linktweet(tweet.text) + " "
			+ "<small><a href=\"http://twitter.com/" + tweet.user.screen_name + "/status/" + tweet.id + "\">" 
			+ relative_time(tweet.created_at)
			+ "</a></small></li>");
		});
	$("#twitter").slideDown("slow");
});
setTimeout("$('#twitter').show('slow')", 2000);

/*
	Bookmarks list
*/

$.getJSON("magpierss/linklist_json.php", function(data) {
	if (!data) return;
	$.each(data, function(i, rssitem) {
		$("#linkfeed").append("<p>"
			+ "<a href=\"" + rssitem.url + "\">" 
			+ rssitem.name + "</a> - "
			+ rssitem.text + "</p>");
	});
});

/*
	Friend list
*/

$.ajax({type:"GET", dataType:"xml", url:"http://oleg.utou.ch/foaf.rdf", complete:function(data) {
	if (!data) return;
	var json = $.xmlToJSON($.textToXML(data.responseText));
	if (!json || !json.Person) return;
	$(json.Person[0].knows).each(function() {
		$("#greetfeed").append("<p>"
			+ "<a href=\"" + $(this.Person[0].homepage[0]).attr('rdf:resource') + "\">" 
			+ $(this.Person)[0].name[0].Text + "</a></p>");
	});
}});

/*
	Feeds list
*/

$.ajax({type:"GET", dataType:"xml", url:"http://oleg.utou.ch/google-reader-subscriptions.xml", complete:function(data) {
	if (!data) return;
	$(data.responseXML).find('outline').each(function() {
		if($(this).attr('xmlUrl')) $("#feedfeed").append("<p>"
			+ "<a href=\"" + $(this).attr('xmlUrl') + "\">" 
			+ $(this).attr('title') + "</a></p>");
	});
}});

/*
	Wiki feed list
*/

$.ajax({type:"GET", dataType:"xml", url:"http://oleg.utou.ch/wiki/index.xml", complete:function(data) {
	if (!data) { $("#rssfeed").show(); return; }
	$("#rssfeed").find("li").remove(); // remove "loader"
	$(data.responseXML).find('item:lt(6)').each(function() {
		if($('title', this).text() != "UploadLog") $("#rssfeed ul").append("<li>"
			+ "<a href=\"http://oleg.utou.ch/wiki/" + $('link', this).text() + "\">" 
			+ $('title', this).text() + "</a> - " 
			+ $('description', this).text().replace(/<\/?[^>]+>/gi, '') + "</li>");
	});
}});

/*
	Compact page script
*/

$("div.linklist").hide("normal");

$("#links h5 a, #projects h4 a").bind("click", function() {
	$("div.linklist", this.parentNode.parentNode.parentNode).slideToggle("normal");
	return false;
});

$(".updates h4 a").bind("click", function() {
	$("div:first", this.parentNode.parentNode.parentNode).slideToggle("normal");
	return false;
});

/* Dipity timeline */
$('#dipity a').click(function() {
	$(this).parent().html('<iframe width="770" height="300" src="http://www.dipity.com/loleg/personal/embed_tl?bgcolor=%237A99C1&bgimg=/images/black_grad_up.png" style="border:1px solid #CCC; width:100%;"></iframe>');
	return false;
});
//'<p style="margin:0;font-family:Arial,sans;font-size:13px;text-align:center"><a href="http://www.dipity.com/loleg/personal">Oleg L.</a> on <a href="http://www.dipity.com/" />Dipity</a>.</p>'

}

/*
	HELPER FUNCTIONS
	----------------
*/

function showProj(nextproj) {
	var projList = $('div#projects');

	nextproj = curProj + nextproj;
	curProj = nextproj;

	// Hide all/show item
	$("div.project", projList).hide();
	$("div.project[@id='proj" + nextproj + "']", projList).show();

	if (nextproj > 10 || nextproj < 0) return false; // buggy browsers

	// Update nav buttons
	$("a#projPrev", projList)[0].style.visibility = (nextproj > 0) ? "visible" : "hidden";
	$("a#projNext", projList)[0].style.visibility = 
		($("div.project[@id='proj" + (nextproj+1) + "']", projList).length) ? "visible" : "hidden";

	return false;
}

function imageBox(url) {

	if(!$('#imgbox').length) {
		$('<div id="imgbox"></div>').appendTo('body').hide();
	}

	$('#imgbox').html(
		'<a href="#" onclick="closeImageBox();">' +
		'<img src="' + url + '" title="Click to close"/>' +
		'</a>')
		.css({
			position: 'absolute', left: '1px', top: '1px'
			})
		.show("normal");

	return false;
}

function closeImageBox() {

	$('#imgbox').hide();
}

/*
	Kind thanks to Ralph Whitbeck
	http://www.damnralph.com
*/
function relative_time(time_value) {
	  var values = time_value.split(" ");
	  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
	  var parsed_date = Date.parse(time_value);
	  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	  delta = delta + (relative_to.getTimezoneOffset() * 60);
	  
	  var r = '';
	  if (delta < 60) {
		r = 'a minute ago';
	  } else if(delta < 120) {
		r = 'couple of minutes ago';
	  } else if(delta < (45*60)) {
		r = (parseInt(delta / 60)).toString() + ' minutes ago';
	  } else if(delta < (90*60)) {
		r = 'an hour ago';
	  } else if(delta < (24*60*60)) {
		r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
	  } else if(delta < (48*60*60)) {
		r = '1 day ago';
	  } else {
		r = (parseInt(delta / 86400)).toString() + ' days ago';
	  }
	  return r;
}

/*
	Adapted from seaofclouds
	http://tweet.seaofclouds.com/
	http://github.com/seaofclouds
*/
function linktweet(txt) {
	// linkUrl
	var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
	txt = txt.replace(regexp,"<a href=\"$1\">$1</a>");
    // linkUser
	regexp = /[\@]+([A-Za-z0-9-_]+)/gi;
    txt = txt.replace(regexp,"<a href=\"http://twitter.com/$1\">@$1</a>");
    // linkHash
	regexp = / [\#]+([A-Za-z0-9-_]+)/gi;
    txt = txt.replace(regexp, ' <a href="http://search.twitter.com/search?q=&tag=$1&lang=all">#$1</a>');
	// makeHeart <3
	txt = txt.replace(/[&lt;]+[3]/gi, "<tt class='heart'>&#x2665;</tt>");
	return txt;
}

/*
	Twitter style alerts
*/
function twalert(txt) {
	$("#twalert").html(txt).slideDown("slow");
	// Todo: cancel the timeout or something for overlapping messages..
	setTimeout("$('#twalert').slideUp('slow')", 15000);
}
