$(function() {
	var el = $("#subscribe-form");
	
	el.ajaxForm({
		url: el.attr("action") + ".json", type: 'POST',
		dataType: "json",
		
		beforeSubmit: function(data, formEl, opts) {
			el.removeClass("success error");
			el.addClass("in-progress");
		},
		
		success: function(response) {
			showFlash("success", response.success);
			hideKeyboard();
			
			if (window.clicky) clicky.log(
				el.attr("action"), "Subscribe to Newsletter", "outbound");
		},
		error: function(xhr) {
			var error = "Something went wrong. Please try again later.";
			try { error = JSON.parse(xhr.responseText).error } catch(ex) {}
			showFlash("error", error);
		},
		complete: function() { el.removeClass("in-progress"); }
	});      

	function showFlash(type, msg) {
		el.addClass(type);
		el.find(".flash").html(msg);
	}
});

$(function() {
	$(document).delegate("a[href^=#]", "click", function(ev) {
		ev.preventDefault();
		
		var section = $($(this).attr("href")).closest("section");
		function focus() { section.find("input[type=email]").focus(); }
		
		if ('createTouch' in document)
			focus();
		else {
			var scroll = section.offset().top;
			var anim = $("html").animate({scrollTop: scroll}, 400);
			anim.promise().done(focus);
		}
	});
});

function hideKeyboard() {
  if (document.activeElement)
    $(document.activeElement).blur();
  else
    $("input:focus, textarea:focus, select:focus").blur();
}

