$.fn.outerHtml = function(s) {
	return (s)
	? this.before(s).remove()
	: $("<p>").append(this.eq(0).clone()).html();
};

$(function(){
	if ($(".cycle_content").length) {
		$(".cycle_nav a").css({"cursor": "pointer"}).click(function(){
			$(".cycle_nav a").removeClass('active');
			$(this).addClass('active');
			var i = 1;
			var c = $(this).attr('class');
			$.each(c.split(" "), function(index, value){
					if (value.substr(0, 10) == "cycle_nav_") {
						i = parseInt(value.substr(10), 10);
					}
				});
			$(".cycle_content").cycle('pause').cycle(i-1);
		});
		$(".cycle_content").cycle({
			fx: 'fade',
			speed: 500,
			timeout: 4000,
			before: function(currElement, nextElement, options, forwardFlag){
				var c = $(nextElement).attr('class');
				var i = 1;
				$.each(c.split(" "), function(index, value){
					if (value.substr(0, 6) == "cycle_") {
						i = parseInt(value.substr(6), 10);
					}
				});
				$('.cycle_nav a').removeClass('active');
				$('.cycle_nav_'+i).addClass('active');
			}
		});
	}
	
	if ($("#gallery_thumbs .thumb_group").length > 1 && $("#gallery_scroll a").length == 2) {
		$("#gallery_scroll .next").fadeIn();
		$("#gallery_scroll a")
			.click(function(e){
				e.preventDefault();
				
				var visible = $("#gallery_thumbs .thumb_group:visible");
				var nextEls = null;
				var el = null;
				var dir = $(this).hasClass("prev") ? "prev" : "next";
				
				if (dir == "next") {
					nextEls = visible.nextAll(".thumb_group");
					el = nextEls.first();
				}
				else {
					nextEls = visible.prevAll(".thumb_group");
					el = nextEls.first(); //?!
				}
				
				if (nextEls.length >= 1) {
					if (nextEls.length == 1) {
						$(this).fadeOut();
					}
					$(this).siblings().fadeIn();
					
					visible.fadeOut(
						function(){
							(function(el) {
								el.fadeIn();
							})(el)
						}
					);
				}
				
			})
		;
	}//if more than 1 thumb group and buttons available
	
	$("a[rel^='prettyPhoto']").prettyPhoto({});
	
	$("#gallery_thumbs a.thumb").click(function(e) {
		e.preventDefault();
		var newImg = new Image();
		newImg.src = $(this).attr('href');
		newImg.onload = function() {
			(function(n) {
				$("#gallery_large img").fadeOut(function(){
					(function(n){
						var $n = $(n);
						$n.hide();
						$("#gallery_large img").replaceWith($(n));
						$n.fadeIn();
					})(n);
				});
			})(newImg);
		};
	});
	
	$("#gallery_large img").live("click", function(e) {
		e.preventDefault();
		var cmpHref = $(this).attr('src').replace('/l/', '/');
		$("a[rel^='prettyPhoto'][href='"+cmpHref+"']").click();
	});
});
