var ccb = window.ccb || {};

/* Just the same as keys of DIMENSION_LABELS? */
REQUIRED_FIELD_NAMES = ['country', 'agerange', 'gender', 'intensity', 'vertical', 'question']
ALERT_LENGTH = 30;

ccb.pageStartTime = (new Date).getTime();

ccb.msg = function(msg){
	if (window.console) {
		timeDiff = (new Date).getTime() - ccb.pageStartTime
		if (typeof(msg) == "string") {
			console.log(timeDiff + "ms | " + msg)
		} else {
			console.log(msg)
		}
	}
}



ccb.toggle_chart_options = function(){
    // IE(8) doesn't like objects with the same name as DOM elements
	formbottom_obj = $("#formbottom");
	if(formbottom_obj.hasClass('showing')){
		formbottom_obj.removeClass('showing').hide('fast');
		$("#formbottom_show").show();
		$("#formbottom_hide").hide();
		$("#show_opts").val(''); //set input value so that the options are NOT showing when the page is reloaded
	}else{
		formbottom_obj.addClass('showing').slideDown('slow');
		$("#formbottom_show").hide();
		$("#formbottom_hide").show();
		$("#show_opts").val('1'); //set input value so that the options are showing when the page is reloaded
	}
	return false;
}


ccb.redraw_fake_selects = function(){
	$(".fake_select .select_bar").each(
		function(){
		nested_checkbox_lists.update_count($(this));
		}
	);
}


ccb.toggle_formtop = function(){
	formtop_obj = $("#formtop");
	if(formtop_obj.hasClass('showing')){
		formtop_obj.removeClass('showing').hide('fast');
		$("#formtop_show").show();
		$("#formtop_hide").hide();
	}else{
		//once the top form is displayed we'll need to get the fake selects to re-draw their summary
		//text, as it can't do it properly when the containing div is display:none;
		formtop_obj.addClass('showing').slideDown('slow', ccb.redraw_fake_selects);
		$("#formtop_show").hide();
		$("#formtop_hide").show();
	}
	return false;
}


/* No idea why this is commented out or whether it should ever come back...
$(".fake_select div:first").each(
	function(){
	nested_checkbox_lists.update_count($(this));
	}
);
*/

ccb.video = {
    yt_base_url: "http://www.youtube.com/embed/wfHyHb_JR-Y?autoplay=1", 

    init: function() {
	$("#yt-video-thumbnail").hover(
	    function () { $(this).attr("src", "/static/img/ccb_video_preview_hover.png"); },
	    function () { $(this).attr("src", "/static/img/ccb_video_preview.png"); }
	);
	$("#yt-video-thumbnail").click( function(event) {
	    event.preventDefault();
	    var video_url = ccb.video.yt_base_url;
	    var language = $("#lang").val();
	    if (language != "en-gb") {
		video_url += "&hl=" + language;
	    }
	    var video_window = window.open(video_url,
					   'video', 
					   'height=500,width=800,scrollbars=yes,status=no,addressbar=no,titlebar=no');
	    if (window.focus) {
		video_window.focus();
	    }
	    return false;
	});
    }
}


