/* -*- mode: c; tab-width: 2; c-tab-always-indent: t; c-basic-offset: 2; comment-column: 0 -*- */
if (!('Boone' in window))
	throw 'application.js is required';

(function() {
	var $form = null;
	function show_new_count_msg(new_msg) {
		var $msgs = $form.find('div.message');
		if ($msgs.length == 0)
			$j(new_msg).fadeIn('slow').slideDown('slow').insertAfter($('certificate-type'));
		else {
			var $msg = $j(new_msg);
			if ($j.trim($msg.text()) == $j.trim($msgs.text()))
				return;
			$msgs.fadeOut(function(){
				if (new_msg)
					$msg.fadeIn('slow').slideDown('slow').insertAfter($('certificate-type'));
				$msgs.remove();
			});
		}
	}

	function has_selected_checkboxes(name){
		for (var els = $form[0][name], l = els.length; l--; )
			if (els[l].checked)
				return true;
		return false;
	}

	function show_required_msg() {
		show_new_count_msg('<div class="errorMessage message"><p><strong>Shape, Color, Clarity, and Certificate fields are required. Please check at least one color, one shape, one clarity, and one certificate type.</strong></p></div>');
	}

	var required_checkboxes = ['shape[]', 'color[]', 'clarity[]', 'lab[]'];
	function validate() {
		for (var l = required_checkboxes.length; l--; )
			if (!has_selected_checkboxes(required_checkboxes[l])) {
				show_required_msg();
				return false;
			}
		return true;
	}

	function update_selection_count(){
		if (update_selection_count.TID != null)
			clearTimeout(update_selection_count.TID);
		if (!validate())
			return;

		update_selection_count.TID = setTimeout(function(){
			var ser = $form.serialize();
			if (ser in update_selection_count.cache) {
				show_new_count_msg(update_selection_count.cache[ser]);
				update_selection_count.TID = null;
			}
			else {
				$j.get($form.attr('action'), ser, function(r){
					update_selection_count.cache[ser] = r;
					show_new_count_msg(r);
					update_selection_count.TID = null;
				});
			}
		}, 500);
	}
	update_selection_count.cache = {};

	Boone.Page.init = function(){
		$form = $j('#search');
		if ($form.length == 0)
			return $form = null;

		var els = $form[0].elements;
		var el, l = els.length;
		while (l--) {
			var el = els[l];
			if (el.type == 'checkbox')
				el.onclick = update_selection_count;
			else
				el.onchange = update_selection_count;
		}
		$form.bind('submit', validate);
	};
})();
