ctr = 0;
submitId = -1;

function delayedSubmit(id)
{
	if(id == undefined)
	{
		submitId = ctr++;
		window.setTimeout("delayedSubmit(" + submitId + ")", 1250)
	}
	else
	{
		if(id == submitId)
			$('filterSubmitter').click();
	}
}

function filterChanged(type, checkbox, recurse)
{
	if(recurse == undefined)
		recurse = true;
	checkbox = $(checkbox);
	var key = checkbox.value;
	var checked = checkbox.checked;
	
	var suffix = '';
	var arry = type.split('_', 2);
	type = arry[0];
	if(arry.length > 1)
		suffix = '_' + arry[1];
	
	var exclude = false;
	if(checkbox.hasClassName('location'))
		exclude = ($('filter_exclude').value == '1') ? true : false;
		
	obj = $('filter_' + type);
	ar = obj.value.split(',');
	idx = ar.indexOf(key);
	if(exclude)
	{
		if(!checked)
		{
			if(idx == -1)
				ar.push(key);
		}
		else
			ar = ar.without(key);
	}
	else
	{
		if(checked)
		{
			if(idx == -1)
				ar.push(key);
		}
		else
			ar = ar.without(key);
	}
	
	obj.value = ar.join(',');
	
	if(recurse)
	{
		if(type.substr(0,3) == 'sub')
		{
			// this is a subset of a parent
			if(checked)
			{
				// this sub-item has been checked. make sure the parent is also checked.
				par = $(type.substr(3)+suffix);
				if(par)
				{
					par.checked = true;
					filterChanged(type.substr(3), par, false);
				}
			}
		}
		else
		{
			sub = $("sub"+checkbox.id);
			if(sub)
			{
				$$('#'+sub.id+' input.checkbox').each(function(obj){
					obj.checked = checkbox.checked;
					filterChanged(sub.id, obj, false);
				});
			}
		}
	}
	
	delayedSubmit();
	updateSummary(type+suffix);
}

function updateSummary(type, max)
{
	elm = $(type+'_summary');
	if(elm)
	{
		var summary = [];
		arry = $$('#'+type+' li input.checkbox');
		$$('#'+type+' li input.checkbox').each(function(obj){
			if(obj.checked)
			{
				var lbl = obj.nextSiblings()[0];
				var txt = lbl.innerHTML;
				var pos = txt.lastIndexOf(" (");
				txt = "<b>" + txt.substring(0, pos) + "</b>" + txt.substr(pos);
				if(lbl)
					summary.push(txt);
			}
		});
		summary = summary.sort().join(', ');
		if(summary.length == 0)
			summary = "No filters selected";
		if(max != undefined && max < summary.length)
		{
			$(type+'_summary').title = summary;
			summary = summary.substr(0,max) + '<b>...</b> <span class="blue">(more)</span>';
		}
		summary = '[ <span class="red bold" style="border-bottom:1px dotted;">edit</span> ] ' + summary;
		elm.innerHTML = summary;
	}
}

function filterOnly(type, key, group, suffix)
{
	$$('#searchFilterContainer input.checkbox.'+group).each(function(obj){obj.checked = false;});
	$$('#filter_form .'+group).each(function(obj){obj.value = '';});
	$('filter_exclude').value = '0';
	checkbox = $(type + '_' + key);
	checkbox.checked = true;
	filterChanged(type+suffix, checkbox);
	//$('filter_' + type).value = ',' + key;
	delayedSubmit();
	init_summary(true);
}
