var HANDLE_HEIGHT = 35;
var MIN_GALLERY_HEIGHT = 400;
var MAX_GALLERY_HEIGHT = 720;
var MENU_ITEM_WIDTH = 412;
var MENU_ITEM_HEIGHT = 40;

function gup( name ) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

$(document).ready(function() {
	/*
	var touch = gup( 'touch' );
	is_touch_device = (touch == 1);
	
	//is_touch_device = 'ontouchstart' in document.documentElement;
	
	if (is_touch_device) {
		$("body").removeClass("no-touch").addClass("touch");
		
		$("#display").remove();
	}
	*/
	
	is_touch_device = $("body").is(".touch");
	
	// hover
	$("#secciones_container li, ul.menu li").hover(
		function() {
			if (!$(this).is(".selected")) {
				var img = $(this).find("img");
				var src = img.attr("src");
				src = src.replace("normal", "click");
				img.attr("src", src);
			}
		},
		function() {
			if (!$(this).is(".selected")) {
				var img = $(this).find("img");
				var src = img.attr("src");
				src = src.replace("click", "normal");
				img.attr("src", src);
			}
		}
	);
	
	// recuperar el alto de la galería actual
	var gallery_height = getGalleryHeight();
	
	// el alto del scroll pane es el alto de la galería + el alto del handle
	$('#scroll-pane').css({height: is_touch_device ? gallery_height : gallery_height + HANDLE_HEIGHT});
	
	// slideshow
	$('.slideshow').each(function(i) {
		var img = $(this).find('img:eq(0)');

		var old_h = img.attr("height");
		var old_w = img.attr("width");
		var w = Math.round((gallery_height * old_w) / old_h);

		$(this)
		.css({width: w, height: gallery_height})
		.cycle({delay: (i+1)*2000});
	});
	
	var displayWidth = (gallery_height * MENU_ITEM_WIDTH) / MAX_GALLERY_HEIGHT;
	init(gallery_height, displayWidth);
	
	if (!is_touch_device) {
		// jScrollPane
		var scrollPane = $('#scroll-pane').jScrollPane({
			hijackInternalLinks: true,
			animateScroll: true,
			xOffset: displayWidth+10
		});
		var api = scrollPane.data('jsp');
		
		$('.content_container').jScrollPane();
		
		// graphic button
		$(".jspDragRight").append('<div class="jspDragRightInner">');
	
		// horizontal mousewheel
		$('#scroll-pane').mousewheel(function(event, delta) {
			if ($(".jspDragRight").size()) {
				// solo si hay el handle
				var maxMousewheel = getMaxMousewheel();
				var minMousewheel = 0;
		
				$jspPane = $(this).find(".jspPane");
				var position = $jspPane.position();
				var left = position.left;
				left+= (delta * 100);
				if (left <= minMousewheel & left >= maxMousewheel) {
					$jspPane.css("left", left+"px");
				} else if (left > minMousewheel) {
					$jspPane.css("left", "0");
				} else {
					$jspPane.css("left", maxMousewheel+"px");
				}
			}
			event.preventDefault();
		});
	}	
	
	if (!is_touch_device) {
		// layer
		$("div.caption-container").caption();
	}
	
	$(window).resize(function() {
		resize($(this), api);
	});
	
	// hack for scroll pane. If it isn't set to 0 initially, it displays vertical scroll bars
	$("div.caption").css("height", "auto");
	
	// mostrar el helper si es necesario
	if ($("#scroll-helper").size()) {
		$("#scroll-helper").css({top: $("#header").height() + gallery_height - $("#scroll-helper").height()});
	  setTimeout('$("#scroll-helper").fadeOut(500);', 10000);
	}
	
	// cache vars
	$content = $("#content");
	$sections = $("#content .wrap div");
	var wrapPaddingTop = parseInt($("#content .wrap").css("padding-top"));
	var wrapMarginBottom = parseInt($("#content .wrap").css("margin-bottom"));
	
	// menu
	$('ul.menu a').click(function(e) {
		e.preventDefault();
		if (!$(this).parents("li").is(".selected")) {
			hideContent();

			var index = $(this).parents("ul").children("li").index($(this).parent());
	
			$section = $("#content .wrap div:eq("+index+")");
			$section.show();
			var height = $section.height() + wrapPaddingTop + wrapMarginBottom;

			$("#secciones_container li.selected")
			.removeClass("selected")
			.addClass("current");

			$.scrollTo($content, 800, 
				{onAfter: 
					function() {
						setTimeout (function() {
							$content.animate({height: height}, 600, function() {
								$.scrollTo($content, 800);
							});
						}, 500);
					}
				}
			);
		}
	});
	
	$("#content a.close").click(function(e) {
		e.preventDefault()
		$(".menu li.selected").removeClass("selected");
		selectSection();
		
		$.scrollTo('#container',800, 
			{onAfter: 
				function() {
					hideContent();
				}
			}
		);		
	});
	
	$("#secciones_container a").click(function() {
		var $li = $(this).parent();
		if ($li.is(".selected")) {
			return false;
		} else if ($li.is(".current")) {
			$(".menu_container ul.menu li").removeClass("selected");
			
			hideContent();
			
			selectSection();
		
			return false;
		}
		
	});
	
	// auto scroll al desplazarse a los laterales de la pantalla
	$(".autoscroll-left").hover(
		function() {
			api.scrollToPercentX(0, true, 20000);
		},
		function() {
			$(".jspDrag").stop();
		}
	);
	
	$(".autoscroll-right").hover(
		function() {
			api.scrollToPercentX(100, true, 20000);
		},
		function() {
			$(".jspDrag").stop();
		}
	);
});