ccb.init = function(){
	
	
	//auto-submit 'choose language' form on-change
	$("#lang").change(
	    function(){
		$("#language_form").submit();
	    }
	);
	
	//top form show/hiding
	$("#formtop_show").click(ccb.toggle_formtop);
	$("#formtop_hide").click(ccb.toggle_formtop);
	
	//bottom form show/hiding
	$("#formbottom_show").click(ccb.toggle_chart_options);
	$("#formbottom_hide").click(ccb.toggle_chart_options);
	
	$("#resetbutton").click( function(){ $("#to_reset").val("1"); return true; });

	
	//TODO: Not sure if this is useful or just confusing to the user
	//remove stale error messages when fields are changed
	for(i in REQUIRED_FIELD_NAMES){
		field_name = REQUIRED_FIELD_NAMES[i];
		$("*[name='"+ field_name +"']").each(
			function(){
				$(this).change(
					function(){
						if($(this).val() != ''){ //field is no longer blank
							$(".error[rel='"+ $(this).attr('name') +"']").remove();
						}
					}
				);
			}
		);
	}
	
	
	//add form validation
	$("#queryform").submit(
		function(){
                        reset =  $("#to_reset").val();
                        if(reset == 1)
                        {
                            return true;
                        }
			return_val = true;
			inputs = $("#queryform").find("input[checked!='']");
			field_name = "too_many_checked"; 

			if($('#too_many_checked').length > 0 && inputs.length > ALERT_LENGTH)
			{
				$('#too_many_checked').click();
				$('#too_many_checked').remove();
				return_val = false;
			}
		        sendEventsToGA.init();
			for(i in REQUIRED_FIELD_NAMES){
				field_name = REQUIRED_FIELD_NAMES[i];
				if($("select[name='"+field_name+"'][value!=''],input[name='"+field_name+"'][checked!='']").length == 0){ //no selection has been made
					return_val = false;
					if($(".error[rel='"+ field_name +"']").length == 0){ //and if there is NOT already an error message
					    /* TODO: replace this with some class manipulation to make a span visible, that would also remove the
                                               need for the please_select_at_least_one_text DIV */
					    error = $('<div class="error" rel="'+ field_name +'">' + $("#please_select_at_least_one_text").text() + '</div>');
					    error.insertAfter($("*[name='"+field_name+"']:first").closest('fieldset').children('legend'));
					}
				} else {
				    $("select[name='"+field_name+"'][value!=''],input[name='"+field_name+"'][checked!='']").each(function() {
					sendEventsToGA.addEvent(field_name, this.value);
				    });

				}
			}
		//It is possible to make the form invalid by not selecting anything in one of the top options, then collapse the top part
		//of the form, and then try to submit the form using the submit button in the bottom part of the form.  So we need to reveal the
		//top part of the form to show the error messages
		if(!return_val){
			formtop_obj = $("#formtop");
			if(formtop_obj.hasClass('js_hide') && !formtop_obj.hasClass('showing')){
				ccb.toggle_formtop(); //show the top part of the form
				y_pos = formtop_obj.attr('offsetTop'); //and scroll to it
				window.scrollTo(0,y_pos);
			}
		}

	            sendEventsToGA.send();

		return return_val;
		}
	);
	
	
	function select_function(){
		//function to select all text in <input> when it's focussed/clicked
		this.select();
		return false;
	}
	
	
	//turn page and chart download links into <input>s which select all text on focus
	$("#link_page, #link_chart").each(
		function(){
			jq_this = $(this);
			href = jq_this.attr('href');
			text = jq_this.text();
			div = jq_this.parent();
			id = jq_this.attr('id');
			jq_this.remove(); //remove the link
			//put the input and label in its place
			label = $('<label for ="'+ id +'">'+ text +' </label>');
			input = $('<input id="'+ id +'" value="'+ href +'" />');
			label.appendTo(div);
			input.appendTo(div);
			//set onfocus and onclick functions to select all text
			input.focus(select_function).click(select_function);
		}
	);
	
	//make help links into fancybox popups
	if ($.browser.msie) {
	    $(".help").click(function(event) {
		    event.preventDefault();
		    href=$(this).attr('href'); 
		    newwindow=window.open(href, 'help', 'height=400,width=800,scrollbars=yes,status=no,titlebar=no');
		    if (window.focus) {
			newwindow.focus();
		    }
		    return False;
		});
	} else {
	    $(".help").fancybox();

	}


	//make alert links into fancybox popups
	if ($.browser.msie) {
	    $(".alert").click(function(event) {
		    event.preventDefault();
		    href=$(this).attr('href'); 
		    newwindow=window.open(href, 'alert', 'height=400,width=800,scrollbars=yes,status=no,titlebar=no');
		    if (window.focus) {
			newwindow.focus();
		    }
		    return False;
		});
	} else {
	    $(".alert").fancybox();

	}



	$("#view_unknowns").click(function(event) {
		jq_this=$(this);
		datanode=$("#unknown_data");
		if (datanode.hasClass("js_hide")) {
		    jq_this.text( $("#hide_details_text").text() );
		} else {
		    jq_this.text( $("#show_details_text").text() );
		}
		datanode.toggleClass('js_hide');

	    });

    ccb.video.init();

}

    ccb.init();


