// infinite carousel plugin
$.fn.infiniteCarousel = function () {

	function repeat(str, num) {
		return new Array(num + 1).join(str);
	}

	return this.each(function () {
		var $wrapper = $('> div', this).css('overflow', 'hidden'),
			$slider = $wrapper.find('> ul'),
			$items = $slider.find('> li'),
			$single = $items.filter(':first'),

			singleWidth = $single.outerWidth(),
			visible = Math.ceil($wrapper.innerWidth() / singleWidth),
			// note: doesn't include padding or border
			currentPage = 1,
			pages = Math.ceil($items.length / visible);

		// 1. Pad so that 'visible' number will always be seen, otherwise create empty items
		if (($items.length % visible) != 0) {
			$slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
			$items = $slider.find('> li');
		}

		// 2. Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
		$items.filter(':first').before($items.slice(-visible).clone().addClass('cloned'));
		$items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
		$items = $slider.find('> li'); // reselect
		// 3. Set the left position to the first 'real' item
		$wrapper.scrollLeft(singleWidth * visible);

		// 4. paging function


		function gotoPage(page) {
			var dir = page < currentPage ? -1 : 1,
				n = Math.abs(currentPage - page),
				left = singleWidth * dir * visible * n;

			$wrapper.filter(':not(:animated)').animate({
				scrollLeft: '+=' + left
			}, 500, function () {
				if (page == 0) {
					$wrapper.scrollLeft(singleWidth * visible * pages);
					page = pages;
				} else if (page > pages) {
					$wrapper.scrollLeft(singleWidth * visible);
					// reset back to start position
					page = 1;
				}

				currentPage = page;
			});

			return false;
		}

		$wrapper.after('<a class="arrow back">&lt;</a><a class="arrow forward">&gt;</a>');

		// 5. Bind to the forward and back buttons
		$('a.back', this).click(function () {
			return gotoPage(currentPage - 1);
		});

		$('a.forward', this).click(function () {
			return gotoPage(currentPage + 1);
		});

		// create a public interface to move to a specific page
		$(this).bind('goto', function (event, page) {
			gotoPage(page);
		});
	});
};

// fade handler
$.fn.fadeInHandler = function(speed, callback) {
	if ($.browser.msie && $.browser.version < 9) {
		$(this).show();
	} else {
		$(this).fadeIn();
	}
};

$(document).ready(function () {
	// animated scrolling


	function enable_smooth_scroll() {
		function filterPath(string) {
			return string
					.replace(/^\//,'')
					.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
					.replace(/\/$/,'');
		}
	
		var locationPath = filterPath(location.pathname);
		
		var scrollElement = 'html, body';
		$('html, body').each(function () {
			var initScrollTop = $(this).attr('scrollTop');
			$(this).attr('scrollTop', initScrollTop + 1);
			if ($(this).attr('scrollTop') == initScrollTop + 1) {
				scrollElement = this.nodeName.toLowerCase();
				$(this).attr('scrollTop', initScrollTop);
				return false;
			}    
		});
		
		$('a[href*=#]').each(function() {
			var thisPath = filterPath(this.pathname) || locationPath;
			if  (   locationPath == thisPath
					&& (location.hostname == this.hostname || !this.hostname)
					&& this.hash.replace(/#/, '')
				) {
					if ($(this.hash).length) {
						$(this).click(function(event) {
							var targetOffset = $(this.hash).offset().top;
							var target = this.hash;
							event.preventDefault();
							$(scrollElement).animate(
								{scrollTop: targetOffset},
								500,
								function() {
									location.hash = target;
							});
						});
					}
			}
		});
	}
	
	enable_smooth_scroll();

	// init infinite carousel	
	$('.infiniteCarousel').infiniteCarousel();

	// form
	var nameVal = "e.g. Daisy";
	var emailVal = "e.g. moo@iamacow.com";
	var msgVal = "enter your message here...";
	var asVal = "?";

	if ($("form .name").val() == '') {
		$("form .name").val(nameVal);
	}

	$("form .name").focus(function () {
		if ($(this).val() == nameVal) {
			$(this).val("");
		}
	});

	$("form .name").blur(function () {
		if ($(this).val() == '') {
			$(this).val(nameVal);
		}
	});

	if ($("form .email").val() == '') {
		$("form .email").val(emailVal);
	}

	$("form .email").focus(function () {
		if ($(this).val() == emailVal) {
			$(this).val("");
		}
	});

	$("form .email").blur(function () {
		if ($(this).val() == '') {
			$(this).val(emailVal);
		}
	});

	if ($("form .message").val() == '') {
		$("form .message").val(msgVal);
	}

	$("form .message").focus(function () {
		if ($(this).val() == msgVal) {
			$(this).val("");
		}
	});

	$("form .message").blur(function () {
		if ($(this).val() == '') {
			$(this).val(msgVal);
		}
	});
	
	if ($("form .antispam").val() == '') {
		$("form .antispam").val(asVal);
	}

	$("form .antispam").focus(function () {
		if ($(this).val() == asVal) {
			$(this).val("");
		}
	});

	$("form .antispam").blur(function () {
		if ($(this).val() == '') {
			$(this).val(asVal);
		}
	});
	
	$("form a").click(function() {
		$("form").submit();
		return false;
	});

	function isValidEmailAddress(emailAddress) {
		var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
		return pattern.test(emailAddress);
	}

	$("form").submit(function () {
		$(".name").val($.trim($("<div>").html($(".name").val()).text()));
		$(".email").val($.trim($("<div>").html($(".email").val()).text()));
		$(".message").val($.trim($("<div>").html($(".message").val()).text()));
		$(".antispam").val($.trim($("<div>").html($(".antispam").val()).text()));

		if ($(".name").val() == '' || $(".name").val() == nameVal || $(".email").val() == '' || $(".email").val() == emailVal || $(".message").val() == '' || $(".message").val() == msgVal || $(".antispam").val() == '' || $(".antispam").val() == asVal) {
			$("p.outcome").hide().removeClass("success").addClass("error").text("Some fields empty?").fadeInHandler();
			return false;
		} else if (!isValidEmailAddress($(".email").val())) {
			$("p.outcome").hide().removeClass("success").addClass("error").text("Not a real email?").fadeInHandler();
			return false;
		} else if ($(".antispam").val() != 2) {
			$("p.outcome").hide().removeClass("success").addClass("error").text("Are you a robot?").fadeInHandler();
			return false;
		} else {
			$("p.outcome").hide().removeClass("error").removeClass("success").text("Sending...").fadeInHandler();
			$.post('index.php?ajax=me', {
				name: $(".name").val(),
				email: $(".email").val(),
				message: $(".message").val(),
				antispam: $(".antispam").val()
			}, function (data) {
				if (data == "success") {
					$("p.outcome").hide().removeClass("error").addClass("success").text("Thanks " + $(".name").val() + "!").fadeInHandler();
					$("form .name").val(nameVal);
					$("form .email").val(emailVal);
					$("form .message").val(msgVal);
					$("form .antispam").val(asVal);
				} else {
					$("p.outcome").hide().removeClass("success").addClass("error").text("That didn't work, please try again :(").fadeInHandler();
				}
			});
			return false;
		}
	});
});