function getMaxMousewheel() {
	return (getContentWidth() - $("#scroll-pane").width()) * -1;
}

function hideContent() {
	$content.height(0);
	$sections.hide();
}

function selectSection() {
	$("#secciones_container li.current")
	.removeClass("current")
	.addClass("selected");
}

function getGalleryHeight() {
	var h = $(window).height() - $("#header").height() - 20; // -20 margen inferior
	if (!is_touch_device) {
		h-= HANDLE_HEIGHT;
	}
	
	return Math.max(Math.min(h, MAX_GALLERY_HEIGHT), MIN_GALLERY_HEIGHT);
}

function init(gallery_height, displayWidth) {
	// cálculo de tamaño de las img y obj de las galerías
	$('#scroll-pane img, #scroll-pane iframe').each(function() {
		var old_h = $(this).attr("height");
		var old_w = $(this).attr("width");
		var w = Math.round((gallery_height * old_w) / old_h);
		$(this).attr("height", gallery_height);
		$(this).attr("width", w);
		
		$(this).parents(".slideshow").css({width: w, height: gallery_height})
	});
	
	// cálculo de tamaño del display (menu)
	$("#display").css({height: gallery_height, width: displayWidth});
	// cálculo del alto de los auto scrollers
	$(".autoscroll").css({height: gallery_height});
	// cálculo del alto de los li de la galería
	$('#scroll-pane li').css({height: gallery_height});
	// cálculo del alto del scroll pane
	$('#scroll-pane').css({height: is_touch_device ? gallery_height : gallery_height + HANDLE_HEIGHT});
	
	// cálculo del ancho de la ul de la galería
	var contentWidth = getContentWidth();
	$('#scroll-pane ul').css({width: contentWidth});
	
	if (is_touch_device) {
		$('#scroll-pane').css({width: contentWidth});
		$('div.sombra_inferior_bottom').css({width: contentWidth});
		$('#footer').css({width: contentWidth -19}); // padding-left
		$('#header_bkg').css({width: contentWidth});
	}
	
	// cálculo de tamaño de los elementos del menú
	$(".menu_container2 img").each(function() {
		var w = Math.round((gallery_height * MENU_ITEM_WIDTH) / 900);
		var h = Math.round((gallery_height * MENU_ITEM_HEIGHT) / 900);
		
		$(this).attr("height", h);
		$(this).attr("width", w);
		
		$(this).parent().css({width: w, height: h}) // <a>
	});
}

function resize($window, api) {
	var gallery_height = getGalleryHeight();
	var displayWidth = (gallery_height * MENU_ITEM_WIDTH) / MAX_GALLERY_HEIGHT;
	init(gallery_height, displayWidth);
	
	$('.jspContainer').css({height: gallery_height + HANDLE_HEIGHT});
	
	if (!is_touch_device) {
		api.resize($window.width(), $('#scroll-pane ul').width());
		api.xOffset(displayWidth+10);
	}
	
	// graphic button
	if (!$(".jspDragRight .jspDragRightInner").size()) {
		$(".jspDragRight").append('<div class="jspDragRightInner">');
	}
	
	$.fn.caption.init("div.caption-container");
}

function getContentWidth() {
	var contentWidth = 0;
	$('#scroll-pane li').each(function() {
		var width = 0;
		// si es un slideshow, no calcula el ancho correctamente
		if ($(this).children(".slideshow").size()) {
			if ($(this).children(".slideshow").children("img").size()) { // a lo mejor no se han encontrado las imágenes
				var max = 0;
				$(this).children(".slideshow").children("img").each(function() {
					if ($(this).attr("width") > max) {
						max = $(this).attr("width");
					}
				});
				width = max;
			}
		} else {
			var $child = $(this).children();
			if ($child.is("img") || $child.is("iframe")) {
				width = parseInt($child.attr("width"));
			}
		}
		contentWidth+= width;
		$(this).css({width: width});
	});
	
	return contentWidth;
}
