var colour_by_group_by = window.colour_by_group_by || {};
var GROUPABLE_COLOURABLE_DIMENSIONS = ['country','agerange','gender','intensity','product','question'];
/* DIMENSION_LABELS is now defined in queryForm.html so that Django
   can do translations on the string
   That had issues with translated text with quotes in, so now use this
   DIV related way which will hopefully be more robust */
var DIMENSION_LABELS = {
    country: $("#country_text").text(),
    agerange:  $("#agerange_text").text(),
    gender: $("#gender_text").text(),
    intensity: $("#intensity_text").text(),
    product: $("#product_text").text(),
    question: $("#question_text").text()
}


var msg = function(msg){
	if(typeof(console) != 'undefined'){
		console.log(msg);
	}
}

/*
GROUP BY AND COLOUR BY SELECTS
When these options are hidden (when the form is first loaded), they should be
auto-populated by JS.  And when they are visible JS should validate them and 
restrict which options are available.  Auto-population and validation should
follow these rules:
*	Each dimension (country, age, gender, etc) can only be used once within the
	group-by and colour-by options
*	If a dimension has more than 1 option chosen (e.g. you've chosen 2 age ranges)
	then it MUST be included in the group-by/colour-by options
*	If a dimension has only got 1 option chosen (e..g you only chose 1 age range)
	then that dimension can NOT be used in the group-by/colour-by options
*	The dimensions that haave got the most items chosen are better suited to being
	used for colour-by, rather than group-by.
*/



colour_by_group_by.new_block = function(name, dimension, as_li){
	//create a label and a checkbox, to be used as a draggable block, return it as a jQuery object
	//NB: it is not set as active or inactive when it is returned, this must be done afterwards
	//name is the value of the name attribute on the <input>,
	//value is the value of the value attribute
	var label = DIMENSION_LABELS[dimension];
	var block_string = '<input type="checkbox" name="'+name+'" id="gbcb_'+dimension+'" value="'+dimension+'" disabled="disabled"    />';
	block_string += '<label for="gbcb_'+ dimension +'" >'+label+'</label>';
	//wrapping 2 elements in an <li> is tricky, as jQuery wraps each one separately, hence
	if(as_li){
		return $('<li>'+block_string+'</li>');
	}
	return $(block_string);
}


colour_by_group_by.get_list_with_least_items = function(){
	//get and return (as a jQuery object) the colour-by or group-by list which has the least items in it
	//as well as the value of the name attribute that should be used for <input>s within that list
	var group_by_list = $("#group_by");
	var colour_by_list = $("#colour_by");
	if(group_by_list.children().length < colour_by_list.children().length){
		return [group_by_list, 'grouped'];
	}
	return [colour_by_list, 'colourcoded'];
}


colour_by_group_by.activate_block = function(dimension_name){
	var input = $(".colour_by_group_by input[value='"+ dimension_name +"']").eq(0);
	var label = input.siblings("label");
	input.removeClass('inactive').addClass('active').attr('checked', true);
	label.removeClass('inactive').addClass('active');
	label.closest('li').removeClass('inactive').addClass('active');
}


colour_by_group_by.deactivate_block = function(dimension_name){
	var input = $(".colour_by_group_by input[value='"+ dimension_name +"']").eq(0);
	var label = input.siblings("label");
	input.removeClass('active').addClass('inactive').removeAttr('checked');
	label.removeClass('active').addClass('inactive');
	label.closest('li').removeClass('active').addClass('inactive');
}

colour_by_group_by.update_then_text = function(){
	//for each <li> element which is NOT the first one, add "then:" text next to it
	msg('updating then text');
	$("#colour_by li, #group_by li").each(
		function(){
			$(this).find(".then").remove();
		}
	);
	$("#colour_by li:not(:first), #group_by li:not(:first)").each(
		function(){
			var jq_this = $(this);
			if(!jq_this.is("first")){
				jq_this.prepend('<span class="then">then:</span>');
			}
		}
	);
}


