function bounce(el) {
	Element.addClassName(el, "bounce");
	Element.removeClassName.delay(0.2, el, "bounce");
}


function init_screenshot_pane(pane_id, up_id, down_id, prev_id) {
	var pane = $(pane_id);
	var preview_container = $(prev_id);
	var up = $(up_id);
	var down = $(down_id);
	var pane_container = pane.parentNode;

	pane.layout = Element.getLayout(pane);
	pane.height = pane.layout.get("height");

	pane_container.layout = Element.getLayout(pane_container);
	pane_container.height = pane_container.layout.get("height");

	pane.min_top = -(pane.height - pane_container.height);

	pane.target_top = pane.min_top;

	// console.debug(pane.height, pane_container.height, pane.min_top);

	pane.scroll_down = function() {
		if (this.show_el.next()) {
			this.show_el = this.show_el.next();
			if (!move_pane(this)) {
				bounce(down);
				this.show_el = this.show_el.previous();
			}
		} else {
			bounce(down);
		}
	}

	pane.scroll_up = function() {
		if (this.show_el.previous()) {
			this.show_el = this.show_el.previous();
			move_pane(this);
		} else {
			bounce(up);
		}
	}

	Event.observe(down, "click", function() {
		pane.scroll_down();
	});

	Event.observe(up, "click", function() {
		pane.scroll_up();
	});

	pane.childElements().each(function(el) {
		el.load = function() {
			pane.show_el = this;
			// console.debug(this);
			move_pane(pane);
			var img = this.readAttribute("image");
			if (img) {
				preview_container.update(new Element("IMG", {src: img}));
			} else {
				var video = this.readAttribute("youtube");
				if (video) {
					var v = video.split(":");
					preview_container.update(
						new Element("IFRAME", {src:"http://www.youtube.com/v/"+v[2]+"?autoplay=1&rel=0&autohide=1&border=0&modestbranding=1",
											   width: v[0],
											   height: v[1],
											   allowfullscreen: 1,
											   frameborder: 0
											  })
					);

				} else {
					video = this.readAttribute("vimeo");
					if (video) {
						var v = video.split(":");
						preview_container.update(new Element("IFRAME", {
							frameborder: 0,
							width: v[0],
							height: v[1],
							src: "http://player.vimeo.com/video/"+v[2]}));
					}
				}
			}
		}
		Event.observe(el, "click", function() {
			el.load();
		});
	});

	pane.down(0).load();
}

function move_pane(pane) {
	var t_current = 0;
	var top_min = 5;

	if (pane.style.top) {
		t_current = parseInt(pane.style.top);
	}
	var t = t_current;

	pane.target_top = Math.max(-pane.show_el.offsetTop+top_min, pane.min_top);

	if (t_current == pane.target_top) {
		return false;
	} else if (t > pane.target_top) {
		t = t - 5;
		if (t < pane.target_top) {
			t = pane.target_top;
		}
	} else if (t < top_min) {
		t = t + 5;
		if (t > top_min) {
			t = top_min;
		}
	}

	if (t != t_current) {
		pane.style.top = t + 'px';
		move_pane.delay(0.02, pane);
	}
	return true;
}
