<script src="js/d3.v3.min.js"></script>
<?php
if (app()->user->translateMode) {
  echo "<i data-translation-id='STATISTIC_RANGE_TYPE_DAY'>STATISTIC_RANGE_TYPE_DAY = ".__('STATISTIC_RANGE_TYPE_DAY')."</i><br>";
  echo "<i data-translation-id='STATISTIC_RANGE_TYPE_WEEK'>STATISTIC_RANGE_TYPE_WEEK = ".__('STATISTIC_RANGE_TYPE_WEEK')."</i><br>";
  echo "<i data-translation-id='STATISTIC_RANGE_TYPE_MONTH'>STATISTIC_RANGE_TYPE_MONTH = ".__('STATISTIC_RANGE_TYPE_MONTH')."</i><br>";
  echo "<i data-translation-id='STATISTIC_RANGE_TYPE_YEAR'>STATISTIC_RANGE_TYPE_YEAR = ".__('STATISTIC_RANGE_TYPE_YEAR')."</i><br>";
  echo "<i data-translation-id='STATISTIC_WEEK_PICKER_LABEL_SUFFIX'>STATISTIC_WEEK_PICKER_LABEL_SUFFIX= ".__('STATISTIC_WEEK_PICKER_LABEL_SUFFIX')."</i><br>";
  
  echo "<i data-translation-id='ANALYTIC_LEGEND_SUCCESSFULL'>ANALYTIC_LEGEND_SUCCESSFULL= ".__('ANALYTIC_LEGEND_SUCCESSFULL')."</i><br>";
  echo "<i data-translation-id='ANALYTIC_LEGEND_MISSED'>ANALYTIC_LEGEND_MISSED= ".__('ANALYTIC_LEGEND_MISSED')."</i><br>";
  
  echo "<i data-translation-id='ANALYTIC_LEGEND_NO_AGENTS'>ANALYTIC_LEGEND_NO_AGENTS= ".__('ANALYTIC_LEGEND_NO_AGENTS')."</i><br>";
  echo "<i data-translation-id='ANALYTIC_LEGEND_TIMEOUT'>ANALYTIC_LEGEND_TIMEOUT= ".__('ANALYTIC_LEGEND_TIMEOUT')."</i><br>";
  echo "<i data-translation-id='ANALYTIC_LEGEND_BREAK_OUT'>ANALYTIC_LEGEND_BREAK_OUT= ".__('ANALYTIC_LEGEND_BREAK_OUT')."</i><br>";
  
  echo "<i data-translation-id='ANALYTIC_Y_AXIS_LABEL'>ANALYTIC_Y_AXIS_LABEL= ".__('ANALYTIC_Y_AXIS_LABEL')."</i><br>";
  
  } 
/***Widget Stuff ***/
?>


<style>

#reportArea {
  font: 10px sans-serif;
  background-color: #fff;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.bar {
  fill: steelblue;
}

.x.axis path {
/*   display: none; */
}

</style>
<div id="reportArea" class="well well-small"></div>

<script>



//var dataUrl = "<?php //echo $dataUrl; ?>";


var dataUrl = "<?php echo url($this->module->name."/".$this->id."/createReport")?>";
var targetType = "<?php echo $this->getTargetType(); ?>";
var modelId = "<?php echo isset($_GET["id"]) ? $_GET["id"] : ""; ?>";
var getParams = <?php echo json_encode($_GET) ?>;
var date = $('#StatisticDay').val();
getParams["date"] = date;
$.each(getParams,function (i,e) {
    if (i != "r") {
        dataUrl = dataUrl+"&"+i+"="+e;
    }
});

function refreshNavbar(id,attributes) {

    var url = '<?php echo url($this->module->name.'/default/ajaxRefreshNavBar')  ?>';
    $.ajax({
        url : url,
        data: {
            range:attributes['range'],
            date:attributes['date'],
            type:attributes['type'],
            week:attributes['week'],
            id: id
        },
        
        type: "GET",
        dataType : "html",
        success: function (data) {
        
            $('#content').find('.navbar').html(data);
            
            
            $('#content').find('.navbar').find('#StatisticDay').val(attributes['date']);
//             $('#content').find('.navbar').find('#StatisticDay').trigger('change');
            updateDiagram();
        }
    });
}

