(function($){
	
	function pr(s) {
		console.log(s);
	}
	
	function position() {
		var w = $(window).height();
		var g = $('#global').height();
		if(w > g) {
			$('#global').css('margin-top', ((w - g) / 3));
		}
		
	}
	
	function fixHeight() {
		var minTotalHeight = 572;
		var maxTotalHeight = 640;
		var total = $('#global');
		var minHeight = 371;
		var content = $('nav.global, section.global, aside');
		
		var newHeight = $(window).height() - 40;
		newHeight = Math.min(Math.max(newHeight, minTotalHeight), maxTotalHeight);
		
		var diff = newHeight - total.height();
		total.height(newHeight);
		content.height(content.height() + diff);
	}
	
	function slideshow() {
		var slideshow = $('section.slideshow');
		if(!slideshow.size()) {
			return;
		}
		
		var collection = [];
		slideshow.find('p').each(function() {
			var p = $(this);
			if(p.find('img').size()) {
				if(collection.length) {
					$(collection).wrapAll('<div class="slide"><div class="slide-content"></div></div>');
					collection = [];
				}
				p.wrap('<div class="slide img"><div class="slide-content"></div></div>');
			} else {
				collection.push(p[0]);
			}
		});
		
		
		var w = $('section.global').width();
		var slides = slideshow.find('.slide');
		slides.css({float: 'left', width: w});
		
		var wrapper = $('<div class="wrapper"></div>').css('width', w * slides.size());
		slideshow.wrapInner(wrapper);
		
		$('section.global').css('overflow', 'hidden');
		$('section.global .content').css('margin', 0);
		
		
		slides.not(':last').click(function() {
			$('section.global').scrollTo({'left': '+=' + w + 'px', 'top': 0}, 400);
		});
		
		$('a.next').click(function(e) {
			e.preventDefault();
			$('section.global').scrollTo({'left': '+=' + w + 'px', 'top': 0}, 400);
		});
		
		$('a.prev').click(function(e) {
			e.preventDefault();
			$('section.global').scrollTo({'left': '-=' + w + 'px', 'top': 0}, 400);
		});
		
	}
	
	function menufix() {
		$('.current-page-ancestor').parents('li').addClass('current_page_ancestor');
	}
	
	function imgfix() {
		$('img.alignleft').parents('p').addClass('left-img');
		$('img.alignleft').parents('h3').addClass('left-img');
	}
	
	function fancybox() {
		$('a.wp-oembed').fancybox({
			'titleShow'		: false
		});
	}
	
	function copyForm() {
		
		function fix() {
			if($('#sendcopy input').filter(':checked').size()) {
				// checked
				$('#sendcopyemail').val($('input[name=your-email]').val());
			} else {
				// not checked
				$('#sendcopyemail').val('no-copy');
			}
		}
		$('#sendcopy input').change(function() {
			fix();
		});
		
		$('form').submit(function() {
			fix();
		});
	}
	
	$(document).ready(function() {
	  fixHeight();
		$(window).resize(position);
		$(window).resize(fixHeight);
		position();
		slideshow();
		menufix();
		imgfix();
		fancybox();
		copyForm();
	});
	
}(jQuery));
