/** doodlism.js **/
var base_url;
var PX_PER_MS = 1; // in ms

function preloadImages() {
	var i = new Image();
	i.src = base_url+"images/body_bg.JPG";
}

function initSite() {				   
	if($(".prevpost").hasClass("hidden")) {
		$(".posttitle").css({'margin-left':$(".prevpost").width()+'px'});
	}
	$(".hidden").removeClass("hidden").hide();
	$("#comments-wrapper").hide();
	
	$("a.ui").click(handleLinkEvent);
	$(".nextpost,.prevpost").hover(showBubble,hideBubble);
	$(window).resize(handleResize);
	$(window).scroll(handleScroll);
	
	$("#bottom").css({position:"fixed", bottom:0});
	$("#about").hide();
	$("#controlBar a").hover(handleHoverIn,handleHoverOut);
	$("#aboutMe ul a").hover(changePortrait);
		
	$("#header").headerFade();
	
	loadPortfolio(2);
}

$.fn.headerFade = function() {
	var floating_header = $(this).find(".floating_header");
	var cycle_finished = true; // keep animations from stacking
	
	if(floating_header != null) {
		floating_header.hide();
		$(this).children("a").bind("mouseenter", function() {
			if(cycle_finished) {
				cycle_finished = false;
				floating_header.fadeIn("slow");
			}
		}).bind("mouseleave", function() {
			floating_header.fadeOut("slow", function() { cycle_finished = true});
		});
	}
}

function setBaseURL(url) {
	base_url = url+"/";
}

function showPopup(eventObj) {
	var target = $(eventObj.currentTarget);
	var topOffset = 0;
	
	if(target.is("#about_button a")) topOffset = target.position().top+10;
	else if(target.is("#portfolio_button a")) topOffset = target.position().top-10;
	
	$(eventObj.target).siblings(".popup").css({display:"block",opacity:0.0}).animate({
		marginTop:topOffset,
		pacity:1.0
		},200, "linear");
}

function hidePopup(eventObj) {
	$(eventObj.currentTarget).siblings(".popup").animate({
		marginTop:0,
		opacity:0.0
		},200,"linear",
		function() {
			$(this).hide();
		});
}

function showBubble(eventObj) {
	$(eventObj.currentTarget).children("span").css({display:"block",opacity:0.0}).animate({
		marginTop:"-10px",
		opacity:1.0
		},200,"linear");
}

function hideBubble(eventObj) {
	$(eventObj.currentTarget).children("span").animate({marginTop:0,opacity:0.0},200,"linear",
		function() {
			$(this).hide();
		});
}

/**
	Post navigation functions
**/

function prevPost(post_id) {
	gotoPost(post_id, true);
}

function nextPost(post_id) {
	gotoPost(post_id, false);
}

function gotoPost(post_id, backwards) {
	
	// waiting state
	$(".entry div").hide();
	$(".entry").addClass("waiting");
	//$(".waiting").show();
	
	var exitPos = $(".posttitle").width();
	if(!backwards) exitPos = -exitPos;
	$(".posttitle a").animate({
		left: exitPos,
		opacity: 0.0
		},500);
	
	$.ajax({
			type: "POST",
			data: {post_id:post_id, dir:"both"},
			url: base_url+"ajaxGetPost.php",
			dataType: "json",
			success: function(json, textStatus) {
				var html = json.post_content;
				var img_tag = html.substring(html.indexOf(']')+1,html.indexOf('>')+1);
				var post_notes = html.substring(html.indexOf('>')+1);
				if(img_tag.match("<img") == null) {
					post_notes = img_tag+post_notes;
					img_tag = "";
				}
				$(".entry div").html(img_tag);
				$(".entry .notes").html(post_notes);
				// add image callback here:
				if($(".entry div img").length > 0) {
					$(".entry div img").load(
					function() {
						transitionPost(json,backwards);
					});
				} else { transitionPost(json,backwards); }
			}
		   });
	
	// also get comments for post
	getComments(post_id);
}

function transitionPost(post, backwards) {
	
	$(".entry").removeClass("waiting");
	$(".entry div").fadeIn();
	
	var enterPos = -$(".posttitle").width();
	if(!backwards) enterPos = -enterPos;
	$(".posttitle a").text(post.post_title).attr("href",post.guid).stop().css({left: enterPos}).animate({
		left: 0,
		opacity: 1.0
		},500);
	
	// update nav buttons
	if(post.next != null) {
		if($(".nextpost").is(":hidden")) {
			$(".nextpost").fadeIn();
		}
		$(".nextpost").attr("href","/blog/?p="+post.next.ID);
		$(".nextpost span").text(post.next.post_date_formatted);
	}
	else $(".nextpost").fadeOut();
	
	if(post.prev != null) {
		if($(".prevpost").is(":hidden")) {
			$(".prevpost").fadeIn();
			$(".posttitle").css({'margin-left':'0px'});
		}
		$(".prevpost").attr("href","/blog/?p="+post.prev.ID);
		$(".prevpost span").text(post.prev.post_date_formatted);
	}
	else $(".prevpost").fadeOut(function() { 
		$(".posttitle").css({'margin-left':$(".prevpost").width()+'px'}); 
	});
}

