$(document).ready(function(){
	$("a[title]").tipTip();

 	$('#projects a').click(function(e) {
		e.preventDefault();
		$(this).create_popup();
	});

	$('.close').live('click', function(e) {
		e.preventDefault();
		$('#popup').close_popup();
	});
		
	$('a[href^="#"]').click(function(e){
		e.preventDefault();
		$($(this).attr('href')).smooth_scroll();
	});
});

jQuery.fn.create_popup = function() {
	$('#popup').remove();
	var url = $(this).attr('href');


	var viewportWidth = $(window).width();
	var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();
	
	$("body").append('<div id="popup"><p id="loading">Loading</p><a href="#popup" class="close"><img src="/wordpress/wp-content/themes/jeffsmith-2010/images/close.png" alt="Close" /></a></div>');
	
	var left = (viewportWidth - $('#popup').width() - (parseFloat($('#popup').css('padding-left')) * 2)) * 0.5;
	if(left < 0)
		left = 10;

	$('#popup').css({
		'top': $(window).scrollTop() + 20 + 'px',
		'left': left + 'px',
		'margin-left': 0
	}).hide().fadeIn('normal', function(){
		$(this).attr('tabIndex', -1).focus();
	});

	$('#popup').css({
		'top': $(window).scrollTop() + 20 + 'px',
		'left': left + 'px',
		'margin-left': 0
	}).hide().fadeIn('normal', function(){
		$(this).attr('tabIndex', -1).focus();
	});

	var img = new Image();
	
	$(img)
		.load(function() {
			$(this).hide();
			$('#popup').prepend(this);
			$(this).addClass('screenshot');
			$(this).fadeIn('normal', function(){
				var width = $(this).width();
				left = (viewportWidth - width - (parseFloat($('#popup').css('padding-left')) * 2)) * 0.5;
				if(left < 0)
					left = 10;
				$('#popup').animate({
					'width': width + 'px',
					'left': left + 'px'
				});
				$('#loading').fadeOut();
			});
		})
		.error(function() {
			$('#popup').prepend("<p>There was an error loading this image.</p>");
		})
		.attr('src', url);
		
	$(document).keyup(function(event){
	    if (event.keyCode == 27) {
	    	$('#popup').close_popup();
	    }
	});
}

jQuery.fn.close_popup = function() {
	var img_src = $(this).find('.screenshot').attr('src');
	$(this).fadeOut('normal', function() { $(this).remove(); });
	$("a[href='"+img_src+"']").focus();
}

jQuery.fn.smooth_scroll = function() {
	var anchor = $(this);
	$('html, body').animate({
        scrollTop: $(anchor).offset().top
    }, 1000, function() { window.location.hash = anchor.attr('id'); });
}