/**
 * CraftStylish.com: Taxonomy Behaviors for Share Forms (Categories and Tags)
 *
 * Copyright (c) 2008 Matthew Knight (http://www.reconstrukt.com)
 * for Taunton Press
 *
 * @requires jQuery v1.2
 *
 */

// max categories that can be checked
var max_categories = 4;

$(document).ready(function(){

	// bind events to a category checkbox
	$('input.post-category').each(function(){
		var o = $(this);
		o.click(function(){
			if (o[0].checked) {
				// this checkbox is checked
				// look at all other checkboxes.  if == 4 chcked, disable the rest.
				disable_category_checkboxes();
			} else {
				// unchecked
				// look at all other checkboxes.  if < 4 checked, enable rest.
				var tot = 0;
				$('input.post-category').each(function(){
					if ($(this)[0].checked) tot++;			 
				});
				if (tot < max_categories) {
					$('input.post-category').each(function(){
						if ( ! $(this)[0].checked ) {
							$(this)[0].disabled = false;
						}
					});
				}
			}
		});
	});
		
	// tag helper component
	// tabs
	$('div.tag-helper ul.tabs a').each(function(){
		$(this).click(function(){
			var a = $(this);
			// change class to unselected state
			$('div.tag-helper ul.tabs a').each(function(){
				$(this).parent().parent().removeClass('buttonActive').addClass('button');
			});
			// hide all tags
			$('div.tag-content').each(function(){
				$(this).hide();
			});
			// set active tab class
			a.parent().parent().removeClass('button').addClass('buttonActive');
			// show the clicked tag group
			$('div#tag-helper-' + a.attr('rel')).show();
			return false;
		});
	});
	// tag links
	$('div.tag-content a').each(function(){
		$(this).click(function(){
			var a = $(this);
			var t = a.html().toLowerCase();
			var v = $('#post_tags').val().toLowerCase();
			if (v.indexOf(  (t + ',') ) == -1) {
				$('#post_tags').val( ( v == '' ? t : ( v + ', ' + t ) ) );
			}
			return false;			
		});
	});
	
	// init checkboxes
	disable_category_checkboxes();
});

// disable category checkboxes
function disable_category_checkboxes() {
	var tot = 0;
	$('input.post-category').each(function(){
		if ($(this)[0].checked) tot++;			 
	});
	if (tot >= max_categories) {
		$('input.post-category').each(function(){
			if ( ! $(this)[0].checked ) {
				$(this)[0].disabled = true;
			}
		});
	}
}