// simple string templating
String.prototype.fill = function(o) {
	return this.replace(/{([^{}]*)}/g,
		function(a, b) {
			var r = o[b];
			return typeof r === 'string' || typeof r === 'number' ? r: a;
		});
};
/*
 *
 * Copyright (c) 2006/2007 Sam Collett (http://www.texotela.co.uk)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 */
/*
 * jQuery Image Replacement. An alternative to using CSS hacks
 * The id attribute (or class) is used for the filename
 *
 * @name     jQIR
 * @param    String format    Image format/file extension (e.g. png, gif, jpg) - ignored if specifying the filename in the class
 * @param    String path      (optional) Path to images folder 
 * @param    Function onload  (optional) Function to run when image has loaded 
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @author   Sam Evans changed $ to jQuery reference; added semicolons (2009-10-31)
 * @example  $(".jqir").jQIR("png", "images/");
 * @before   <h1 id="heading1" class="jqir">Heading 1</h1>
 *           <h2 class="jqir {src:heading2.png}">Heading 2</h2>
 * @result   <h1 id="heading1" class="jqir"><img alt="Heading 1" src="images/heading1.png"></h1>   
 *           <h2 class="jqir {src:heading2.png}"><img alt="Heading 2" src="images/heading2.png"></h2>   
 * @example  $(".jqir").jQIR("gif"); // use same folder as page
 * @before   <h1 id="heading1" class="jqir">Heading 1</h1>
 * @result   <h1 id="heading1" class="jqir"><img alt="Heading 1" src="heading1.gif"></h1>   
 *
 */
jQuery.fn.jQIR = function(format, path, onload)
{
	if(!document.images) return this;
	path = path || "";
	this.each(
		function()
		{
			var img = jQuery("<img>"), el = jQuery(this);
			var file;
			var re = /(?:{src\:)(\S+)(?:})/i;
			var m = this.className.match(re);
			if(m)
			{
				file = path + m[1];
			}
			else
			{
				file = path + this.id + "." + format;
			}
			
			jQuery(img).attr(
			{
				src: file,
				alt: el.text()
			}).load(typeof onload == "function" ? onload : function(){} );
			var a = el.find("a");
			var toAppend = a.length ? a.empty().append(img) : img;
			el.empty().append(toAppend);
		}
	);
	return this;
};

//	Execution starts here
	
jQuery.lazy({
	name: 'dataTable',
	src:  '/js/jquery.datatables.min.js',
	cache: true
});
	
//	Ready

jQuery(document).ready(function($){
	
	try {
		// .content must be at least as tall as #primary, .after-content
		var columns, heights, tallest, pad;
		columns = $('.content, .after-content, #primary:visible');
		heights = columns.map( function () {
				return $(this).innerHeight();
			});
		heights = $.makeArray(heights);
		tallest = Math.max.apply( null, heights );
		$('.content').each( function () {
			var diff = Math.max( 0, tallest - $(this).innerHeight() );
			if ( diff ) {
				$(this).css( 'min-height', diff + $(this).innerHeight() );
			};
		});
	} catch (e) {};
	
	try {
		// headline text to image
		$('.as-image').jQIR();
	} catch (e) {};
	
	try {
		// Main nav: hover turns other tabs inactive
		$('#main-nav li').hover(function() {
			$('#main-nav li').not(this).addClass('inactive');
		}, function() {
			$('#main-nav li').removeClass('inactive');
		});
	} catch (e) {};
	
	$("table").dataTable( {
		bAutoWidth: false,
		bAutoWidth: false,
		bFilter: true,
		bInfo: true,
		bLengthChange: false,
		bPaginate: false,
		bProcessing: false,
		bSort: true,
		bStateSave: true
	});
	
	try {
		// Ext links open in new window
		$('a[href]').each(function(index) {
			if ( this.href && -1 == this.href.search(location.hostname) ) {
				$(this).click(function() {
					window.open(this.href);
					return false;
				});
			};
		});
	} catch (e) {};
		
	try {
		// Contact: Schools
		$('body.page-contact #schools h3+ul').hide();
		$('body.page-contact #schools h3').addClass('clickable').click(function() {
			$('body.page-contact #schools h3+ul:visible').slideUp();
			$(this).next('ul:hidden').slideDown();
		});
	} catch (e) {};
	
	
	try {
		// Persons
		var persons = $('#persons');
		var eachPerson = $('#persons .person');
		if (persons.length && eachPerson.length) {
			var personFull = $('<li id="person-full" class="editable"></li>');
			personFull.hide().insertAfter('#persons .person:eq(2)');
			eachPerson.addClass('clickable').click(function() {
				var activePerson = $(this);
				var personDescription = activePerson.find('.person-about').clone();
				eachPerson.removeClass('active');
				activePerson.addClass('active');
				if (personFull.is(':visible')) {
					personFull.fadeOut('normal', function() {
						var oldHeight = $(this).height();
						// set fixed height (old)
						// substitute new description
						$(this).html(personDescription).css('height', 'auto');
						var newHeight = $(this).height();
						$(this).height( oldHeight )
							.animate({height: newHeight, opacity: 'show'}, 'normal', 'swing', function() {
								$(this).css('height', 'auto');
							});
					});
				} else {
					personFull.html( personDescription ).slideDown();
				};		
			}); // eachPerson.click
			
			// $('.entry-content').append("<p><b>Click on a photo below to meet some of our students</b></p>");
			
		}; // if persons
	} catch (e) {};
	
	var shareTemplate = ' <span class="news-item-share">Share: <a href="{facebookUrl}" title="Share “{headline}” on Facebook"><img alt="Facebook" src="/wp-content/themes/kipp/img/facebook-16x16.png" width="16" height="16" /></a> <a href="{twitterUrl}" title="Tweet about “{headline}”"><img alt="Twitter" src="/wp-content/themes/kipp/img/twitter-16x16.png" width="16" height="16" /></a></span>';
	
	$("#news-items h3 > a[href]").each(function () {
		var item = {};
		var $heading = $(this).parent();
		
		item.url = this.href;
		item.headline = $heading.text();
		item.facebookUrl = "http://www.facebook.com/sharer.php?u={encodedUrl}&t={encodedTitle}"
			.fill({ encodedUrl: encodeURIComponent(item.url), encodedTitle: encodeURIComponent(item.headline) });
		item.twitterUrl = "http://twitter.com/home?status="
			+ encodeURIComponent("Reading {headline} {url}".fill(item));
		
		var shareHtml = shareTemplate.fill(item);

		$heading
			.nextAll("p")
				.eq(1) // 2nd paragraph
				.append(shareHtml);
	});

}); // end ready