// $('.target').click(function() {
$('#content').on('click','.target',function() {
    $(this).attr('data-model-id'); 
    targetType = $(this).data('target-type');
    modelId = $(this).data('model-id');
    var urlData = dataUrl.split('&');
    var url = urlData[0]
    dataUrl = '';
    var attributes = {};
    $.each(urlData,function(i,e){
        var keyValue = e.split('=');
        if (keyValue[1]) {
            if (keyValue[0] != 'id') {
                attributes[keyValue[0]] = keyValue[1];
                dataUrl+= keyValue[0]+'='+keyValue[1]+'&';
            }
        } 
    });
    
    dataUrl+='id='+modelId;
    dataUrl+='&targetType='+targetType;
    refreshNavbar($(this).attr('data-model-id'),attributes);
    return false;
})

function selectWeek(el) {

dataUrl = "<?php echo url($this->module->name."/".$this->id."/createReport")?>";
var getParams = <?php echo json_encode($_GET) ?>;

var week = el;
date = $('#StatisticDay').val();
getParams["date"] = date;
getParams["week"] = week;
getParams["targetType"] = targetType;
getParams["id"] = modelId;

$.each(getParams,function (i,e) {
    if (i != "r") {
        dataUrl = dataUrl+"&"+i+"="+e;
    }
});
}

function changeDate() {
dataUrl = "<?php echo url($this->module->name."/".$this->id."/createReport")?>";
var getParams = <?php echo json_encode($_GET) ?>;

date = $('#StatisticDay').val();
getParams["date"] = date;
getParams["targetType"] = targetType;
getParams["id"] = modelId;

$.each(getParams,function (i,e) {
    if (i != "r") {
        dataUrl = dataUrl+"&"+i+"="+e;
    }
});
}
/*
QueueReport Stuff :
*/
if ('<?php echo $this->module->name; ?>' == 'analyticsQueueReport' ) {
  var xRangeDevisor = 4;
  var csvHeader = ["<?php echo __('ANALYTIC_LEGEND_SUCCESSFULL'); ?>","<?php echo __('ANALYTIC_LEGEND_TIMEOUT'); ?>","<?php echo __('ANALYTIC_LEGEND_NO_AGENTS'); ?>","<?php echo __('ANALYTIC_LEGEND_BREAK_OUT'); ?>"];
  var color = d3.scale.ordinal()
    .range(["#468847", "#b94a48","#3939DD","#E4C901"]);

} else {
  var csvHeader = ['<?php echo __("ANALYTIC_LEGEND_SUCCESSFULL") ?>','<?php echo __("ANALYTIC_LEGEND_MISSED") ?>']; // this is in dailyReport
  var xRangeDevisor = 2;
  var color = d3.scale.ordinal()
    .range(["#468847", "#b94a48"]);

}





// var margin = {top: 20, right: 20, bottom: 30, left: 40},
var margin = {top: 20, right: 120, bottom: 30, left: 40},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
//     .rangeRoundBands([0, width], .1);
    .rangeRoundBands([10, width -75], .1);

var y = d3.scale.linear()
    .rangeRound([height, 0]);
var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .tickFormat(d3.format("d"))
    .tickSubdivide(0);

var svg = d3.select("#reportArea").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

d3.csv(dataUrl, function(error, data) {

  color.domain(d3.keys(data[0]).filter(function(key) { return key !== "State"; }));

  data.forEach(function(d) {
    var y0 = 0;
    d.ages = color.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });
    d.total = d.ages[d.ages.length - 1].y1;
  });

  //data.sort(function(a, b) { return b.total - a.total; });

  x.domain(data.map(function(d) { return d.State; }));
  y.domain([0, d3.max(data, function(d) { return d.total; })]);
  
  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)
      .append("text")
      .attr("transform", "translate("+ -75 +"," + 0 +")")
      .attr("x", width)
      .attr("y", 10)
      .attr("dy", ".71em")
      .text("<?php echo  __($xAxisTranslationTag); ?>");

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
      .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("<?php echo __("ANALYTIC_Y_AXIS_LABEL"); ?>");

  var state = svg.selectAll(".state")
      .data(data)
      .enter().append("g")
      .attr("class", "g")
      .attr("transform", function(d) { return "translate(" + x(d.State) + ",0)"; });

  state.selectAll("rect")
      .data(function(d) { return d.ages; })
      .enter().append("rect")
      .attr("width", x.rangeBand())
      .attr("y", function(d) { return y(d.y1); })