colour_by_group_by.init = function(){
	
	//when the page loads, the group-by and order-by items that are needed (for the current dataset) should
	//already be selelcted, so initially we need to turn each select into a draggable block element, and
	//then make the ones that DO have a value selected and make them active, and then make sure that there
	//is one block for each dimension (age range, gender, country, etc), and that the ones that aren't in use
	//(or that wouldn't be useful) are styled to be not active
	
	
	if($("#formbottom").hasClass('hide')){ //if the bottom part of the form is hidden, because the user hasn't submitted anything yet
		return; //don't do anything.  Grouping/colouring will be done automatically server-side
	}
	
	//remove 'then by:' text, as we don't need it for the JS version
	$(".then").remove();
	
	$(".colour_by_group_by select").each(
		function(){
			var jq_this = $(this);
			var dimension = jq_this.val();
			var name = jq_this.attr('name');
			if(dimension){ //if this item is in use
				var li = jq_this.closest('li');
				jq_this.remove();
				var block = colour_by_group_by.new_block(name, dimension, false);
				li.append(block);
				colour_by_group_by.activate_block(dimension);
			}
		}
	);
	
	
	//now get rid of any <select>s which are not in use (i.e. no value set)
	$(".colour_by_group_by select").each(
		function(){
			var jq_this = $(this);
			if(jq_this.val() == ''){
				jq_this.closest('li').remove();
			}
		}
	);
	//now we need to create a draggable block for every dimension that is NOT being used, but that could be
	//we create them as un-checked, so they can still be dragged around, but don't get submitted
	for(index in GROUPABLE_COLOURABLE_DIMENSIONS){
		var dimension = GROUPABLE_COLOURABLE_DIMENSIONS[index];
		if($(".colour_by_group_by input[value='"+dimension+"']").length == 0){ //no block created for this dimension yet
			//we'll add the block to the list that has the fewest items in it
			var list_and_name = colour_by_group_by.get_list_with_least_items();
			var list_to_append_to = list_and_name[0];
			var name_attribute_value = list_and_name[1];
			var block = colour_by_group_by.new_block(name_attribute_value, dimension, true);
			list_to_append_to.append(block);
			colour_by_group_by.deactivate_block(dimension);
		}
	}
	
	
	//set on-change function for all options, so that the active/non-active group-by and colour-by blocks can be set
	$("#formtop input").each(
		function(){
			$(this).change(
				function(){
					var jq_this = $(this);
					var name = jq_this.attr('name');
					if($("input[name='"+name+"']:checked").length > 1){ //more than one option in this dimension is selected
						colour_by_group_by.activate_block(name);
					}else{
						colour_by_group_by.deactivate_block(name);
					}
				}
			);
		}
	);
	
	
	//make the items draggable betweent the two lists
	$("#colour_by, #group_by").sortable({
		cursor: 'crosshair',
		connectWith: '.colour_by_group_by',
		update: function(event, ui){
			//update the name attribute of the moved <input>  to 'colourcoded' or 'grouped' depending on which list it is now in
			var moved_input = ui.item.find("input").eq(0);
			var containing_list = ui.item.closest('ul');
			if(containing_list.attr('id') == 'colour_by'){
				moved_input.attr('name', 'colourcoded');
			}else{
				moved_input.attr('name', 'grouped');
			}
			colour_by_group_by.update_then_text();
		}
	}).disableSelection();
	
	
	//when the form is submitted, un-disable the checkboxes so that their values get submitted.  readonly="readonly" doesn't work
	$("#queryform").submit(
		function(){
			$(".colour_by_group_by input").each(
				function(){
					$(this).removeAttr('disabled');
				}
			);
		}
	);
	
	colour_by_group_by.update_then_text();
	
	//TODO: Auto button
	
	//TODO: Submit inactive group/colour by options as a separate form value so they can be sticky even when not in use

}
















colour_by_group_by.init();












