/**
 * @author David Mauro
 */

// Hyphenator
Hyphenator.config({ minwordlength : 4 });
Hyphenator.run();

// Nav globals
var active = false;
var tweenInTime = 250;
var tweenOutTime = 350;

// Portfolio globals
var isScrollingVert = false;
var portWinHeight = 329;
var portWinWidth = 526;
var portAutoScrollTimer = "";
var portScrollSpeed = 700;
var tooltipMouseThreshold = 40;
var tooltipFadeIn = 500;
var tooltipFadeOut = 300;
var slideshowTime = 5000;
var isPaused = false;
var isScrollingHori = false;

// Contact form globals
var opacitySpeed = 500;
var errorSpeed = 700;
var email_filter = new RegExp(/^[0-9a-zA-Z._%-]+@[0-9a-zA-Z._%-]+[\.]{1}[0-9a-zA-Z._%-]+[\.]?[0-9a-zA-Z._%-]+$/);
var formErrorColor = "#b21b4d";
var contactFormUrl = "contact.php";
var errorWaitTime = 2000;
var formDefaultColor = "";

$(document).ready(function() {
 	// Film grain effect
	/*
 	setInterval(function() {
 		$("#noise").css({backgroundPosition: Math.floor(Math.random()*105) + "px " + Math.floor(Math.random()*105) + "px"});
	}, 100);
	*/
	
	// Add hyphenation class to appropriate paragraphs
	$("section figcaption p, #blog > figure p").addClass("hyphenate");
	
	// Borders for figcaptions
	//$("section > figcaption, #port_figcap_bg").prepend('<div class="figcap_border top_border"></div>').append('<div class="figcap_border bottom_border"></div>');
	
	// Remove nav links, float right and reverse order
	$("nav li a[href]").removeAttr('href').parent().click(function() { navClick($(this)); });
	$("nav li").addClass("floatRight").reverseOrder();
	
	// Nav hover effect
	var navDefaultColor = $("nav li a").css("color");
	$("nav li a").mouseover(function() {
		$(this).css("color", "#1f5571").delay(200).stop().animate({color: navDefaultColor}, 800, "swing");
	});
	
	// Put first portfolio project in
	$("#port_window").prepend($("#port_holding > div.port_project:first-child > figure"));
	$("#port_figcap").prepend($("#port_holding > div.port_project:first-child > figcaption"));
	$("#port_holding > div.port_project:first-child").remove();
	checkForScrolling();
	
	// Start arrows listening
	$("#left_arrow").click(function() {
		if (!isScrollingHori) {
			prevPortProject();
		}
	})
	$("#right_arrow").click(function() {
		if (!isScrollingHori) {
			nextPortProject();
		}
	})
	
	// Portfolio scrolling stuff
	
	// Set text for first 
	$("#port_details > p").html($("#portfolio figure > img:first-child").attr("alt"));
	
	$("#port_window").hover(function() {
		//clearInterval(portAutoScrollIntval);
		$("#port_details, #port_scroll_controls").stop().animate({opacity: 1}, tooltipFadeIn, "swing");
	}, function() {
		//startPortAutoScroll();
		$("#port_details, #port_scroll_controls").stop().animate({opacity: 0}, tooltipFadeIn, "swing");
	});
	
	$("#port_scroll_up").click(function() {
		if (!isScrollingVert) {
			slideToPrevSlideshow()
		};
	});
	$("#port_scroll_down").click(function() {
		if (!isScrollingVert) {
			slideToNextSlideshow()
		};
	});
	$("#port_scroll_pause").click(function() {
		if (isPaused) {
			isPaused = false;
			$("#port_scroll_pause").css("backgroundPosition", "-19px 0");
			checkForScrolling();
		}
		else {
			isPaused = true;
			$("#port_scroll_pause").css("backgroundPosition", "-19px -19px");
			clearTimeout(portAutoScrollTimer);
		}
	});
	
	// Tumblr stuff
	displayPosts();
	
	// Contact Form Stuff
	formDefaultColor = $("#contact > figure > form > input:first-child").css("backgroundColor");
	
	$("#contact > figure > form > input[type='submit']").click(function() {
		validateForm();
		return false;
	});
	$('#contact > figure input[type="text"]').addClass("defaultField");
	$('input[type="text"]').focus(function() {
		$(this).removeClass("defaultField").addClass("userField");
		if (this.value == this.defaultValue){
			this.value = '';
		}
		if(this.value != this.defaultValue){
			this.select();
		}
	});
	$('input[type="text"]').blur(function() {
		if (this.value == '' || this.value == this.defaultValue) {
			this.value = this.defaultValue;
			$(this).removeClass("userField").addClass("defaultField");
		}
	});
});

function navClick(target)
{
	var nDom = $("nav li").size() - target.index();
	var nNav = target.index() + 1;
	if (!active && nDom != 1) {
		swapDOM(nDom);
		swapNav(nNav);
	}
	active = (nDom == 1) ? false : true;
}

