$(function() {
	$("div[data-load]").each(function(index) {
		var $this = $(this)
			, url = $(this).attr("data-load")

		$this.addClass("loading");
		$this.load(url, [], function() {
			$this.removeClass("loading");
			$('body').scrollSpy('refresh');
		});
	});

	$("a[href=#overview]").click(function() {
		$("html, body").animate({ scrollTop: 0 }, "slow");
		return false;
	});

	$("a[rel=favorite]").live("click", function() {
		var navFavorite = $("#nav-favorite").offset()
			, $this = $(this)
			, url = $this.attr("href")
			, parent = $this.attr("data-favorite")
			, $parent = $(parent)
			, offset = $parent.offset()
			, width = $parent.width()
			, height = $parent.height()

		if (!offset || !width || !height) {
			return false;
		};

		$parent.clone()
		.appendTo("body")
		.css({
			position: "absolute",
			top: offset.top,
			left: offset.left,
			width: width,
			height: height,
			opacity: 1
		})
		.animate({
			top: navFavorite.top,
			left: navFavorite.left,
			width: 0,
			height: 0,
			opacity: 0
		}, {
			duration: "slow",
			easing: "swing",
			complete: function() {
				$("#nav-favorite")
				.animate({
					opacity: 0
				})
				.animate({
					opacity: 1
				});
			}
		});
		$.post(url, [], function() {
			$this.animate({
				opacity: 0
			}, {
				duration: "slow",
				complete: function() {
					$this.removeClass("info")
					.addClass("success")
					.text("追加しました")
					.removeAttr("rel")
					.animate({
						opacity: 1
					}, {
						duration: "slow",
					})
				}
			});
		});
		return false;
	});

	$("div[data-waypoint]").each(function(index) {
		var $this = $(this)
			, opts = {offset: "100%"}
			, url = $this.attr("data-waypoint")

		$this.waypoint(function(event, direction) {
			if (direction === "down") {
				$this.addClass("loading");
				$this.load(url, [], function() {
					$this.removeClass("loading");
					$('body').scrollSpy('refresh');
				});
				$this.waypoint("destroy");
			}
			var hash = window.location.hash;
			$(hash).scrollTop(0);
		});
	});

});

