$(document).ready(function(){

		var SF_error = {

			log: function(str) {
				if (typeof console.log !== 'undefined') {
					console.log(str);
				}
			}
		};

		if ( $('#e_lib_pubs').exists() ) {

		var tableClass = $('#e_lib_pubs').attr('class');

		if (tableClass.indexOf('links') == -1) {
			  $("#e_lib_pubs").tablesorter({
			  		sortList: [[1,1]],
			  		dateFormat: 'uk',
			  		headers: {
			  			0: { sorter: false },
			  			4: { sorter: false },
			  			5: { sorter: false }
			  		}
			  	});


		}
		else {

			  $("#e_lib_pubs").tablesorter({
			  		sortList: [[2,1]],
			  		dateFormat: 'uk'
			  	});


		}


		predictiveSearch('#e_lib_pubs', tableClass);


		}


		$('.home_col4').equalize();
		$('.home_col2').equalize();

		$(".image_caption img[title]").tooltip({effect: 'bouncy'});
		$("#nicva a.caption").tooltip({effect: 'bouncy'});

		$("body.home .block_wrap:even").addClass("alt");

		$(".block_wrap").fittd();
		$("#home_top_pages .col").fittd();
		$("#home_news .item").fittd();
		$(".news_block").fittd();
		$(".news_block").fittd();
		$("#connect_nicem").fittd();
		$("#bill_of_rights").fittd();
		$("#nicva").fittd();
		$("#twitter").fittd();

		if($("#disclaimer").length != 0)
		{
			$("#disclaimer").hide();
			setTimeout(function(){$("#disclaimer").slideDown("slow");}, 1000)
		}



		$("table tr:even").addClass('alt');
		$("table tr").hover(
			  function () {
				$(this).addClass("ruled");
			  },
			  function () {
				$(this).removeClass("ruled");
			  }
			);
		$("table.publications tbody tr").click(
			  function () {
				var link = $("a.target", this).attr("href");
				window.location = link;
			  }
			);
		$("table tr").hover(
		  function () {
			$(this).addClass("ruled");
		  },
		  function () {
			$(this).removeClass("ruled");
		  }
		);


		$('#slideshow').cycle({
			fx: 'fade',
			timeout:       9000
		});


	if ( $('.ajax_form').exists() ) {
		addFormIDs(".ajax_form");
				$(".ajax_form").ajaxForm({
				    target: '#alert',
					success: function() {
				       hideForm(".ajax_form")
				        return false;
				        }
				});
	}

	if(document.getElementById("monitoring_form"))
	{
		formFieldToggle("contact_check", "div#form_contact_details");
		formFieldToggle("intrepreter_check", "div#form_intrepreter_language");
	}

	track_downloads("#main a");

	var search_focus = 0;
	$('#search_terms').focus(function() {
		search_focus++;
		if (search_focus) {
			$(this).val('');
		}
	});

});


function formFieldToggle(trigger, field)
{

	$(field).hide();
//	console.log("Action: INIT Trigger: "+trigger+" Field: "+field);

	$("[name="+trigger+"]").change(function()
	{
		if ($("[name="+trigger+"]").is(':checked'))
		{
			$(field).slideDown();
//			console.log("Action: DOWN Trigger: "+trigger+" Field: "+field);
		}
		else
		{
			$(field).slideUp();
//			console.log("Action: UP Trigger: "+trigger+" Field: "+field);
		}
	});

}


function hideForm(form)
{

	var className = $("#alert div:first").attr("class");
	var idName = $("#alert div:first").attr("id");


	//hide form on successful submission (i.e info rather than error div class)
	if(className == "info")
	{
		$(form).slideUp();
		$("alert").hide().fadeIn();

		if(idName == "members")
		{
			window.location = "/members_area"
		}


		if(document.getElementById("paypal_confirm"))
		{
			$("#paypal_confirm").submit();
		}

	}

	//clear any previously highlighted fields
	$(':input', form).each(function() {
		$(this).parent('div').removeClass("error")
		.animate({ backgroundColor: "#fff" }, "fast");
	});

	//highlight error fields
	var errors = $("#error_report").html();
	if(errors !== null)
	{
		errors = errors.split(",");
		for (i in errors) {
			$("#form_"+errors[i]).addClass("error");
			$("#form_"+errors[i]).animate({ backgroundColor: "#FBE6F2" }, "slow")
			.animate({ backgroundColor: "#fff" }, "slow")
			.animate({ backgroundColor: "#FBE6F2" }, "slow");
		}
	}


}