/** 
	Pane Displays
**/

function scrollToPos(pos) {

	var current_pos = Math.max($("html").scrollTop(), $("body").scrollTop());
	var time = Math.abs((current_pos - pos) / PX_PER_MS);
	$("html, body").animate({'scrollTop': pos}, time, "swing", 
	function() {
		if($("#about").is(":visible")) {
			toggleAboutMe();
		}
	});
}

function gotoPortfolio() {
	var desired_pos = $("#portfolio").position().top;
	scrollToPos(desired_pos);
}

function gotoHome() {
	var desired_pos = $("#main").position().top;
	scrollToPos(desired_pos);
}

function gotoComments() {
	var desired_pos = $("#comments").offset().top - 10;
	scrollToPos(desired_pos);
}

function toggleAboutMe() {
	if($("#about").is(":hidden")) {
		$("#about").height(0).show().animate({height: 400}, 300);
	} else {
		$("#about").height(400).animate({height: 0}, 300, 
		function() { 
			$(this).hide();
			if(!isAtBottom) {
				hideBottomLink();
			}
		});
	}
}


/**
	Comments
**/

function getComments(post_id) {
	var was_showing = !$("#comments-wrapper").is(":hidden");
	if(was_showing) $("#comments-wrapper").hide();
	
	$("#comments a").text("Loading...");
	
	$.ajax({
		   type: "POST",
		   data: {post_id:post_id},
		   url: base_url+"ajaxGetComments.php",
		   success: function(html, textStatus) {
			  $(".comments-template").html(html);
			  $("#comments-wrapper").hide();
			  $("#comments a.ui").click(handleLinkEvent);
			  if(was_showing) $("#comments-wrapper").fadeIn();
		   }
		   });
	
}

function toggleComments() {
	
	if($("#comments-wrapper").is(":hidden")) {
		$("#comments-wrapper").slideDown();
		gotoComments();
	} else {
		$("#comments-wrapper").slideUp();
		gotoHome();
	}
}
	
/**
	Portfolio Loading
**/

function loadPortfolio(id) {

	$("#info").animate({
		opacity: 0.5
		}, 300);
	$("#info h2").text("Loading...").siblings().text("");
	animatePortfolioLink("port-nav-"+id);
	
	if($(".thumbnail a").length > 0) {
		var total = $(".thumbnail a").length;
		var counter = 0;
		$(".thumbnail a").animate({top:"0px"},500,function() {
			$(this).empty().html("");
			counter ++;
			if(counter == total) getPortfolioPage(id, 0);
		});
	} else getPortfolioPage(id, 0);
}

function getPortfolioPage(id, pageNum) {
	
	// clear all images out
	
	$.ajax({
		   type: "POST",
		   data: {p:id, page:pageNum},
		   dataType: "json",
		   url: base_url+"ajaxGetPortfolioPage.php",
		   success: function(json, textStatus) {
				addPortfolioImages(json);
				showPortfolioInfo(json);
		   }
		   });

}

function addPortfolioImages(json) {
	
	var images = json.images;
	
	var numImages = images.length;
	var counter = 0;
	
	// for each image, load as new Image
	$(".thumbnail").each(
		function(i) {
		  if(i < numImages) {
			  if($(this).is(":hidden")) $(this).fadeIn();
			  
			  $("<a></a>").attr({
			  	href: "/portfolio"+images[i].imgsrc,
			  	title: images[i].title,
			  	rel: "floatbox."+json.id
			  	}).prependTo($(this));
			  				  
			  $("<img />").attr({
				src: base_url+"phpThumb/phpThumb.php?src=/portfolio"+images[i].imgsrc+"&w=150&h=150",
				title: images[i].title
				}).load( function() {
				
					var x = ($(this).parent().width() - $(this).width())/2;
					var y = -($(this).height() + ($(this).parent().height()-$(this).height())/2);
			  		$(this).parent().css({"left":x}).animate({
			  			top:y
			  			},500);
			  			
			  		counter ++;
			  		if(counter == numImages) {
			  			fb.tagAnchors(document.getElementById("imageViewer"));
			  			scaleModalWindows();
			  		}
			  		
			 	}).prependTo($(this).find("a"));
			  
		  } else $(this).fadeOut();
		});	
	
	if(json.next != null) {
		// show next button, modify href
	} else {// keep button hidden
	}
	
	if(json.prev != null) {
		// show prev button, modify href
	} else {// keep button hidden
	}
	
}

