$(document).ready(function() {
	
	var delayed;
	var newright = 0;
	var timelinewidth = 0;
	var intextbox = false;
	
	/* Get template directory, required for AJAX calls.
	 * Not at all elegant, but functional.
	 */
	var templatedir = $(".neverseeme").attr('id');
	$(".neverseeme").remove();
		
	function clearoverlays() {
		$(".attachment").remove();
		$(".inlinepost").remove();
		$(".overlay").remove();
	}
	
	/* Scroll with arrow keys & close overlay */
	
	$(document).bind('keydown', function(e) {
		if (e.keyCode == 27){
			clearoverlays();
		}
			
		$("#postline").css({ right : newright + 'px' });
		var right = $("#postline").css('right').replace("px", "");
		var postlinewidth = $(".post").size() * 330;
		
		if ((right < 0) && e.keyCode == 39 && intextbox == false) {
			newright = (parseInt(right) + 330);
			if (newright > 0) { 
				newright = 0;
			}			
			$("#postline").animate({ right : newright + 'px' }, 100);
		}
		if ((right > -postlinewidth + 330) && e.keyCode == 37 && intextbox == false) {
			newright = (parseInt(right) - 330);
			$("#postline").animate({ right : newright + 'px' }, 100);
		}
		return true;
	});
	
	$("input").livequery("focus", function() {
		intextbox = true;
	}).livequery("blur", function() {
		intextbox = false;
	});
	
	$(".postlink").livequery('click', function() {
		var link = $(this).attr('href');
		clearoverlays();
		$('body').append("<div class='inlinepost'><div class='postinner'><img src='" + templatedir + "images/ajax-loader.gif' /></div></div>");
		$.ajax({
			type: "GET",
			url: link + "?ajax=1",
			dataType: "html",
			success: function(html, status) {
				$('body').append("<div class='overlay'></div>");
				$(".inlinepost").css({ 'top' : '100px', 'width' : '600px', 'margin-left' : '-310px' }).html(html);
			}
		});
		return false;
	});
	
	$("#pagespanel a").livequery('click', function() {
		var link = $(this).attr('href');
		clearoverlays();
		$('body').append("<div class='inlinepost'><div class='postinner'><img src='" + templatedir + "images/ajax-loader.gif' /></div></div>");
		$.ajax({
			type: "GET",
			url: link + "?ajax=1",
			dataType: "html",
			success: function(html, status) {
				$('body').append("<div class='overlay'></div>");
				$(".inlinepost").css({ 'top' : '100px', 'width' : '600px', 'margin-left' : '-310px' }).html(html);
			}
		});
		return false;
	});
	
	$(".showtrackbacks").livequery('click', function() {
		if ($(".showtrackbacks").html() == 'Hide') {
			$("#trackbacks").fadeOut(500);
			$(".showtrackbacks").html("Show")		
		} else {
			$("#trackbacks").fadeIn(500);
			$(".showtrackbacks").html("Hide")
		}
		return false;
	});
	
	/* Toggle image zoom icon */
	
	$(".post img").livequery('mouseover', function() {
		$(this).parent().parent().parent().find(".imgzoom").show();
	}).livequery('mouseout', function() {
		$(this).parent().parent().parent().find(".imgzoom").hide();
	});
	
	/* Play Youtube video */

	$(".playthis").livequery('click', function() {
		clearTimeout(delayed);
		var attach = $(this).find('span').attr('href');
		var id = $(this).find('span').attr('rel');		
		clearoverlays();
		$('body').append("<div class='attachment'><img src='" + templatedir + "images/ajax-loader.gif' /></div>");
		$('body').append("<div class='overlay'></div>");		
		$(".attachment").html('<div id="ytapiplayer">You need Flash player 8+ and JavaScript enabled to view this video.</div>');		
		
		var params = { allowScriptAccess: "always", bgcolor: "#000000" };
		var atts = { id: "myytplayer" };
		
		swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=ytplayer", "ytapiplayer", "640", "360", "8", null, null, params, atts);	
		
		$(".attachment").css({ 'left' : ($(window).width() / 2 - 330) });
		$(".attachment").css({ 'top' : ($(window).height() / 2 - 190) });
		
		$(".attachment").append('<div class="buttons"><img src="' + templatedir + 'images/pause.png" /></div>');
		
		$.ajax({
			type: "GET",
			url: templatedir + "ajax.php?getyoutube=1&attach=" + attach + "&id=" + id,
			dataType: "html",
			timeout: 30000,
			success: function(html, status) {
				$(".attachment").prepend(html);
			}
		});
			
		delayed = setTimeout(function() {
			loadNewVideo(attach, 0);
		}, 2500);
		
		play();

		return false;
	});
	
	$(".buttons img").livequery('click', function() {
		if (getPlayerState() == 1) {
			pause();
			$(".attachment").append('<div class="buttons"><img src="' + templatedir + 'images/play.png" /></div>');
		} else {
			play();
			$(".attachment").append('<div class="buttons"><img src="' + templatedir + 'images/pause.png" /></div>');
		}
	});
	
	$(".attachment object").livequery('mouseover', function() {
		$(this).parent().find(".imgtags").show();
		$(this).parent().parent().find(".buttons").show();
	}).livequery('mouseout', function() {
		$(this).parent().find(".imgtags").hide();
		$(this).parent().parent().find(".buttons").hide();
	});
	
	$(".buttons").livequery('mouseover', function() {
		$(this).show();
	});
	
	/* Zoom image */

	$(".zoomthis").livequery('click', function() {
		var attach = $(this).find('a').attr('href');
		var id = $(this).find('a').attr('rel');
		clearoverlays();
		$('body').append("<div class='attachment'><img src='" + templatedir + "images/ajax-loader.gif' /></div>");
		$("<img src=" + templatedir + "timthumb.php?src=" + attach + "&h=600&w=800&q=100 />") .load(function() {
			$('body').append("<div class='overlay'></div>");
			$(".attachment").html($(this));
			$(".attachment").css({ 'left' : ($(window).width() / 2 - ($(this).width() / 2) - 10) });
			$(".attachment").css({ 'top' : ($(window).height() / 2 - ($(this).height() / 2) - 10) });
		}); 
		$.ajax({
			type: "GET",
			url: templatedir + "ajax.php?getattachment=1&attach=" + attach + "&id=" + id,
			dataType: "html",
			timeout: 30000,
			success: function(html, status) {
				$(".attachment").prepend(html);
			}
		});
		return false;
	});
	
	$(".attachment img").livequery('mouseover', function() {
		$(this).parent().find(".imgtags").show();
	}).livequery('mouseout', function() {
		$(this).parent().find(".imgtags").hide();
	});
	
	$(".imgtags").livequery('mouseover', function() {
		$(this).show();
	});
	
	$(".overlay").livequery('click', function() {
		clearoverlays();
	});

	/* Toggle month stats */
	
	$("#timeline li a").livequery('mouseenter', function() {
		if (jQuery.support.style == true) {
			var link = $(this).attr('rel');
			var awidth = $(this).width() + 20;
			var pwidth = $("#" + link ).find(".text").width();
			var pos = -45 + (awidth / 2);
			$('#pos').html("-40 + " + awidth + " / 2 = " + pos);
			$("#" + link).css({ left : pos + 'px' });
			$("#" + link).fadeIn(200);
			$("#" + link).css({ display : 'inline' });
		} // Disable stats in IE, causes all sorts of problems
	});
	
	$("#timeline li a").livequery('mouseout', function() {
		$(".monthstats").hide();
	});
	
	/* Scroll postline */
	
	$("#postline").livequery('mousewheel', function(event, delta) {
		$("#postline").css({ right : newright + 'px' });
		var right = $("#postline").css('right').replace("px", "");
		var postlinewidth = $(".post").size() * 330;
		
		if ((right < 0) && (delta > 0)) {
			newright = (parseInt(right) + 330);
			if (newright > 0) { 
				newright = 0;
			}			
			$("#postline").animate({ right : newright + 'px' }, 100);
		}
		if ((right > -postlinewidth + 330) && (delta < 0)) {
			newright = (parseInt(right) - 330);
			$("#postline").animate({ right : newright + 'px' }, 100);
		}
	});

	/* Scroll to month anchor */

	$(".month").livequery('click', function() {
		var link = $(this).attr('href');
		var offset = $(link).position();
		var pos = ($("#postline").width() - offset.left)
		$("#postline").animate({ right : "-" + pos + "px" }, 1000, 'easeInOutExpo');
		newright = -pos;
		return false;
	});
	
	/* Toggle popup boxes */
	
	$(".show-popup").click(function() {
		var rel = $(this).attr('rel');
		var height = parseInt($("#" + rel).css('height'), 10);
		$(".popup:not(#" + rel + ")").parent().animate({'height' : '24px'}, 100);
		$(".popup:not(#" + rel + ")").hide();
		if ( $("#" + rel).is(':visible') ) {
			$("#" + rel).hide();
			$(this).parent().animate({'height' : '24px'}, 100);
		} else {
			$("#" + rel).css({ 'height' : '0px' });
			$("#" + rel).show();
			$(this).parent().css({'height' : '30px'});
			$("#" + rel).animate({'height' : height + 'px'}, 100);
			if ( rel == 'search' ) { $("#s").focus(); }
		}
		return false;
	});
	
	/* Scroll timeline */ 
	
	$(function(){
		var sum = 0;
		$('#timeline li').each(function(){
			sum += $(this).width();
		});
		timelinewidth = sum + 10;
		return false;
	});
	
	$("#moveright").livequery("mouseenter", function(){
		var right = $("#timeline").css('right').replace("px", "");
		$("#timeline").animate({ right : '0px'}, right.replace("-", "") * 3);
	}).livequery("mouseout", function(){
		$("#timeline").stop();
	});
	
	$("#moveleft").livequery("mouseenter", function(){
		var right = $("#timeline").css('right').replace("px", "");
		$("#timeline").animate({ right : '-' + (timelinewidth - $(window).width() + 25) + 'px'}, ((timelinewidth - $(window).width() + 25) - right.replace("-", "")) * 3);
	}).livequery("mouseout", function(){
		$("#timeline").stop();
	});
	
	/* Toggle pages list */
	
	$("#pages").click(function() {
		if ($("#pagespanel").is(":visible")) {
			$("#pages").removeClass("selected");
			$("#pagespanel").hide();
		} else {
			$(".panel").hide();
			$(".button").removeClass("selected");
			$("#pages").addClass("selected");
			$("#pagespanel").show().css({ bottom : $("#pagespanel").height() + 36 }).css({ left : $("#pages").position().left - 1 });
		}
		return false;
	});
	
	/* Get recent activity */
	
	$("#recents").click(function() {
		if ($("#recentspanel").is(":visible")) {
			$("#recents").removeClass("selected");
			$("#recentspanel").hide();
		} else {
			$(".panel").hide();
			$(".button").removeClass("selected");
			$("#recents").addClass("selected");
			$("#recentspanel").show().css({ bottom : $("#recentspanel").height() + 36 }).css({ left : $("#recents").position().left - 1 });
			$.ajax({
				type: "GET",
				url: templatedir + "ajax.php?getrecents=1",
				dataType: "html",
				success: function(html, status) {
					$("#recentspanel").find("#recentslist").remove();
					$("#recentspanel").html("<ul id='recentslist'>" + html + "</ul><div class='clearer'></div>").css({ bottom : $("#recentspanel").height() + 36 });
				}
			});
		}
		return false;
	});
	
	/* Get hot posts */
	
	$("#hot").click(function() {
		if ($("#hotpanel").is(":visible")) {
			$("#hot").removeClass("selected");
			$("#hotpanel").hide();
		} else {
			$(".panel").hide();
			$(".button").removeClass("selected");
			$("#hot").addClass("selected");
			$("#hotpanel").show().css({ bottom : $("#hotpanel").height() + 36 }).css({ left : $("#hot").position().left - 1 });
			$.ajax({
				type: "GET",
				url: templatedir + "ajax.php?gethot=1",
				dataType: "html",
				success: function(html, status) {
					$("#hotpanel").find("#hotlist").remove();
					$("#hotpanel").html("<ul id='hotlist'>" + html + "</ul><div class='clearer'></div>").css({ bottom : $("#hotpanel").height() + 36 });
				}
			});
		}
		return false;
	});
	
	/* Toggle feeds list */
	
	$("#feeds").click(function() {
		if ($("#feedspanel").is(":visible")) {
			$("#feeds").removeClass("selected");
			$("#feedspanel").hide();
		} else {
			$(".panel").hide();
			$(".button").removeClass("selected");
			$("#feeds").addClass("selected");
			$("#feedspanel").show().css({ bottom : $("#feedspanel").height() + 36 }).css({ left : $("#feeds").position().left - 1 });
		}
		return false;
	});
	
	/* Toggle votd list */
	
	$("#votd").click(function() {
		if ($("#votdpanel").is(":visible")) {
			$("#votd").removeClass("selected");
			$("#votdpanel").hide();
		} else {
			$(".votd").hide();
			$(".button").removeClass("selected");
			$("#votd").addClass("selected");
			$("#votdpanel").show().css({ bottom : $("#votdpanel").height() + 36 }).css({ left : $("#votd").position().left - 1 });
		}
		return false;
	});
	
	/* Toggle meebo list */
	
	$("#meebo").click(function() {
		if ($("#meebopanel").is(":visible")) {
			$("#meebo").removeClass("selected");
			$("#meebopanel").hide();
		} else {
			$(".meebo").hide();
			$(".button").removeClass("selected");
			$("#meebo").addClass("selected");
			$("#meebopanel").show().css({ bottom : $("#meebopanel").height() + 36 }).css({ left : $("#meebo").position().left - 1 });
		}
		return false;
	});
	
	/* Get lastfm tracks */
	
	$("#lastfm").click(function() {
		if ($("#lastfmpanel").is(":visible")) {
			$("#lastfm").removeClass("selected");
			$("#lastfmpanel").hide();
		} else {
			$(".panel").hide();
			$(".button").removeClass("selected");
			$("#lastfm").addClass("selected");
			$("#lastfmpanel").show().css({ bottom : $("#lastfmpanel").height() + 36 }).css({ left : $("#lastfm").position().left - 1 });
			$.ajax({
				type: "GET",
				url: templatedir + "ajax.php?getlastfm=1",
				dataType: "html",
				success: function(html, status) {
					$("#lastfmpanel").find("#lastfmlist").remove();
					$("#lastfmpanel").html("<ul id='lastfmlist'>" + html + "</ul><div class='clearer'></div>").css({ bottom : $("#lastfmpanel").height() + 36 });
				}
			});
		}
		return false;
	});
	
	/* Get twitter posts */
	
	$("#twitter").click(function() {
		if ($("#twitterpanel").is(":visible")) {
			$("#twitter").removeClass("selected");
			$("#twitterpanel").hide();
		} else {
			$(".panel").hide();
			$(".button").removeClass("selected");
			$("#twitter").addClass("selected");
			$("#twitterpanel").show().css({ bottom : $("#twitterpanel").height() + 36 }).css({ left : $("#twitter").position().left - 1 });
			$.ajax({
				type: "GET",
				url: templatedir + "ajax.php?gettwitter=1",
				dataType: "html",
				success: function(html, status) {
					$("#twitterpanel").find("#twitterlist").remove();
					$("#twitterpanel").html("<ul id='twitterlist'>" + html + "</ul><div class='clearer'></div>").css({ bottom : $("#twitterpanel").height() + 36 });
				}
			});
		}
		return false;
	});
	
	/* Load search results */

	$(".searchbox").livequery('keyup', function() {
		clearTimeout(delayed); 
		var term = $(this).val();
		var length = $(this).val().length;
		var link = $(this).parent().attr('action');
		if (length > 0) {
			delayed = setTimeout(function() {
				$("#s").addClass("blackloader");
				$.ajax({
					type: "GET",
					url: link + "?s=" + term + "&ajax=1",
					dataType: "html",
					success: function(html, status) {
						$("#s").removeClass("blackloader");
						$("#content").html(html).show();						
					}
				});
			}, 500);
		}
		if (length == 0) {
			delayed = setTimeout(function() {
				$.ajax({
					type: "GET",
					url: link + "?ajax=1",
					dataType: "html",
					success: function(html, status) {
						$("#content").html(html).hide().fadeIn(200);
					}
				});
			}, 1000);
		}
		return false;
	});
	
	/* Close suggest box */
	
	$(".close").livequery("click", function() {
		$(this).parent().fadeOut();
		return false;
	});
});