function addFormIDs(form)
{

	$(':input', form).each(function() {
		$(this).parent('div').attr("id", "form_"+this.name);
	});

}


/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}

	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break;

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};

})(jQuery);



/*
 * jQuery Larger Clickable areas (Fitts Law)
 * Copyright 2009 Eoin McGrath
 * Released under the MIT and GPL licenses.
 */

(function($) {
	$.fn.fittd = function(options) {

	this.each(function() {

		var $this = $(this);
			$this.hover(function(e) {
				$this.addClass('active');

			}, function() {
				$this.removeClass('active');
			});
				$this.click(function (e) {
					var $link = $('a.target', this).attr("href");

					if(!$link) {
						$link = $('a:first', this).attr("href");
					}

					if($link) {
						window.location = $link;
					}

 				});
		  });

		  return this;

	}
})(jQuery);



function track_downloads(div)
{


	$(div).each(function() {

		if($(this).attr("hostname") == location.host)
		{
			var isDoc = $(this).attr("href").match(/\.(?:doc|eps|jpg|png|svg|xls|ppt|pdf|xls|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3)($|\&|\?)/);

			if(isDoc)
			{

				var download = $(this).attr("href");
				download = download.replace(/https?:\/\/(.*)/,"$1");
				download = '/download' + download;

				$(this).click(function () {
					pageTracker._trackPageview(download);
				});


			}

		}


	});

	return;

}


function is_internal_link(link, host){

	if(link.match(/^mailto\:/)) {
		console.log('mailto');
		return false;
	}

	if(host !== location.hostname); {
		console.log('not same domain:'+' '+host+' = '+location.host);
		return false;
	}

console.log('internal');
	return true;

};


// checks if element exists
(function($) {
	$.fn.extend(
		{ exists: function() {
			return this.length>0;}
		});
})(jQuery);



// sets all .div to the same height
(function( $ ){
  $.fn.equalize = function() {

	tallest = 0;

    $(this).each(function() {

		if ($(this).height() > tallest) {
			tallest = $(this).height();
		}
    });

	$(this).each(function() {
		$(this).css({'height': tallest});
	});

  };
})( jQuery );


// create custom animation algorithm for jQuery called "bouncy"
$.easing.bouncy = function (x, t, b, c, d) {
    var s = 1.70158;
    if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
    return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;

}

// create custom tooltip effect for jQuery Tooltip
$.tools.tooltip.addEffect("bouncy",

	// opening animation
	function(done) {
		this.getTip().animate({top: '+=15'}, 500, 'bouncy', done).show();
	},

	// closing animation
	function(done) {
		this.getTip().animate({top: '-=15'}, 500, 'bouncy', function()  {
			$(this).hide();
			done.call();
		});
	}
);


function predictiveSearch(tableId, tableClass) {



	$('#elib_search').submit(function() {

		var searchTerms = $('#filter').val();
		var searchCat = $('#category').val();

		searchTerms = searchTerms.toLowerCase();
		var found = 0;

		$(tableId+' tr').each(function() {
			var table_id = $(this).attr('id');
			var ref_id = table_id.replace('table_', '');

			// reset in case was hidden in previous search
			$('#table_'+ref_id).show();

			var txt = $('#ref_'+ref_id).html();
			var cat = $('#ref_'+ref_id).children('span').html();

			if (typeof txt == 'string') {

				var matchCat = true;

				if (searchCat.length && typeof cat == 'string') {
					matchCat = (cat.indexOf(searchCat) != -1)
						? true
						: false;

						console.log('CAT: '+cat+'Search: '+searchCat+' RES: '+''+matchCat);
				}

				txt = txt.toLowerCase();
				if (txt.indexOf(searchTerms) != -1 && matchCat) {
					found++;
				}
				else {
					$('#table_'+ref_id).hide();
				}

			}

		});


		var contentType = (tableClass == 'publications')
			? 'publications'
			: 'links';

		contentType = contentType.substring(0, contentType.length-1);

		searchTerms = (searchTerms) ? searchTerms : 'everything';
		searchCat = (searchCat) ? searchCat : 'All Categories'
		var resultString = 'Searched for <b>'+searchTerms+'</b><br /> Found '+found+' '+contentType;
		if (searchCat) {
			resultString += ' in <em>'+searchCat+'</em>';
		}
		$('#liveResultSummary').html(resultString).hide().fadeIn('slow');


		return false;

	});


}


