/*
*** Coded with loving care by Mat at Demotive ***
***	    "Toiling since '75" | Summer 2010     ***
*** .......... www.demotive.com ............. ***
*/

var createAccordion = function($el) {
	
	var $col_1_els = $el.find('.col_1');
	var $col_2_els = $el.find('.col_2');
	var $col_3_els = $el.find('.col_3');
	var $col_4_els = $el.find('.col_4');
	
	// re-stack into column lists (avoid the float blowing)
	
	if ($('body').hasClass('category')) {
		$el.after('<div class="crosslinks">');
		
		$col_1_els.appendTo('div.crosslinks').wrapAll('<ul class="col_container" role="navigation" />');
		$col_2_els.appendTo('div.crosslinks').wrapAll('<ul class="col_container" role="navigation" />');
		$col_3_els.appendTo('div.crosslinks').wrapAll('<ul class="col_container" role="navigation" />');
		$col_4_els.appendTo('div.crosslinks').wrapAll('<ul class="col_container" role="navigation" />');
		
		$el.remove();
	}
		
	attachAccordion($col_1_els);
	attachAccordion($col_2_els);
	attachAccordion($col_3_els);
	attachAccordion($col_4_els);
	
}

var attachAccordion = function($els) {
	$els.css("position", "static").find('.panel_pic').css('height', '100px');
	$els.not(':first').find('.panel_pic').css('height', '0px');
	$els.each(function(el, i) {
		$(this).mouseenter(function() {
			var $openingEl = $(this).find('.panel_pic');
			var $closingEls = $els.not(this).find('.panel_pic');
			var $closingEl;
			$closingEls.each(function(el, i) {
				if($(this).height() > 0) {
					$closingEl = $(this);
				}
			});
			$openingEl.stop().animate({
				height: 100,
				queue: false
			}, 200);
			$closingEl.stop().animate({
				height: 0,
				queue: false
			}, 200);
		});
	});
}

$(document).ready(function() {

	// 1. accordions
	if ($('body:not(.single, .news) .crosslinks_block:first .crosslinks').length > 0) {
		createAccordion($('.crosslinks_block:first .crosslinks'));
	}
	
	// 2. Tabs
	if ($('.panes').length > 0) {
		$('div.panes > div > h3').remove()
		// match heights
		var elHeight = 0;
		$("div.panes > div").each(function() {
			var myHeight = $(this).height();
			if (myHeight > elHeight) {
				elHeight = myHeight;
			}
		});
		$("div.panes > div").height(elHeight + "px");
		$("ul.tabs").tabs("div.panes > div");
	}
	
	// 3. Ajax calendar functionality, footer only
	// hijack the monthly <a> tags
	// change the reference for the links to return just /site/calendar template
	$("div#events .previous_month a, div#events .next_month a").live('click', function(event) {
		var linkStr = $(this).attr("href");
		var newLink = linkStr.replace("events", "calendar");
		$("div#events").animate({ opacity: 0 }, 200, function() {
			$(this).load(newLink, function() {
				$(this).animate({ opacity: 1 }, 200);
			});
		});
		event.preventDefault();
	});
	
	// 4. Search field checking
	$("#treb_search").submit(function() {
		if($(this).children(".input").val() == "") {
			$(this).addClass("error");
			return false;
		}
	});

});