function swapNav(n)
{
	var target = $("nav > ul > li:nth-child(" + n + ")");
	var targetWidth = target.outerWidth(false);
	var targetMargin = target.css("marginLeft");
	targetMargin = targetMargin.substr(0, targetMargin.length - 2)*1;
	target.animate({width: 0, opacity: 0, marginLeft: 0}, tweenInTime, null, function() {
		$("nav ul").append(target);
		target.animate({width: targetWidth, opacity: 1, marginLeft: targetMargin}, tweenOutTime, null, function() {
			active = false;
		});
	});
}

function swapDOM(n)
{
	var targetItem = $("#content > section:nth-child(" + n + ")");
	var targetHeight = targetItem.outerHeight(true);
	var targetOffset = targetItem.position();
	targetItem.after('<div style="height: ' + targetHeight + 'px;"></div>');
	var replacement = $("#content > div:nth-child(" + (n + 1) + ")");
	targetItem.addClass("absolute");
	replacement.before(targetItem);
	$("#content > section:nth-child(1)").before('<div style="height: 0px;"></div>');
	var placeholder = $("#content > div:nth-child(1)");
	
	targetItem.animate({left: '-=500', opacity: 0}, tweenInTime, null, function() {
		$("#content > div:nth-child(1)").before(targetItem);
		targetItem.css({"left" : targetOffset.left - 500});
		targetItem.animate({left: '+=500', opacity: 1}, tweenOutTime, null, function() {
			targetItem.removeClass("absolute");
			placeholder.remove();
		})
	});
	
	replacement.delay(70).animate({height: 0}, tweenInTime, null, function() {
		replacement.remove();
	});
	placeholder.delay(70).animate({height: targetHeight}, tweenInTime, null);
}

// Portfolio functions

function checkForScrolling()
{
	if ($("#port_window figure:first-child > img").length <= 1) {
		$("#port_scroll_controls").addClass("hidden");
	}
	else if (!isPaused && !isScrollingVert) {
		portAutoScrollTimer = setTimeout("slideToNextSlideshow()", slideshowTime);
		$("#port_scroll_controls").removeClass("hidden");
	}
	else {
		$("#port_scroll_controls").removeClass("hidden");
	}
}

function slideToNextSlideshow()
{
	clearTimeout(portAutoScrollTimer);
	if (isScrollingHori) {
		portAutoScrollTimer = setTimeout("slideToNextSlideshow()", slideshowTime)
	}
	else {
		isScrollingVert = true;
		var targetImg = $("#port_window figure:first-child > img:first-child");
		var targetPlace = $("#port_window figure:first-child > img:last-child");
		targetImg.stop().animate({marginTop: '-329px'}, portScrollSpeed, "swing", function() {
			targetImg.css("marginTop", 0);
			targetPlace.after(targetImg);
			isScrollingVert = false;
			$("#port_details > p").html($("#portfolio figure > img:first-child").attr("alt"));
			checkForScrolling();
		});
	}
}

function slideToPrevSlideshow()
{
	isScrollingVert = true;
	clearTimeout(portAutoScrollTimer);
	var targetImg = $("#port_window figure:first-child > img:last-child");
	targetImg.css("marginTop", -329);
	$("#port_window figure:first-child").prepend(targetImg);
	targetImg.stop().animate({marginTop: '0'}, portScrollSpeed, "swing", function() {
		isScrollingVert = false;
		$("#port_details > p").html($("#portfolio figure > img:first-child").attr("alt"));
		checkForScrolling();
	});
}

function nextPortProject()
{
	isScrollingHori = true;
	clearTimeout(portAutoScrollTimer);
	// Make a div in holding for the stuff that's going out
	$("#port_holding").append('<div class="port_project"></div>');
	
	var target = $("#port_holding > div.port_project:first-child > figure");
	$("#port_window").prepend(target);
	target.css("left", 526);
	$("#port_window figure").stop().animate({"left" : '-=526'}, 400, null, function() {
		$("#port_holding > div.port_project:last-child").append($("#port_window figure:nth-child(2)"));
		$("#port_details > p").html($("#portfolio figure > img:first-child").attr("alt"));
	});
	
	$("#port_figcap > figcaption").stop().animate({"opacity" : 0}, 200, null, function() {
		$("#port_holding > div:last-child").prepend($("#port_figcap > figcaption:first-child"));
		$("#port_holding > div.port_project:first-child > figcaption").css("opacity", 0);
		$("#port_figcap").prepend($("#port_holding > div.port_project:first-child > figcaption"));
		$("#port_figcap > figcaption:first-child").stop().animate({"opacity" : 1}, 200, null, function() {
			$("#port_holding > div.port_project:first-child").remove();
			isScrollingHori = false;
			checkForScrolling();
		});
	});
}

