jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}

jQuery.fn.animateToCenter = function(rev) {
	// rev = true to reverse direction
    this.css("position","absolute");
	// initial position off screen
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
	if(rev == true) {
	    this.css("left", $(window).width());
	} else {
	    this.css("left", "-200px");
	}
	this.css("opacity","0");
	this.css("display","block");
	
	var x = ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px";
    this.animate({
		left: x,
		opacity: 1
	});
    return this;
}

function startTutorial() {
	var count = 0;
	$('#tutorial').load('/html/tutorial.htm', function(){		
		var total = $('#tutorial .tutorial-page').length;
		// bring in first card
		$('#tutorial .tutorial-page-1').animateToCenter(true).find('img.tut-arrow,div.redbox').fadeIn();
		// set up other cards
		$('#tutorial .tutorial-page').each(function(){
			count++;
			var cur = $(this);
			var extras = $(this).find('img.tut-arrow,div.redbox'); // arrows and red highlights
			// Counter
			$(cur).find('.tutorial-page-inner').append('<p class="small bold">Tip '+count+' of '+total+'</p>');
			// Add includes
			$(this).find('.tutorial-page-inner').append( $('#tutorial-page-include').html() );
			$(this).find('a.close').attr('href', '#tutorial-page-'+count);
			$(this).find('a.close').click(function(){
				$('#tutorial').fadeOut();
				return false;
			});
			$(this).find('a.prev').attr('href', '#tutorial-page-'+(count-1));
			$(this).find('a.prev').click(function(){
				var s = $(this).attr('href').replace('#','.');
				$(extras).fadeOut();
				$(cur).animate({
					left: $(window).width(),
					opacity: 0
				});
				$(s).animateToCenter(false).find('img.tut-arrow,div.redbox').fadeIn();
			});
			$(this).find('a.next').attr('href', '#tutorial-page-'+(count-0+1));
			$(this).find('a.next').click(function(){
				var s = $(this).attr('href').replace('#','.');
				$(extras).fadeOut();
				$(cur).animate({
					left: '-100px',
					opacity: 0
				});
				$(s).animateToCenter(true).find('img.tut-arrow,div.redbox').fadeIn();
			});
			// hide "prev" arrow on first panel, and "next" arrow on last panel
			if( count == 1 )     { $(this).find('a.prev').css('visibility','hidden'); }
			if( count == total ) { $(this).find('a.next').css('visibility','hidden'); }
		});
	});
}

$(document).ready(function(){
	
	$('body').append('<div id="tutorial"></div>');
	$('#tutorial').hide();
	
	$('#hints-tab').click(function(){
		$('#tutorial').show();
		startTutorial();
	});
});
