$(document).ready(function() {

    $("table").tablesorter({
        // sort on the first column and third column, order asc
        sortList: [[0,0],[2,0]]
    });

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

    if ( $('#slideControls').length > 0 ) {
        // alert('fading')
        $('#slideControls').fadeTo(0,0.5); 
        $('#slideControls').hover(
            function() {
                $(this).fadeTo('fast',0.8); 
            },
            function() {
                $(this).fadeTo('fast', 0.5); 
            }
        );
    }

	$('#next-meeting div').equalHeights();

	// some ajax goodness for the accessibility toolbar
	$('p#skip a').click(function() {
		var link = $(this).attr('href');
		var id = $(this).attr('id');

		// ignore the 'skip to nav' link
		if(link != '#header' && link != '/pcc/styleswitch') {

			$.ajax({
				type: 'GET',
				url: link,
				success: function(data) {

						console.log(data);

						// inject css into header
						$("head").append("<link>");
						css = $("head").children(":last");
						css.attr({
							rel:  "stylesheet",
							type: "text/css",
							href: "/themes/pcc/css/"+data
						});

						// if textresize set to active
						if(link.indexOf('textsize') != -1) {
							$('p#skip a').removeClass('active');
							$('a#'+id).addClass('active');
						}



						if(id == 'toggle_style' && data == 'main.css') {
							$('a#toggle_style').html('High Contrast');
						}
						else if(id == 'toggle_style' && data == 'hicontrast.css') {
							$('a#toggle_style').html('Normal Version');
						}


						//unload the hicontrast.css if need be
						if(data == 'main.css') {
							$('link[rel=stylesheet]').each(function() {
								var href = $(this).attr('href');
								if(href == '/themes/pcc/css/hicontrast.css') {
									$(this).remove();
								}
							});



						}

				}
			});
			return false;
		}
	});


	//scroll to local page anchors
	$('a[href*=#]').click(function() {
		if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
		&& location.hostname == this.hostname) {
				var $target = $(this.hash);
				$target = $target.length && $target
			|| $('[name=' + this.hash.slice(1) +']');
			if ($target.length) {
			var targetOffset = $target.offset().top;
			$('html,body')
			.animate({scrollTop: targetOffset}, 1000);
				return false;
			}
		}
	});


	// style cms image (is loaded)
	$('img.clip').prepend('<div class="paperclip"></div>');

	// force footer divs to equal height for consistent look
	$('.fblock').equalHeights();

//	$('#wrapper form input:first').focus();

	$("p#feedback a:first").attr("id", "feedback_link");
	$("p#feedback img").attr("alt", "");

	$("#feedback_link").fancybox({
		'width'				: '40%',
		'height'			: '85%',
		'autoScale'			: false,
		'transitionIn'		: 'elastic',
		'transitionOut'		: 'elastic',
		'titlePosition'		: 'inside',
		'type'				: 'iframe'
	});

	$('ul.gallery li a').fancybox({ 'titlePosition' : 'inside' });

	$("#slideshow span.control").fadeTo('fast', 0.3);

	$('#slideshow').bind('mouseenter', function() {
	 	$("#slideshow span.control").fadeTo('fast', 0.8);
	});

	$('#slideshow').bind('mouseleave', function() {
		$("#slideshow span.control").fadeTo('fast', 0.3);
	});


	//load twitter feed
	$('#twitter_feed').load('/pcc/tweets/patientclient');

	//newsletter subscribe
	$('#newsletter input:first').click(function () {
		$(this).val('');
	});

	//newsletter subscribe
	$('input#searchfield').click(function () {
		$(this).val('');
	});


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



	// board meetings
	$('table.zebra tr:nth-child(odd)').addClass('on');
	$('#meetings-table form:last').addClass('last');
	if ( $('#next-meeting-date').length ) {
		var html = $('#next-meeting-date').html();
		$(html).insertAfter('#content-area p:first');
		$('#next-meeting-date').remove();
	}

});



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 == "success")
	{
		$(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 Plugin: "EqualHeights"
 * by:	Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com)
 *
 * Copyright (c) 2008 Filament Group
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * Description: Compares the heights or widths of the top-level children of a provided element
 		and sets their min-height to the tallest height (or width to widest width). Sets in em units
 		by default if pxToEm() method is available.
 * Dependencies: jQuery library, pxToEm method	(article:
		http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/)
 * Usage Example: $(element).equalHeights();
  		Optional: to set min-height in px, pass a true argument: $(element).equalHeights(true);
 * Version: 2.0, 08.01.2008


 * 29 May 09	- EDITED to work without dependencies & doesn't bother with children just the class passed to the fn
				- eoin@starfish.ie
--------------------------------------------------------------------*/

$.fn.equalHeights = function() {
	var currentTallest = 0;
	$(this).each(function(){

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

	$(this).each(function(){

		$(this).css({'height': currentTallest});

	});


	return this;
};


