// TODO implement _t()
var i18n = i18n || {};

;(function($) {
	
	$.fn.DemandMap_collapsible = function() { 
		return this.each(function(){
			var $this = $(this);
			var container = this;
			
			// set up collapsible boxes
			// if any children(checkbox) of 'li ul' is/are selected then collapse 
			$('li ul', container).each(function(){			
				if (!hasSelectedChildren(this)) $(this).hide();
			});
			
			$('li.category', container).each(function(el) {
				if($('li.subcategory', this).length > 0) {
					expandOrCollapse = "";
					if(hasSelectedChildren($(this).children('ul'))) {
						
						expandOrCollapse = $.i18n._t('COLLAPSE');
					} 
					else {
						expandOrCollapse = $.i18n._t('EXPAND');
					}
					
					if (expandOrCollapse != '') $(this).children('label').after(
						$.sprintf('<small class="toggle">(<a href="#">%s</a>)</small>',
							expandOrCollapse
						)
					);
				}
			});
			
			$('li.category .toggle', container).livequery('click', function(e) {
				$(this).siblings('ul').toggle();
				$(this).siblings('ul').is(':visible') ? $('a', this).html($.i18n._t('COLLAPSE')) : $('a', this).html($.i18n._t('EXPAND'));
				return false; 
			});
			
			/**
			 * Return true if any of children of list are selected, otherwise false
			 */
			function hasSelectedChildren(list) {
				var skip = false;
				
				$(list).children().each(function(){
					supplierCheckbox = $('#' + $(this).attr('id') + ' input');
		
					if (supplierCheckbox.attr('checked')) {
						skip = true;
						return;
					}
				});
				
				if (skip) return true;
			}

		});
	}
})(jQuery);