
var wd = $('#plotarea_1').width();
var ht = $('#plotarea_1').height();

// set the dimensions and margins of the graph
var margin = {top: 10, right: 80, bottom: 30, left: 30};

var defaultbuckets = 50;
try
{
	defaultbuckets = parseInt($('#resolution').val());
}
catch(e)
{
	
}
if ((isNaN(defaultbuckets)) || (defaultbuckets == 0)) defaultbuckets = 50;
var buckets = defaultbuckets;
try
{
	buckets = parseInt(Options['resolution']);
}
catch(e)
{
	buckets = defaultbuckets;
}
if (isNaN(buckets)) buckets = defaultbuckets;

if (buckets > 100) margin.bottom = 10;

var width = wd - margin.left - margin.right;
var height = ht - margin.top - margin.bottom;
	
var svg = d3.select("#plotarea_" + 1)
  .append("svg")		
	.attr("viewBox", "0 0 " + wd + " " + ht)
	.attr("preserveAspectRatio","xMidYMid meet")
	.attr("width","100%")
	.attr("height","100%")
	
//Append a defs (for definition) element to your SVG
var defs = svg.append("defs");

//Append a linearGradient element to the defs and give it a unique id
var linearGradient = defs.append("linearGradient")
    .attr("id", "linear-gradient");
	
linearGradient
    .attr("x1", "0%")
    .attr("y1", "100%")
	.attr("x2", "0%")
    .attr("y2", "0%");

var startcolour = "#000000";
var endcolour = "#69b3a2";

//Set the color for the start (0%)
linearGradient.append("stop")
    .attr("offset", "0%")
    .attr("stop-color", startcolour);

//Set the color for the end (100%)
linearGradient.append("stop")
    .attr("offset", "100%")
    .attr("stop-color", endcolour);
	
legend = svg.append("g")
	.attr("class","legend")
    .attr("transform",
          "translate(" + (width + 60)  + "," + margin.top + ")");
		  
var lwidth = 30;

legend.append("rect")
	.attr("x",0)
	.attr("y",20)
	.attr("width",lwidth)
	.attr("height",height-40)
	.attr("stroke","white")	
	.attr("fill","url(#linear-gradient)");
	
var maxtext = legend.append("text")
	.attr("x",lwidth/2)
	.attr("y",10)
	.attr("fill","white")
	.attr("text-anchor","middle")
	.text("MAX");
	
var mintext = legend.append("text")
	.attr("x",lwidth/2)
	.attr("y",height)
	.attr("fill","white")
	.attr("text-anchor","middle")
	.text("MIN");

// append the svg object to the body of the page
svg = svg
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");


var channels = TD.channels.length-1;

var bucketspan = 1;
var bucketset = new Array(buckets);
var channelset = new Array(channels);

for(var x=0;x<buckets;x++)
{
	bucketset[x] = x+1;
}
for(var x=0;x<channels;x++)
{
	channelset[x] = TD.channels[x+1];
}

var bucket = new Array(channels);
var bucketcount = new Array(channels);
var bucketpoint = new Array(buckets);
var bucketranges = new Array(buckets);
for (var q=0;q<channels;q++)
{
	bucket[q] = new Array(buckets);
	bucketcount[q] = new Array(buckets);
}

var data = TD.records;	
var backfill = true;

var mint = d3.min(data,function (d) { return d[0]; });
var maxt = d3.max(data,function (d) { return d[0]; });
mint = parseDateTime(mint).getTime();
maxt = parseDateTime(maxt).getTime();
var spnt = maxt - mint;

var bucketspan = spnt / buckets;
var indx = 0;

for(var q=0;q<buckets;q++)
{
	bucketpoint[q] = FormatAxisDate(mint + (bucketspan * q) + (bucketspan / 2),spnt);
	bucketranges[q] = dateformat(mint + (bucketspan * q)) + " to " + dateformat(mint + (bucketspan * (q+1)));
}

for (var n=0;n<TD.records.length;n++)
{
	indx = Math.floor((parseDateTime(TD.records[n][0]).getTime() - mint) / bucketspan);
	for (var q=0;q<channels;q++)
	{
		if (bucket[q][indx] == undefined)
			bucket[q][indx] = 0;
		bucket[q][indx] += parseFloat(TD.records[n][q+1]);
		if (bucketcount[q][indx] == undefined) 
			bucketcount[q][indx] = 1;
		else
			bucketcount[q][indx]++;
	}
}

var vl = undefined;
var vmx = undefined;
var vmn = undefined;
for(var n=0;n<buckets;n++)
{
	for (var q=0;q<channels;q++)
	{
		if (bucketcount[q][n] >= 1)
		{
			bucket[q][n] /= bucketcount[q][n];
		}
		vl = bucket[q][n];
		if (!isNaN(vl))
		{
			if (vmx == undefined)
			{
				vmx = vl;
				vmn = vl;
			}
			else
			{
				
					if (vl > vmx) vmx = vl;
					if (vl < vmn) vmn = vl;
				
			}
		}
	}
}