function showPortfolioInfo(json) {

	var navLi = $("#port-nav-"+json.id).parent();
	var offset = navLi.position().top - navLi.parent().position().top;
	
	$("#info h2").text(json.title);
	$("#info .date").text(json.date_formatted);
	$("#info .details").text(json.description);
	$("#info").css({display:"block",opacity:0.5}).animate({
		marginTop: offset,
		opacity: 1.0},500);
}

function animatePortfolioLink(linkID) {
	
	var others = $("#portfolio li");
	var target = $("#"+linkID).parent();

	others.animate({
		right: "0px",
		marginTop: "5px",
		marginBottom: "0px"},250,
		function() {
			if($(this).children("a").is(":hidden")) {
				$(this).children("a,span").toggle();
			}
		});
	target.animate({
		right: "-15px",
		marginTop: "10px",
		marginBottom: "10px"},250,
		function() {
			$(this).children("a,span").toggle();
		});
}

/**
	Event handlers
**/

var lastResize = 0; // ms
const EVENT_LATENCY = 1000; // ms
function handleResize(resizeEvent) {
	
	if(lastResize <= 0 || (resizeEvent.timestamp - lastResize <= EVENT_LATENCY)) {
		return true;	
	}
	scaleModalWindows();
}

const MAX_WIDTH = .5; // 70%
const MAX_HEIGHT = .7; // 90%
function scaleModalWindows() {

	var windowWidth = window.innerWidth;
	var windowHeight = window.innerHeight;
	
	var img;
	var aspectRatio;
	var revStr = "";
	$(".thumbnail").each(
	function() {
		img = $(this).children("a>img");
		aspectRatio = img.width()/img.height();
		
		if(aspectRatio >= 1.0) {
			revStr = "width:"+(MAX_WIDTH*windowWidth)+" height:"+Math.round((MAX_WIDTH/aspectRatio)*windowWidth);
		}
		else {
			revStr = "width:"+Math.round((aspectRatio*MAX_HEIGHT)*windowHeight)+" height:"+(MAX_HEIGHT*windowHeight);
		}
	});
}

/**
	Control bar effects
**/
var isAnimating = false; // is portrait head animating in/out?
var isAtBottom = false; // if user is at the bottom of the page

function handleHoverIn() {
	if(!isAtBottom && $("#about").is(":hidden")) {
		showBottomLink();
	}
}

function handleHoverOut() {
	if(!isAtBottom && $("#about").is(":hidden")) {
		hideBottomLink();
	}
}

function handleScroll(scrollEvent) {
	if(!isAnimating) {
		if($(window).scrollTop() >= ($("#portfolio").position().top - $(window).height() + $("#portfolio").outerHeight())) {
			isAtBottom = true;
			if($("#controlBar #portrait_head").is(":hidden")) {
				isAnimating = true;
				showBottomLink();
			}
		}
		else {
			isAtBottom = false;
			if($("#controlBar #portrait_head").is(":visible") && $("#about").is(":hidden")) {
				isAnimating = true;
				hideBottomLink();
			}
		}
	}
}

function showBottomLink() {
	$("#controlBar a").css({height: "120px", top: "-90px"});
	$("#portrait_head").css({top:"-240px"}).fadeIn(function() { isAnimating = false; });
}

function hideBottomLink() {
		// change link size
	$("#controlBar a").css({height: "30px", top: "0px"});
		// hide div
	$("#portrait_head").css({top:"-150px"}).fadeOut(function() { isAnimating = false; });
}

/**
	Portrait effect
**/

function changePortrait(hoverEvent) {
	var target = $(hoverEvent.currentTarget);
	
	var offset = 0;
	switch(target.attr("title")) {
		case "illustration":
			offset = 0;
			break;
		case "print":
			offset = 1;
			break;
		case "web":
			offset = 2;
			break;
		case "interactive":
			offset = 3;
			break;
		default:
			break;
	}
	
	var mainPortraitOffset = "0px "+(-offset * $("#about #portrait").height())+"px";
	$("#about #portrait").css({backgroundPosition: mainPortraitOffset});
	
	var headPortraitOffset = "0px "+(-offset * $("#controlBar #portrait_head").height())+"px";
	$("#controlBar #portrait_head").css({backgroundPosition:headPortraitOffset});
}