function initPlugins(el){
	$el = $(el);
	$('input:radio, input:checkbox', $el).NiceForm();
	$('.autosuggest', $el).each(function(){
		var model = $(this).attr('rel');
		$(this).autoSuggest('/ajax/autosuggest/' + model, {neverSubmit:true, usePost:true, preFill:$(this).val()});
	});
	//$('select:not[multiple]').selectmenu();

	// delete/cancel
	$('#delete').hide();
	$('a[href=#delete]').live('click',function(){
		var btn = $(this),
			delDiv = $(this).next('#delete');
		btn.slideUp(200);
		delDiv.slideDown(200, function(){
			$(this).find('a[href=#cancel]').click(function(){
				delDiv.slideUp();
				btn.slideDown();
				return false;
			});
		});
		return false;
	});
}

$(function(){

	// Login area
	if( $('#login').length ){

		var hash = window.location.hash;
		if( !$(hash).length ) hash = '#login_init';

		$('#loginbox > div').hide();
		$(hash).show();

		$('#loginbox a[href^=#]').live("click", function(){
			var closest = $(this).closest('div'),
				target = $( $(this).attr('href') );
			closest.fadeOut('fast', function(){
				target.fadeIn();
			});
			return false;
		});
	}

	// flashmsg
	$('#flashmsg').fadeOut(250).fadeIn(250);
	$('#flashmsg .close').click(function(){
		$('#flashmsg').fadeOut('fast');
		return false;
	});

	// init plugins...
	initPlugins('body');

	// fancybox
	$('a.fancybox').fancybox({
		padding:10,
		overlayOpacity:.5,
		overlayColor:'#000',
		showNavArrows:false,
		scrolling:'no',
		onComplete: function(el){
			var rel = $(el).attr('rel');
			if( rel.match(/^js\:/) ){
				var js = rel.replace(/js\:/,''),
					jsArray = js.split(',');
				for(i in jsArray){
					$.getScript('/media/js/' + jsArray[i]);
				}
			}
			initPlugins('#fancybox-content');
			Cufon.refresh();
		}
	});

	// jcarousel
	$('ul.carousel').jcarousel({itemFallbackDimension:202, scroll:2});
	$('ul.carousel_small').jcarousel({itemFallbackDimension:110});


	// add tags to input
	$('#tags_suggested a').click(function(e){
		e.preventDefault();
		var tag = $(this).text().toLowerCase(),
			presskey = jQuery.Event("keydown");
			presskey.keyCode = 13; // Return
		// Suspending focus as this was selecting the wrong input field:
		// $('input[rel=tag]').val(tag).focus().trigger(presskey);
		$(this).parents('fieldset').find('input[rel=tag]').val(tag).focus().trigger(presskey);
	});

	// 'none' checkbox...
	$('input:checkbox[name^=none]').each(function(){
		var none = $(this),
			siblings = none.closest('label').siblings().find(':checkbox');

		none.click(function(){
			if( $(this).is(':checked') ){
				siblings.removeAttr('checked').NF_UpdateState();
			}
		});

		siblings.click(function(){
			if( $(this).is(':checked') ){
				none.removeAttr('checked').NF_UpdateState();
			}
		});
	})

	// tabs
	function showTab(trigger){
		if( !trigger.hasClass('current') ){
			var target = $(trigger.attr('href')),
				tabsNav = trigger.closest('ul'),
				tabs = tabsNav.closest('.tabs_nav').next('.tabs_content').find('.tab');

			tabsNav.find('a').removeClass('current');
			trigger.addClass('current');
			tabs.hide();
			target.show();
		}
	}
	$('.tabs_nav').each(function(){
		var links = $(this).find('a');
		if( !links.filter('.current').length ){
			showTab(links.eq(0));
		}
		links.click(function(){
			showTab($(this));
			return false;
		});
	});

	// hover info
	$('.hover_info').each(function(){
		var info = $(this),
			height = info.outerHeight(),
			container = info.closest('.img').css({overflow:"hidden"});
		info.css({top:-height});
		container.hover(function(){
			info.animate({top:0},500);
		},
		function(){
			info.animate({top:-height},500);
		})
	});

	// open external links in new windows
	$('a[href^=http]').each(function(){
		var href = $(this).attr('href');
		if( !href.match(/cousteaudivers\.org/) ){
			$(this).click(function(){
				window.open(href);
				return false;
			})
		}
	});

	// open JYC image link in new window
	$('#cousteau').click(function(){
		window.open($(this).attr('href'));
		return false;
	});

	/* Membership options: */
	$('button.duration').click(function() {
		var value = $(this).val();
		$('#buy_membership input[name=duration]').val(value);
		$('button.duration').removeClass('btn_blue');
		$(this).addClass('btn_blue');
		Cufon.refresh();
		return false;
	});

	/* Paginate the activity streams: */
	var activity_per_page = 6;
	$('#activity_pagination a').click(function() {
		var page = $(this).attr('rel');
		if (page == 1) {
			filter_activity(1,activity_per_page);
		}
		else if (page == 2) {
			filter_activity(activity_per_page+1,activity_per_page*2);
		}
		else if (page == 3) {
			filter_activity((activity_per_page*2)+1,activity_per_page*3);
		}
		$('#activity_pagination a.current').removeClass('current');
		$(this).addClass('current');
		return false;
	});

	// Hide all but the first seven activity items by default:
	filter_activity(1,activity_per_page);

	// Flag the guestbook posts as inappropriate
	// (this should be easily extended to media)
	$('#community_guestbook a.flag_as_inappropriate').click(function() {
		var id = $(this).attr('rel');
		var thanks = $.ajax({
			url: '/ajax/flag',
			type: "POST",
			data: ({id : id, myclass: 'guestbook', flag: 'inappropriate'}),
			async:false
		}).responseText;

		$(this).replaceWith(thanks);

		return false;
	});
	$('#community_guestbook a.flagged_as_inappropriate').live('click',function() {
		return false;
	});

});

function filter_activity(from,to) {
	$('#activity_stream li').each(function() {
		var c = $(this).attr('class');
		var n = parseInt(c.replace('cfx activity_',''));
		// Hack! Put a proper regex here, I'm just on the train at the moment without access to a JavaScript reference :-)
		if (n < from || n > to) {
			$(this).hide();
		}
		else {
			$(this).show();
		}
	});
	// Add a first-child psueod class to the first li that we've just shown...
	$('#activity_stream li').removeClass('first-child'); // Not strictly necessary
	$('#activity_stream li:nth-child('+from+')').addClass('first-child');

}

/* Revising search form: */
$(function() {
	$('#search_form').hide();
	
	$('#toggle_search').toggle(
		function() {
			$('#search_form').show();
			$(this).find('span').text("Hide Search Form");
			Cufon.refresh();
			return false;			
		},
		function() {
			$('#search_form').hide();
			$(this).find('span').text("Show Search Form");
			Cufon.refresh();			
			return false;		
		}
	);
	
});