//       .attr("x",10) // TEST 
      .attr("height", function(d) { return y(d.y0) - y(d.y1); })
      .style("fill", function(d) { return color(d.name); });

  var legend = svg.selectAll(".legend")
      .data(color.domain().slice().reverse())
      .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) { return "translate(100," + i * 20 + ")"; });

  legend.append("rect")
      .attr("x", width - 18)
      .attr("width", 18)
      .attr("height", 18)
      .style("fill", color);

  legend.append("text")
      .attr("x", width - 24)
      .attr("y", 9)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .text(function(d) { return d; }); 
      
});

function transitionGrouped() {
d3.csv(dataUrl, function(error, data) {
    data.forEach(function(d) {
    var y0 = 0;
    d.ages = color.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });
    d.total = d.ages[d.ages.length - 1].y1;
  });
//Y Axis refresh
  y.domain([0, d3.max(data, function(d) { return d.total; })]);

  
  svg.selectAll('.y')
      .call(yAxis)
      .append("text")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end");
  
  var layer = svg.selectAll('.g')
      .data(data);
      
  var rect = layer.selectAll("rect")
      .data(function(d) { return d.ages; })
      .transition()
      .duration (250)
      .attr("width", x.rangeBand()/xRangeDevisor)
      .transition()
      .duration (250)
      .attr("x", function(d) {
	  if (d.name == csvHeader[1]) {
	    return x.rangeBand()/xRangeDevisor;
	  } else if (csvHeader[2] && d.name == csvHeader[2]) {
	    return x.rangeBand()/xRangeDevisor/xRangeDevisor*8;  
	  } else if (csvHeader[3] && d.name == csvHeader[3]) {
	    return x.rangeBand()/xRangeDevisor/xRangeDevisor*12;  
	  }  
	  
      })
      .transition()
      .duration (250)
      .attr("height", function(d) { return y(d.y0) - y(d.y1); })
      .attr("y", function(d) {
	  if (d.name == 'Successfull') {
	      return thisY = y(d.y1);
	  } else {
	      return height-(y(d.y0) - y(d.y1)) ;
	  }
      })
      .style("fill", function(d) { return color(d.name); });
 });
}

function transitionStacked() {
 d3.csv(dataUrl, function(error, data) {
 
    data.forEach(function(d) {
    var y0 = 0;
    d.ages = color.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });
    d.total = d.ages[d.ages.length - 1].y1;
  });
//Y Axis refresh
  y.domain([0, d3.max(data, function(d) { return d.total; })]);

  svg.selectAll('.y')
      .call(yAxis)
      .append("text")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end");
  
  var layer = svg.selectAll('.g')
      .data(data);
      

  var rect = layer.selectAll("rect")
      .data(function(d) { return d.ages; })
      .transition()
      .duration (250)
      .attr("height", function(d) { return y(d.y0) - y(d.y1); })
      .style("fill", function(d) { return color(d.name); })
       .transition()
      .duration (250)
      .attr("y", function(d) { return y(d.y1); })
      .transition()
      .duration (250)
      .attr('x',0)
      .attr("width", x.rangeBand());
 });
}


function updateDiagram() {
  if ($('#selectViewMode').find('.active').attr('id') == 'grouped') {
      updateGrouped();
  } else {
      updateStacked()
  }
};

function updateGrouped() {
  d3.csv(dataUrl, function(error, data) {
  
    data.forEach(function(d) {
      var y0 = 0;
      d.ages = color.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });
      d.total = d.ages[d.ages.length - 1].y1;
    });
  
    if ( svg.selectAll('.g')[0].length != data.length ) {
      updateXAxis(data,'grouped');
    } else {
  
    y.domain([0, d3.max(data, function(d) { return d.total; })]);

      svg.selectAll('.y')
      .call(yAxis)
      .append("text")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end");
  
    var layer = svg.selectAll('.g')
      .data(data);
    var rect = layer.selectAll('rect')
	  .data(function(d) { return d.ages; })
	  .transition()
	  .duration (250)
	  .attr("height", function(d) { return y(d.y0) - y(d.y1); })
	  .attr("y", function(d) {
	  if (d.name == 'Successfull') {
	      return thisY = y(d.y1);
	  } else {
	      return height-(y(d.y0) - y(d.y1)) ;
	  }
      })  
      }
  });
}

