var path = location.pathname.toLowerCase();
if (path.substring(path.length-1) == '/') path += 'index.html';
path += location.search + location.hash;

$(window).load(function() { resize_images(); });

$(function() {
	$('li.cat > span:not(:has(a))').wrap('<div class="event-catcher" style="display: inline-block; margin-left: -16px; padding-left: 16px; cursor: pointer;"/>');
	$('li.cat > div.event-catcher').click(function(event) {
		event.stopPropagation();
		$(this).parent().toggleClass('expanded').find('> ul').slideToggle('fast');
	});
	
	// highlight the path
	//$("a[href='"+path+"']").parents('li').addClass('selected').find('> ul').show();
	// avoid highlighting multiple items at the same node level
	$('li.selected ~ li.selected').removeClass('selected');
	
	// tooltips for tutorial descriptions
	$("ul.tutorials li.video > span > a").tooltip({ track:true, delay:0, showURL:false, showBody:"//", fade:500 });
	
	// resize large images -- click to zoom
	resize_images();
});

function resize_images() {
	var max = {width:790, height:600};
	var small = 0.6;
	
	$(".content img:not(.resized)").each(function() {
		var $img = $(this);
		var width = $img.width();
		var height = $img.height();
		var offset = $img.offset();
		if (width && height) {
			width = parseInt(width);
			height = parseInt(height);
			var origsz = {width:width, height:height};
			if (origsz.width > max.width || origsz.height > max.height || offset.left + width > 1000) {
				var smallsz = {width:Math.round(origsz.width*small), height:Math.round(origsz.height*small)};
				$img.data('original_size', origsz).data('small_size', smallsz).data('zoomed', false);
				$img.addClass('resized').css(smallsz).css({
					display: 'block',
					margin: 0,
					cursor: 'pointer'
				});
				$img.wrap('<div class="image"/>').parent().append('&nbsp;').css({
					width: smallsz.width,
					height: smallsz.height
				});
				$img.attr('title', 'Click to zoom in')
					.click(function() {
						if ($(this).data('zoomed')) {
							zoomout($(this));
						} else {
							zoomin($(this));
						}
					})
					.bind("mouseleave", function() {
						if ($(this).data('zoomed')) {
							zoomout($(this));
						}
					});
			}
		}
	});
}

function zoomin(img) {
	var origsz = img.data('original_size');
	img.data('zoomed', true)
		.attr('title', '')
		.css({
			position: 'absolute',
			zIndex: 999,
			border: '2px solid red',
			marginTop: '-2px',
			marginLeft: '-2px'
		})
		.animate($.extend(origsz,{marginLeft:'-100px'}), 300);
}

function zoomout(img) {
	var smallsz = img.data('small_size');
	img.data('zoomed', false)
		.css({position:'relative'})
		.animate($.extend(smallsz,{marginLeft:0}), 300)
		.css({
			zIndex: 0,
			border: 'none',
			marginTop: 0
		})
		.attr('title', 'Click to zoom in');
}
