$(window).on("load", function() {
	$('#svg_woman, #svg_man').each(function() {
		var svg = $(this.contentDocument).find('svg').attr('id', $(this).attr('id')+'_svg');
		svg.find('g:has(title)[id*=UBERON], path:has(title)[id*=UBERON]').each(function() {
			var t = $(this).find('title:first');
			$(this).attr('title', t.text().charAt(0).toUpperCase() + t.text().slice(1));
			t.remove();
		});
		svg.prependTo($(this).parent());
		$(this).hide();
	});
	
	
	$('.woman')
		.on('toggle_woman', function(e, type) {
			var $svg = $(this).find('svg');
			$('.uberon').each(function() {
				var uberon = $(this).attr('uberon');
				if (!uberon) return;
				var nx = $(this).attr('nx')*1;
				var color = $(this).attr('color');
				uberon = uberon.split(',');
				for (var i=0; i<uberon.length; i++) {
					var $g = $svg.find('.'+uberon).css({'fill':'none', 'opacity':'1'});
					//var $g = $svg.find('[inkscape\\:label="'+uberon[i]+'"]').css({'fill':'none', 'opacity':'1'});
					if (type == 'expression') {
						//var opacity = nx/50;
						var opacity = nx>0? Math.log(nx)/Math.log(6520) : 0;
						$g.css({'fill':'#d90000', 'opacity':opacity});
					}
					else if (type == 'detection') {
						if (nx > 1) $g.css('fill', color);
					}
					else if (type == 'all') {
						$g.css('fill', color);
					}
				}
			});
		})
		.on("click", function(e) {
			var $html = $('<div class="womanContainer" style="background-color:#fff; text-align:center; padding:10px;"></div>').append($('.womanContainer .slideToggle').clone(true), '<br>', $('.womanContainer .woman').clone(true).off('click').css({'width':'400px', 'display':'inline-block'}));
			var options = {
				opacity: 0.9,
				open: true,
				title: '<a href="https://data.humancellatlas.org/analyze/visualization/anatomogram" target="_blank">Anatomogram</a> of '+$('.gene_name').text()+' expression in human tissue. See the <a href="/learn/dictionary">histological dictionary</a> for more tissue information.',
				html: $html,
			};
			$.colorbox(options);
			e.preventDefault();
		})
		.trigger('toggle_woman', 'expression');
		
	$('.tissue_link, .tissue_group, .multiplex_link').on("mouseover", function(e) {
		var uberon = $(this).attr('uberon');
		if ($(e.target).hasClass('tissue_group')) {
			uberon = $(this).find('.tissue_link').map(function() {
				return $(this).attr('uberon');
			}).get().join(',');
		}
		if (!uberon) return;
		uberon = uberon.split(',');
		var color = $(this).closest('.tissue_group').attr('color') ?? $(this).attr('color');
		for (var i=0; i<uberon.length; i++) {
			var $g = $('.woman_center, .man_center').find('.'+uberon[i]);
			if ($g.prop('tagName') == 'use') {
				$g = $('.woman_center, .man_center').find($g.attr('xlink:href'));
			}
			$g.css({'fill':color}).addClass('uberon_color').children().css('fill', '');
		}
	}).on("mouseout", function() {
		var $g = $('.woman_center, .man_center').find('.uberon_color').css({'fill':'none'});
	});
});