mintext.text(vmn.toFixed(2));
maxtext.text(vmx.toFixed(2));

if (backfill == true)
{
	//Forward-fill step
	var lv = new Array(channels);
	var backfill = false;
	for(var n=0;n<buckets;n++)
	{
		for (var q=0;q<channels;q++)
		{
			if (bucketcount[q][n] >= 1)
			{
				lv[q] = bucket[q][n];
			}
			else
			{
				if (lv[q] != undefined)
				{
					bucket[q][n] = lv[q];
				}
				else
				{
					backfill = true;
				}
			}			
		}
	}
	
	if (backfill == true)
	{
		//Backfill step
		for(var n=buckets-1;n>=0;n--)
		{
			for (var q=0;q<channels;q++)
			{
				if (bucketcount[q][n] >= 1)
				{
					lv[q] = bucket[q][n];
				}
				else
				{					
					bucket[q][n] = lv[q];				
				}			
			}
		}
	}	
}

var miny = 0;
	var maxy = channels;
	var yspn = maxy - miny;		

  // Add X axis
  var x = d3.scaleBand()
	.range([ 0, width ])
	.domain(bucketpoint)
	.padding(0.01);
	
  var bdisplay = "block";
  if (buckets > 100) bdisplay="none";
  
  svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x))
		.selectAll("text")
			.style("text-anchor", "end")
			.attr("dx","-5")
			.attr("transform","rotate(-90)")
			.attr("display",bdisplay);

  // Add Y axis
  var y = d3.scaleBand()
	.range([ 0,height ])
	.domain(channelset)
	.padding(0.01);
	
   var clr = d3.scaleLinear()
      .range([startcolour, endcolour])
      .domain([vmn,vmx])
	
	var indx = 0;
	finaldata = new Array(buckets * channels);
	for (var q=0;q<buckets;q++)
	{
		for (var n=0;n<channels;n++)
		{		
		    var v = bucket[n][q];			
			finaldata[indx] = [n,q+1,v];	
			indx++;
		}
	}
	
  svg.append("g")
	.attr("class","yaxis")
    .call(d3.axisLeft(y));
		
	
	finaldata = finaldata.filter(function (d) {
		return (d[2] != undefined);
	});

  // Add dots
  svg.append('g')
    .selectAll("rect")
    .data(finaldata)
    .enter()
    .append("rect")
	  .attr("data-value",function (d) {return MappedValue(TD.channels[d[0] + 1],d[2]); })
	  .attr("data-column",function (d) {return TD.channels[d[0]+1]; })
	  .attr("data-range",function (d) {return bucketranges[d[1]]; })
	  .on("mouseover",function(e) { HMShowTooltip(e); })	
	  .on("mousemove",function(e) { HMUpdateTooltip(e); })	
	  .on("mouseout",function(e) { HMHideTooltip(e); })		  
      .attr("x", function (d) { 
		if (d == undefined) return 0;
		return x(bucketpoint[d[1]]); 
	  })
      .attr("y", function (d) { 
		if (d == undefined) return 0;
	    var yd = y(TD.channels[d[0]+1]);
		return yd;
	  })
      .attr("width", x.bandwidth() )
	  .attr("height", y.bandwidth() )
      .style("fill", function (d) {	   
		var c = clr(d[2]);
		return c;
	  })
	  
function HMTooltipContent(element)
{
	return "Average " + element.getAttribute("data-column") + ": " + element.getAttribute("data-value") + "<br/>From " + element.getAttribute("data-range").replace(" to ","<br/>To ");
}
	  
function HMShowTooltip(element)
{
	$('#tooltip').css('left',element.clientX);
	$('#tooltip').css('top',element.clientY);
	$('#tooltip').css('display','block');
	//$('#tooltip').stop(true,true).fadeIn(200);
	var panel = element.currentTarget.getAttribute('data-panel');
	var item = element.currentTarget.getAttribute('data-id');
	
	tooltipob = panelsettings[panel];
	tooltipid = item;
	tooltipcontext = element;
	try
	{
		//console.log("Creating Tooltip");
		$('#tooltip').html(HMTooltipContent(element.currentTarget));
	}
	catch(e)
	{
	}
}

function HMUpdateTooltip(element)
{
	$('#tooltip').css('left',element.clientX + 10);
	$('#tooltip').css('top',element.clientY + 10);
	tooltipcontext = element;
	try
	{
		$('#tooltip').html(HMTooltipContent(element.currentTarget));
	}
	catch(e)
	{
	}
}

function HMHideTooltip(element)
{
	//$('#tooltip').hide(0);
	$('#tooltip').css('display','none');
	try
	{
		$('#tooltip').html(HMTooltipContent(element.currentTarget));
	}
	catch(e)
	{
	}
}