function prevPortProject()
{
	isScrollingHori = true;
	clearTimeout(portAutoScrollTimer);
	// Make a div in holding for the stuff that's going out
	$("#port_holding").prepend('<div class="port_project"></div>');
	
	var target = $("#port_holding > div.port_project:last-child > figure");
	$("#port_window").prepend(target);
	target.css("left", -526);
	$("#port_window figure").stop().animate({"left" : '+=526'}, 400, null, function() {
		$("#port_holding > div.port_project:first-child").append($("#port_window figure:nth-child(2)"));
		$("#port_details > p").html($("#portfolio figure > img:first-child").attr("alt"));
	});
	
	$("#port_figcap > figcaption").stop().animate({"opacity" : 0}, 200, null, function() {
		$("#port_holding > div:first-child").prepend($("#port_figcap > figcaption:first-child"));
		$("#port_holding > div.port_project:last-child > figcaption").css("opacity", 0);
		$("#port_figcap").prepend($("#port_holding > div.port_project:last-child > figcaption"));
		$("#port_figcap > figcaption:first-child").stop().animate({"opacity" : 1}, 200, null, function() {
			$("#port_holding > div.port_project:last-child").remove();
			isScrollingHori = false;
			checkForScrolling();
		});
	});
}

// Contact functions

function validateForm()
{
	var contactForm =  $("#contact > figure > form");
	var nameInput = $("#contact > figure > form > input:first-child");
	var emailInput = $("#contact > figure > form > input:nth-child(2)");
	var subjectInput = $("#contact > figure > form > input:nth-child(3)");
	var messageInput =  $("#contact > figure > form > textarea");
	var submitInput =  $("#contact > figure > form > input:nth-child(5)");
	
	// Set min height of container so that it doesn't shrink when displaying the response, get background color for inputs
	$("#contact > figure").css("minHeight", $("#contact > figure").height());
	
	var emailIsValid = (email_filter.test(emailInput.attr("value"))) ? true : false;
	var nameIsValid = true;
	var subjectIsValid = true;
	var messageIsValid = true;
	if (!emailIsValid) {
		emailInput.stop().css({backgroundColor: formErrorColor}).animate({backgroundColor: formDefaultColor}, errorSpeed, "swing");
	}
	if (nameInput.attr("value") == "" || nameInput.attr("value") == nameInput.attr("defaultValue")) {
		nameInput.stop().css({backgroundColor: formErrorColor}).animate({backgroundColor: formDefaultColor}, errorSpeed, "swing");
		nameIsValid = false;
	}
	if (subjectInput.attr("value") == "" || subjectInput.attr("value") == subjectInput.attr("defaultValue")) {
		subjectInput.stop().css({backgroundColor: formErrorColor}).animate({backgroundColor: formDefaultColor}, errorSpeed, "swing");
		subjectIsValid = false;
	}
	if (messageInput.attr("value") == "") {
		messageInput.stop().css({backgroundColor: formErrorColor}).animate({backgroundColor: formDefaultColor}, errorSpeed, "swing");
		messageIsValid = false;
	}
	if (emailIsValid && nameIsValid && subjectIsValid && messageIsValid) {
		submitInput.animate({opacity: 0}, 50, "swing", function() {
			submitInput.addClass("hidden");
		});
		var name = nameInput.attr("value");
		var email = emailInput.attr("value");
		var subject = subjectInput.attr("value");
		var message = messageInput.attr("value");
		var dataString = "email=" + email + "&name=" + name + "&subject=" + subject + "&message=" + message;
		$.ajax({
			type: "post",
			url: contactFormUrl,
			data: dataString,
			dataType: "json",
			success: function(data) {
				if (data.error == false) {
					contactForm.animate({opacity: 0}, opacitySpeed, "swing", function() {
						contactForm.addClass("hidden");
						contactForm.before('<div class="contact_form_response"><p>' + data.message + '</p></div>');
						$("div.contact_form_response").stop().animate({opacity: 1}, opacitySpeed, "swing", function() {
							$("#contact > figure").stop().animate({minHeight: 0}, 300, null);
						});
					});
				} else {
					displayErrorResponse(data.message);
				}
			},
			error: function(e, xhr, settings, exception) {
				displayErrorResponse(settings.message);
			}
		});
	}

	function displayErrorResponse(msg)
	{
		contactForm.animate({opacity: 0}, opacitySpeed, "swing", function() {
			contactForm.addClass("hidden");
			submitInput.removeClass("hidden").css("opacity", 1);
			contactForm.before('<div class="contact_form_response"><p>' + msg + '</p>');
			$("div.contact_form_response").stop().animate({opacity: 1}, opacitySpeed, "swing");
			$("div.contact_form_response").delay(errorWaitTime).stop().animate({opacity: 0}, opacitySpeed, "swing", function() {
				$("div.contact_form_response").remove();
				contactForm.removeClass("hidden").stop().animate({opacity: 1}, opacitySpeed, "swing");
			});
		});
	}
}