$.fn.multiplexPanelPlot = function(data, inSettings) {
	var plot = {};
	var extraDefaults = {
		yLabels: '',
		yTickFormat: '',
		minY: 0,
		dimension: {w: 730, h: 400},
		padding: {t: 20, r: 20, b: 120, l: 30},
		bgColor: '',
		barWidth: 11,
		xLabelsHide: false,
		extendedTooltip: false,
		radius: 1,
	};
	var settings = addDefaultPlotSettings(inSettings, extraDefaults);
	plot.settings = settings;

	// Inner dimension
	var width = plot.width = settings.dimension.w - settings.padding.l - settings.padding.r; // inner width
	var height = plot.height = settings.dimension.h - settings.padding.t - settings.padding.b; // inner height

	var xScale = plot.x = d3.scaleBand()
			.range([0, width])
			.domain(data.map(function(d) { return d.label; }));
	var xAxis = d3.axisBottom(xScale)
			.tickSizeOuter(0)
			.tickSize(0);

	if (settings.xLabelsHide) {
		xAxis.tickFormat('');
	}

	var yScale;
	var yMin, yMax, yAxis;
	if (settings.yLabels) {
		yMin = plot.yMin = 0;
		yMax = plot.yMax = d3.max(d3.keys(settings.yLabels));
		yScale = plot.y = d3.scaleLinear()
				.range([height, 0])
				.domain([yMin, yMax]);
		yAxis = d3.axisLeft(yScale)
				.tickFormat(function(d) { return settings.yLabels[d]; })
				.tickValues(d3.keys(settings.yLabels));
	}
	else {
		yMin = plot.yMin = 0.3;
		yMax = plot.yMax = Math.max(d3.max(data, function(d) { return parseFloat(d.value); }), settings.minY);
		yScale = plot.y = d3.scaleLinear()
				.range([height, 0])
				.domain([yMin, yMax])
				.nice(5);
		yAxis = d3.axisLeft(yScale)
				.ticks(5);
		if (settings.yTickSize != undefined) {
			yAxis.tickSize(settings.yTickSize);
		}
		if (settings.yTickFormat) {
			yAxis.tickFormat(d3.format(settings.yTickFormat));
		}
	}
	var vis = plot.vis = d3.select($(this).get(0))
			.append("svg")
			.attr("class", "barchart")
			.attr("width", width + settings.padding.l + settings.padding.r)
			.attr("height", height + settings.padding.t + settings.padding.b)
			.append("g")
			.attr("transform", "translate(" + settings.padding.l + "," + settings.padding.t + ")")
			.attr("width", width)
			.attr("height", height);

	$(this).on('click', '[url]', function() {
		document.location.href = $(this).attr('url');
	});

	if (settings.bgColor) {
		vis.append("rect")
				.attr("class", "chart_field")
				.attr("width", width)
				.attr("height", height+4)
				.attr("transform", "translate(0,-4)")
				.style("fill", settings.bgColor);
	}

	var bar_g = vis.selectAll(".bar_g")
			.data(data)
			.enter()
			.append("g")
			.attr("class", function(d) { return d.class? "bar_g "+d.class : "bar_g"; })
			.attr("transform", function(d) { return 'translate('+xScale(d.label)+', 0)'; })
			.attr("title", function(d) { return d.tooltip; });

	var link = bar_g.append("a")
			.each(function(d) { if (d.url) d3.select(this).attr("xlink:href", d.url); });

	if (settings.extendedTooltip) {
		var bar_transp = link.append("rect")
				.attr("class","bartrans")
				.attr("y", 0)
				.attr("x", function(d) { return xScale.bandwidth()/2 - settings.barWidth/2 ; })
				.attr("width", settings.barWidth)
				.attr("height", height)
				.style("fill", "transparent");
	}
	var bar_line = link.append("line")
			.attr("class","bar")
			.style("stroke", function(d) { return d.color; })
			.style("stroke-width", 2)
			.attr("y1", function(d) { return yScale(d.value); })
			.attr("x1", function(d) { return xScale.bandwidth()/2 ; })
			.attr("y2", function(d) { return yScale(0); })
			.attr("x2", function(d) { return xScale.bandwidth()/2 ; })

	var bar_hex = link.append("g")
			.attr("class", "hex")
			.attr("transform", function (d) { return "translate("+(xScale.bandwidth()/2)+","+yScale(d.value)+") scale("+d.radius*settings.radius+")"; })
			.append('polygon')
			.attr('points', "20,11.5 0,23 -20,11.5 -20,-11.5 0,-23 20,-11.5")
			//.style("stroke-width","2")
			//.style("stroke","black")
			.style("fill", function(d) { return d.color; });

	if (settings.valueLabels) {
		link.append("text")
				.attr("class", "valueLabel")
				.style("text-anchor", "middle")
				.attr("x", xScale.bandwidth()/2)
				.attr("y", function(d) { return yScale(d.value)+4; })
				.text(function(d) { return d.na? '' : d.value; });
	}

	vis.append("g")
			.attr("class", "x axis")
			.attr("transform", "translate(0," + height + ")")
			.call(xAxis)
			.selectAll(".tick text")
			.attr("class", "barchartlabel")
			.attr("y", 0)
			.attr("x", -9)
			.attr("transform", "rotate(-55)")
			.style("text-anchor", "end")
			.each(function(d, i) {
				if (data[i].tooltip) {
					d3.select(this).attr('title', data[i].tooltip);
				}
				if (data[i].url) {
					d3.select(this).attr('url', data[i].url).style('cursor', 'pointer');
				}
			});

	$(this).on('click', '[url]', function() {
		document.location.href = $(this).attr('url');
	});

	// x axis label
	vis.selectAll(".x.axis")
			.append("text")
			.attr("y", 20)
			.attr("x", width/2)
			.text(settings.xAxisLabel);
	// y axis label
	vis.append("g")
			.attr("class", "y axis")
			.call(yAxis)
			.append("text")
			.attr("y", -8)
			.style("text-anchor", "middle")
			.text(settings.yAxisLabel);

	vis.selectAll(".y .tick text")
			.call(wrap, settings.padding.l);

	// Legend
	if (settings.legend !== '') {
		var legend = vis.selectAll(".legend")
				.data(d3.map(data, function(d){return d.legend;}).values())
				.enter().append("g")
				.attr("class", "legend")
				.attr("transform", function(d, i) { return "translate(0," + i * (settings.barWidth+2) + ")"; });

		legend.append("rect")
				.attr("x", settings.legend.x)
				.attr("y", settings.legend.y)
				.attr("width", settings.barWidth)
				.attr("height", settings.barWidth)
				.style("fill", function(d, i) {return d.color; });

		legend.append("text")
				.attr("x", settings.legend.x+settings.barWidth+2)
				.attr("y", settings.legend.y+settings.barWidth/2)
				.attr("dy", ".35em")
				.style("text-anchor", settings.legend.txtAnchor)
				.text(function(d) { return d.legend; });

	}

	/*$(this).on('sort', function(e, order) {
		var x0 = xScale.domain(
				data.sort(
						order==='pos'? function(a, b) { return a.pos - b.pos; }
								:order==='value'? function(a, b) { return a.na? 1000 : b.na? -1000 : b.value - a.value; }
										:order==='real_value'? function(a, b) { return a.na? 1000 : b.na? -1000 : b.real_value - a.real_value; }
												:order==='label'? function(a, b) { return a.label.localeCompare(b.label); }
														:order==='origin'? function(a, b) { return a.origin.localeCompare(b.origin); }
																:order==='category'? function(a, b) { return a.category.localeCompare(b.category); }
																		: function(a,b) { return 0; }
				)
						.map(function(d) { return d.label; })
		)
				.copy();
		vis.selectAll(".bar_g").sort(function(a, b) { return x0(a.value) - x0(b.value); });
		vis.selectAll(".x.axis.tick").sort(function(a, b) { return x0(a.value) - x0(b.value); });

		var transition = vis.transition().duration(100);
		transition.selectAll(".bar_g")
				.attr("transform", function(d) { return 'translate('+x0(d.label)+', 0)'; });
		transition.select(".x.axis")
				.call(xAxis)
				.selectAll(".tick text")
				.style("text-anchor", "end")
				.attr("y", 0)
				.attr("x", -9);
	});*/

	function wrap(text, width) {
		text.each(function() {
			var text = d3.select(this),
					words = text.text().split(/\s+/).reverse(),
					word,
					line = [],
					lineNumber = 0,
					lineHeight = 1.1, // ems
					y = text.attr("y"),
					x = text.attr("x"),
					dy = parseFloat(text.attr("dy")),
					tspan = text.text(null).append("tspan").attr("x", x).attr("y", y).attr("dy", dy + "em");
			while (word = words.pop()) {
				line.push(word);
				tspan.text(line.join(" "));
				if (tspan.node().getComputedTextLength() > width) {
					line.pop();
					tspan.text(line.join(" "));
					line = [word];
					tspan = text.append("tspan").attr("x", x).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
				}
			}
		});
	}
	return plot;
};