function updateStacked() {
  d3.csv(dataUrl, function(error, data) {
  
    data.forEach(function(d) {
      var y0 = 0;
      d.ages = color.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });
      d.total = d.ages[d.ages.length - 1].y1;
    });
    
    if ( svg.selectAll('.g')[0].length != data.length ) {
      updateXAxis(data,'stacked');
    } else {
    
    
    y.domain([0, d3.max(data, function(d) { return d.total; })]);

    
    
    
    svg.selectAll('.y')
      .call(yAxis)
      .append("text")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end");
      
    var layer = svg.selectAll('.g')
      .data(data);
    var rect = layer.selectAll('rect')
	    .data(function(d) { return d.ages; })
	    .transition()
	    .duration (250)
	    .attr("y", function(d) { return y(d.y1); })
 	    .attr("height", function(d) { return y(d.y0) - y(d.y1); })
    }
	 
  });
}

function updateXAxis(data,viewMode) {

  
  // überflüssige balken löschen ...
  x.domain(data.map(function(d) { return d.State; }));
  y.domain([0, d3.max(data, function(d) { return d.total; })]);

  
  svg.selectAll(".x")
      .transition()
      .duration(250)
      .call(xAxis);
  svg.selectAll(".y")
      .transition()
      .duration(250)
      .call(yAxis);
  if (data.length < svg.selectAll(".g")[0].length) {
    while (svg.selectAll(".g")[0][data.length]) {    
      svg.selectAll(".g")[0][data.length].remove()
    } 
  } else {
      
    dataPart = data.splice(svg.selectAll(".g")[0].length,30)
    var newDays = svg.selectAll('.state')
      .data(dataPart)
      .enter().append("g")
      .attr("class", "g")
      .attr("transform", function(d) { return "translate(" + x(d.State) + ",0)"; })

    if (viewMode == 'stacked') { 
    newDays.selectAll('rect')
      .data(function(d) { return d.ages; })
      .enter().append("rect")
      .style("fill", function(d) { return color(d.name); })
      .attr("width", x.rangeBand())
      .attr("y", 450)
      .transition()
      .duration(250)
      .attr("y", function(d) { return y(d.y1); })
      .attr("height", function(d) { return y(d.y0) - y(d.y1); })
    } else {
      newDays.selectAll('rect')
	  .data(function(d) { return d.ages; })
	  .enter().append("rect")
	  .style("fill", function(d) { return color(d.name); })
	  .attr("width", x.rangeBand()/xRangeDevisor)
	  .attr("x", function(d) {
	      if (d.name == 'Missed') {
		return x.rangeBand()/xRangeDevisor; 
	      }
	  })
	  .attr("y", 450)
	  .transition()
	  .duration (250)
	  .attr("height", function(d) { return y(d.y0) - y(d.y1); })
	  .attr("y", function(d) {
	  if (d.name == 'Successfull') {
	      return thisY = y(d.y1);
	  } else {
	      return height-(y(d.y0) - y(d.y1)) ;
	  }
      }) 
      
      
    }
  }
  if (viewMode == 'stacked') {
  var layer = svg.selectAll('.g')
      .data(data)
      .attr("transform", function(d) { return "translate(" + x(d.State) + ",0)"; });
  var rect = layer.selectAll('rect')
      .data(function(d) { return d.ages; })
      .transition()
      .duration(250)
      .attr("width", x.rangeBand())
      .attr("y", function(d) { return y(d.y1); })
      .attr("height", function(d) { return y(d.y0) - y(d.y1); })
  } else {
	var layer = svg.selectAll('.g')
	  .data(data)
	  .attr("transform", function(d) { return "translate(" + x(d.State) + ",0)"; });
	var rect = layer.selectAll('rect')
	      .data(function(d) { return d.ages; })
	      .transition()
	      .duration (250)
	      .attr("width", x.rangeBand()/xRangeDevisor)
	      .attr("height", function(d) { return y(d.y0) - y(d.y1); })
	      .attr("y", function(d) {
	      if (d.name == 'Successfull') {
		  return thisY = y(d.y1);
	      } else {
		  return height-(y(d.y0) - y(d.y1)) ;
	      }
	  }) 
  }
} 

</script>