/*****************************/
/* All content, code and images written and created by Graham Swan (thinkswan@gmail.com), 2010.
/*****************************/

$(document).ready(function() {
	// Variables
	curProject = null;
	
	// Hide projects (we do this with jQuery instead of CSS so that people with JavaScript disabled can still see the full projects)
	$("div.project").hide();
	
	// Image rollovers
	$("ul.buttons img").hover(function() {
		image = $(this).attr("src");
		var imageHover = image.substr(0, image.lastIndexOf(".")) + "2.png"; // Change image.png to image2.png
		
		$(this).attr("src", imageHover);
	}, function() {
		$(this).attr("src", image);
	});
	
	// Fades
	$("img.fade").hover(function() {
		$(this).fadeTo('fast', 1);
	}, function() {
		$(this).fadeTo('fast', .8);
	});
	
	// Portfolio hazing (adapted from vilcsak.com)
	$('img.haze').hover(function() {
		$(this).animate({opacity: '0.2'}, {queue: false, duration: 300});
	}, function() {
		$(this).animate({opacity: '1.0'}, {queue: false, duration: 300});
	});
	
	// Portfolio fading
	$("div#portfolio a img").hover(function() {
		$("div#portfolio a img").not(this).animate({opacity: '0.6'}, {queue: false, duration: 300});
	}, function() {
		$("div#portfolio a img").animate({opacity: '1.0'}, {queue: false, duration: 300});
	});
	
	// Portfolio display
	$("div#portfolio a, div.projectCards a").click(function() {
		// Retrieve target ID
		var target = $(this).attr("href");
		
		// Check to see if user is trying to open an already-visible project
		if (curProject == target)
			return false;
		
		// Check to see if any projects are open
		var openProjects = $(".project:visible");
		
		if (openProjects.length > 0) {
			$(".project").hide();
			$(target).slideDown("slow"); // Display the project
		} else
			$(target).slideDown("slow"); // Display the project
		
		curProject = target;
	});
	
	// Back button
	$("span.back a").click(function() {
		$(".project").fadeOut("slow"); // Hide all projects
		
		curProject = null;
	});
	
	// Icon tooltips
	$("img.fade").tipsy({
		fade:		true,
		gravity:	's'
	});
	
	// Modal window for email form
	$("a.modalWindow").colorbox({
		inline:		true,
		href:		function() { return $(this).attr("href"); },
		onComplete:	function() { $("form input[name=name]").focus(); }
	});
	
	// Email validation regex
	function validateEmail(email) {
		var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
		
		return email.match(re);
	}
	
	// Form validation for email form
	$("form").submit(function() {
		// Bind all elements and values to variables
		var focus = false,
			valid = true,
			
			name = $("input[name=name]"),
			email = $("input[name=email]"),
			message = $("textarea[name=message]"),
			
			nameError = $("span.errorName"),
			emailError = $("span.errorEmail"),
			messageError = $("span.errorMessage"),
			
			nameVal = $.trim(name.val()),
			emailVal = $.trim(email.val()),
			messageVal = $.trim(message.val());
		
		// Check for a name
		if (!nameVal) {
			nameError.fadeIn();
			name.val("");
			name.focus();
			focus = true;
			valid = false;
		} else
			if (nameError.is(":visible"))
				nameError.fadeOut();
		
		// Check for a email
		if ((!emailVal) || (!validateEmail(emailVal))) {
			emailError.fadeIn();
			
			if (!emailVal)
				email.val("");
				
			valid = false;
			
			if (!focus) {
				email.focus();
				focus = true;
			}
		} else
			if (emailError.is(":visible"))
				emailError.fadeOut();
		
		// Check for a message
		if (!messageVal) {
			messageError.fadeIn();
			message.val("");
			valid = false;
			
			if (!focus) {
				message.focus();
				focus = true;
			}
		} else
			if (messageError.is(":visible"))
				messageError.fadeOut();
		
		// Submit the form if it's valid
		if (valid) {
			var form = $("form"),
				loading = $("div#emailForm img.loading"),
				thanks = $("div#emailForm p.thanks"),
				failed = $("div#emailForm p.failed");
			
			// Hide the form and show the throbber
			form.fadeOut("fast", function() {
				loading.fadeIn("fast", function() {
					$(this).css("display", "block");
					$.fn.colorbox.resize();
				});
			});
			
			// Post the form
			$.post("/_scripts/common.php", $("form").serialize(), function(data) {
				var success = (data === "true" ? true : false);
				
				// Pause for 1s before displaying the resultant message (so fadeIn() and fadeOut() don't skip)
				setTimeout(function() {
					if (success) {
						loading.fadeOut("fast", function() {
							thanks.fadeIn("fast", function() {
								$.fn.colorbox.resize();
								
								// Close the modal window after 5s
								setTimeout(function() {
									$.fn.colorbox.close();
									
									thanks.hide();
									form.show();
									
									name.val("");
									email.val("");
									message.val("");
								}, 5000);
							});
						});
					} else {
						loading.fadeOut("fast", function() {
							failed.fadeIn("fast", function() {
								$.fn.colorbox.resize();
								
								// Redisplay the form after 5s
								setTimeout(function() {
									failed.fadeOut("fast", function() {
										form.fadeIn("fast", function() {
											$.fn.colorbox.resize();
										});
									});
								}, 5000);
							});
						});
					}
				}, 2000);
			});
			
			return false;
		} else
			return false;
	});

	/*$("form").validate({
		rules: {
			name: "required",
			email: {
				required: true,
				email: true
			},
			message: "required"
		},
		messages: {
			name: "Please enter your name.",
			email: {
				required: "Please enter a valid email address.",
				email: "Please enter a valid email address."
			},
			message: "Please enter a message."
		},
		submitHandler: function(form) {
			form.submit();
		},
		onfocusout: false,
		onkeyup: false,
		errorElement: "span",
		errorPlacement: function(error, element) {
			error.appendTo(element.previous("span"));
		}
	});*/

	// Smooth scrolling for internal links
	$("a[href*=#]:not(.modalWindow)").click(function() {
		if ((location.pathname.replace(/^\//, "") == this.pathname.replace(/^\//, "")) && (location.hostname == this.hostname)) { // Ensure it's not a link to an anchor on another site
			var target = $(this.hash);
			target = target.length && target || $("[name=" + this.hash.slice(1) +"]"); // Find target on page
			
            if (target.length) {
				var targetOffset = target.offset().top;
				
				$("html, body").animate({scrollTop: targetOffset}, 1000);
				
				return false;
			}
		}
	});
});

