$(document).ready(function()
{
	var ie = $.browser.msie;
	var swap_bg_img = typeof custom_checkboxes_use_image_swap == 'undefined' ? false : custom_checkboxes_use_image_swap; //set in the page template

	$('span.checkbox').live('click', function()
	{
		var input = $(this).siblings(':checkbox.styled');

		if ($(input).length == 0)
		{
			var name = $(this).attr('id').split('span_')[1];
			input = ":checkbox[name='"+name+"']";
		}

		if ($(input).attr('checked'))
			uncheck(this, $(input)[0]);
		else
			check(this, $(input)[0]);
	});

	$.each($(':checkbox'), function(i, box)
	{

		var span = '#span_'+$(this).attr('id');

		if ($(span).length == 0)
		{
			if ($(this).attr('id') == '')
			{
				var name = $(this).attr('name');
				$(this).attr('id', name)
			}
			if (!$(this).hasClass('nocustom')) {
				if($(this).prev().attr('id') != 'span_'+$(this).attr('id')) 
					span = create_span(this);
			}
		}

		if ($(this).is(':checked'))
		{
			check(span, this);
		}
	});


	function create_span(checkbox)
	{
		var id = $(checkbox).attr('id');
		var span = $(document.createElement('span'))
			.attr('id', 'span_'+id)
			.attr('title', $(checkbox).attr('title'))
			.addClass('checkbox')
			.addClass('dynamic_span')
			.css('background-position', '0 0')
			.css('position', 'relative')
			.css('top', '0');

		$(checkbox).before($(span));
		return $(span);
	}
	function check(span, input)
	{
		if (swap_bg_img)
		{
			$(span).css('background-image', $(span).css('background-image').replace("_unchecked", "_checked"));
		}
		else
		{
			$(span)
				.css('background-position', '0 -65pt')
				.css('top', '-2pt');
		}

		if (ie || $(span).hasClass('dynamic_span'))
			$(input).attr('checked', true);
		else
			$(input).checked = true;
	}

	function uncheck(span, input)
	{
		if (swap_bg_img)
		{
			$(span).css('background-image', $(span).css('background-image').replace("_checked", "_unchecked"));
		}
		else
		{
			$(span)
				.css('background-position', '0 0')
				.css('top', '0');
		}

		if (ie || $(span).hasClass('dynamic_span'))
			$(input).attr('checked', false);
		else
			$(input).checked = false;
	}
});
