# Area Chart

The code is under file `awesome-area-chart-demo.html`. The chart is draw for a set of dummy transaction withdrawal and deposit on a particular date 
  - X-axis represents the date
  - Y-axis shows the credit/debit amount
<link rel="import" href="https://polygit.org/polymer+polymer+v2.0.0-rc.3/webcomponentsjs+webcomponents+v1.0.0-rc.6/components/polymer/polymer-element.html">
<link rel="import" href="awesome-charts/awesome-area-chart.html">
<dom-module id="awesome-area-chart-demo">
  <template>
    <style>
      :host {
        display: block;
      }
      
      .container {
        margin: 10px;
        background-color: #fafafa;
        padding: 10px;
        border: 1px solid #e5e5e5;
      }
      
      pre {
        font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
        margin-bottom: 10px;
        overflow: auto;
        width: auto;
        padding: 5px;
        background-color: #eee;
        width: 650px!ie7;
        padding-bottom: 20px!ie7;
        max-height: 600px;
      }
      
      .chart1{
        --chart-opacity:0.8;
      }
      
    </style>
    <div class="container">
      <h2>Basic Area chart</h2>
      <blockquote>
        <pre>
        <code>
  #1 : Charts binded with data and basic minimal configuration
  #2 : mixins used for styling
        </code>
      </pre>
      </blockquote>
      <div class="chart1">
        <awesome-area-chart data={{data1}} chart-config={{config1}}></awesome-area-chart>
      </div>
    </div>

    <div class="container">
      <h2>Configurable Pie chart with events</h2>
      <blockquote>
        <pre>
        <code>
  #1 : Charts binded with data and few configuration factors
  #2 : The hover tooltip here is not default its resolved via a hook 'tooltip'
  #3 : Click events are binded, click any circle to see in action
        </code>
      </pre>
      </blockquote>
      <div class="chart2">
        <awesome-area-chart data={{data2}} chart-config={{config2}} pie-click="{{pieClick2}}" tooltip={{fntooltip}} circle-click={{fnCircleClick}}></awesome-area-chart>
      </div>
    </div>

   
  </template>
  <script>
    // Define the class for a new element called custom-element
    class AwesomeAreaChartDemo extends Polymer.Element {
        static get is() {
          return "awesome-area-chart-demo";
        }
        static get properties() {
          return {
            data1:{
              type:Array,
              value:[],
              notify:true
            },
            data2:{
              type:Array,
              value:[],
              notify:true
            },
            config1:{
              type:Object,
              value:{
                keys:"credit",
                label:"date",
                drawCircle:false,
                gridLines:false
              }
            },
            config2:{
              type:Object,
              value:{
                 keys:["credit","debit"],
               label:"date",
               legends:["Deposit","Withdraw"],
               color:["#89e200","#ff812f"],
               timeFormat:"%d-%b",
               valueFormat:"",
               xlabelRotate:90,
               margin:{left:50}
              }
            }
          }
        }
        ready() {
          super.ready();
          this.data1 = [{"credit":25000,"debit":10000,"date":"2016-12-31T18:30:00.000Z"},{"credit":43000,"debit":20000,"date":"2017-01-31T18:30:00.000Z"},{"credit":80000,"debit":10000,"date":"2017-02-28T18:30:00.000Z"},{"credit":65000,"debit":35000,"date":"2017-03-31T18:30:00.000Z"},{"credit":25000,"debit":40000,"date":"2017-04-30T18:30:00.000Z"},{"credit":90000,"debit":5000,"date":"2017-05-31T18:30:00.000Z"},{"credit":63000,"debit":7000,"date":"2017-06-30T18:30:00.000Z"},{"credit":41000,"debit":13500,"date":"2017-07-31T18:30:00.000Z"},{"credit":120000,"debit":47500,"date":"2017-08-31T18:30:00.000Z"},{"credit":70000,"debit":1000,"date":"2017-09-30T18:30:00.000Z"},{"credit":77000,"debit":42500,"date":"2017-10-31T18:30:00.000Z"},{"credit":145000,"debit":180000,"date":"2017-11-30T18:30:00.000Z"}];
          this.data2 = [{"credit":25000,"debit":10000,"date":"2016-12-31T18:30:00.000Z"},{"credit":43000,"debit":20000,"date":"2017-01-31T18:30:00.000Z"},{"credit":80000,"debit":10000,"date":"2017-02-28T18:30:00.000Z"},{"credit":65000,"debit":35000,"date":"2017-03-31T18:30:00.000Z"},{"credit":25000,"debit":40000,"date":"2017-04-30T18:30:00.000Z"},{"credit":90000,"debit":5000,"date":"2017-05-31T18:30:00.000Z"},{"credit":63000,"debit":7000,"date":"2017-06-30T18:30:00.000Z"},{"credit":41000,"debit":13500,"date":"2017-07-31T18:30:00.000Z"},{"credit":120000,"debit":47500,"date":"2017-08-31T18:30:00.000Z"},{"credit":70000,"debit":1000,"date":"2017-09-30T18:30:00.000Z"},{"credit":77000,"debit":42500,"date":"2017-10-31T18:30:00.000Z"},{"credit":145000,"debit":180000,"date":"2017-11-30T18:30:00.000Z"}];
        }
        fntooltip(d,prop){
          return prop + " : " + d[prop].toLocaleString('en');
        }
        fnCircleClick(d,k,el){
          alert(k + " clicked");
          console.log(d,k,el);
        }
        
      }
      // Register the new element with the browser
    customElements.define(AwesomeAreaChartDemo.is, AwesomeAreaChartDemo);
  </script>
</dom-module>
<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://polygit.org/webcomponentsjs+1.0.0-rc.5/components/webcomponentsjs/webcomponents-loader.js"></script>
    <link rel="import" href="awesome-area-chart-demo.html">
  </head>
  <body>
    <awesome-area-chart-demo></awesome-area-chart-demo>
  </body>
</html>
<!--
MIT License

Copyright (c) 2017 Vinod Louis

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
-->

<link rel="import" href="https://polygit.org/polymer+polymer+v2.0.0-rc.3/webcomponentsjs+webcomponents+v1.0.0-rc.6/components/polymer/polymer-element.html">
<script src="https://d3js.org/d3.v4.min.js"></script>
<dom-module id="awesome-area-chart">
    <template>
        <style>
            :host {
                display: block;
            }
            .grid line {
                stroke: var(--grid-stroke-color,#ddd);
                stroke-width: var(--grid-stroke-width,1px);
            }
            .cursor-pointer{
                cursor: pointer;
            }
            .line{
                opacity:var(--chart-opacity,0.5);
            }

        </style>
        <div id="groundAreaChart"></div>
    </template>

    <script>
    /**
     * `awesome-area-chart`
     *
     *
     * @AwesomeAreaChart
     * @polymer
     * @demo demo/awesome-area-chart.html
        
     ------------
      Properties
     ------------
     #1: Data is the array of object with minimal 2 key value pair which can act as label and key(s) for area chart   
     *REQUIRED
     data : {
        type: Array,
        //label here (date) should be an Js date object or a date string which can be type casted to a valid date
        value:[{"credit":25000,"debit":10000,"date":"2016-12-31T18:30:00.000Z"},{"credit":43000,"debit":20000,"date":"2017-01-31T18:30:00.000Z"},{"credit":80000,"debit":10000,"date":"2017-02-28T18:30:00.000Z"},{"credit":65000,"debit":35000,"date":"2017-03-31T18:30:00.000Z"},{"credit":25000,"debit":40000,"date":"2017-04-30T18:30:00.000Z"},{"credit":90000,"debit":5000,"date":"2017-05-31T18:30:00.000Z"},{"credit":63000,"debit":7000,"date":"2017-06-30T18:30:00.000Z"},{"credit":41000,"debit":13500,"date":"2017-07-31T18:30:00.000Z"},{"credit":120000,"debit":47500,"date":"2017-08-31T18:30:00.000Z"},{"credit":70000,"debit":1000,"date":"2017-09-30T18:30:00.000Z"},{"credit":77000,"debit":42500,"date":"2017-10-31T18:30:00.000Z"},{"credit":145000,"debit":180000,"date":"2017-11-30T18:30:00.000Z"}];
     }

     #2 chart-config an composite object of properties not all are required provides additional customization to chart
     chartConfig:{
        type:Object,
        value:{
            //default size of the chart if containe has no width
            chartSize:300,
            
            *REQUIRED
            //The date object or date string property name which can be used to plot graph
            label:"",
            
            *REQUIRED
            //The values or properties to which graph shall be plot can be a string in case of single area chart or array in case of multi area chart
            keys:"",

            //Array of colors to be used in chart, lenght should be greater than equal to key(s)
            color:[],

            //Object of properties left,right,top,bottom : To set margins useful in case of handling long labels
            margin:{left:35, right:80, top: 30, bottom: 50}

            //Shows tooltip on top
            aggregatedTooltip:true,
            
            //It accepts values in similar fashion as keys legends are given preference over keys in labelling    
            legends:"",
            
            //Draws a circle at every end point on line when set to true 
            drawCircle:false,
            
            //The x axis format identifier must be an valid d3.js time parse specifier(https://github.com/d3/d3-time-format)
            timeFormat:"%d-%b-%y",
            
            //The y axis format identifier must be an valid d3.js number oarse specifier(https://github.com/d3/d3-format)
            valueFormat:".2s",
            
            //The rotation value in degree for x axis alignment
            xlabelRotate:45,

            //draw background gridlines if set to true
            gridLines:true
        }   
     }

     ---------------
      Methods
     ---------------
        #1 : circleClick : Function called when the circle is clicked passing parms include : (param1:data for the clicked circle,param3:property under context click, param3: the circle svg object clicked)

     ---------------
      Events
     ---------------
        #1 : tooltip 
        Hook for displaying tooltip 
        Return type : String
        params passed include : (param1:data for the context point,param2: property name under context)  

     ----------------
      Mixins 
     ----------------
      --grid-stroke-color : Set grid line color
      --grid-stroke-width : Set width of the grid lines
      --chart-opacity : Set opacity for area          
     */

    class AwesomeAreaChart extends Polymer.Element {
      static get is() { return 'awesome-area-chart'; }
      static get properties() {
        return {
          chartConfig:{
            type: Object
          },
          __defaultConfig:{
            type: Object,
            value:{
                chartSize:300,
                label:"",
                margin:{left:35, right:80, top: 30, bottom: 50},
                aggregatedTooltip:true,
                keys:"",
                legends:[],
                color:[],
                drawCircle:true,
                timeFormat:"%d-%b-%y",
                valueFormat:".2s",
                xlabelRotate:45,
                gridLines:true
            }
          },
          data:{
            type: Array,
            observer:'_dataChanged'
          }
        };
      }
      ready(){
        super.ready();
      }
      _dataChanged(val){
        if(val){

            //The Mandatory check
            if(!this.chartConfig.label || typeof this.chartConfig.label !== "string"){
                 throw new Error("'label' property under chartConfig should be an appropriate string value");
                 return;
            }
            if(!this.chartConfig.keys || (typeof this.chartConfig.keys !== "string" && !Array.isArray(this.chartConfig.keys))){
                 throw new Error("'keys' property under chartConfig should be an appropriate string/array value");
                 return;
            }

            //Convert keys to array
            this.chartConfig.keys = (!Array.isArray(this.chartConfig.keys)) ? [this.chartConfig.keys] : this.chartConfig.keys;

            //Safe check for color
            if(this.chartConfig.color){
                if(!Array.isArray(this.chartConfig.color)){
                    (console ? (console.warn || console.log) : function (m) { return m; })("color should be a valid array");
                    this.chartConfig.color = this.__defaultConfig.color;
                }else if(this.chartConfig.color.length < this.chartConfig.keys.length){
                    (console ? (console.warn || console.log) : function (m) { return m; })("color length should be equal to keys length");
                    this.chartConfig.color = this.__defaultConfig.color;
                }
            }

            //Safe check for legends
            if(this.chartConfig.legends){
                if(typeof this.chartConfig.legends !== "string" && !Array.isArray(this.chartConfig.legends)){
                    (console ? (console.warn || console.log) : function (m) { return m; })("legends should be valid string/array");
                    this.chartConfig.legends = this.__defaultConfig.legends;
                }else if(typeof this.chartConfig.legends === "string" && this.chartConfig.keys.length !== 1){
                    (console ? (console.warn || console.log) : function (m) { return m; })("legends length should be equal to key length");
                    this.chartConfig.legends = this.__defaultConfig.legends;
                }else if(Array.isArray(this.chartConfig.legends) && this.chartConfig.legends.length < this.chartConfig.keys.length){
                    (console ? (console.warn || console.log) : function (m) { return m; })("legends length should be equal to key length");
                    this.chartConfig.legends = this.__defaultConfig.legends;
                }
            }

            //Safe check for margin
            if(this.chartConfig.margin){
                if(typeof this.chartConfig.margin !== "object"){
                    (console ? (console.warn || console.log) : function (m) { return m; })("margin should be of type object");
                    this.chartConfig.margin = this.__defaultConfig.margin;
                }else{
                    var arrM = ["top","bottom","right","left"];
                    arrM.forEach((d)=>{
                        if(this.chartConfig.margin.hasOwnProperty(d) && typeof this.chartConfig.margin[d] !== "number"){
                            (console ? (console.warn || console.log) : function (m) { return m; })(d + " in margin is not a valid number");
                            this.chartConfig.margin[d] = this.__defaultConfig.margin[d];
                        }
                    });
                }
            }

            if(typeof this.chartConfig.aggregatedTooltip !== "boolean" && typeof this.chartConfig.aggregatedTooltip !== "undefined"){
                (console ? (console.warn || console.log) : function (m) { return m; })("aggregatedTooltip should be a boolean value");
                            this.chartConfig.aggregatedTooltip = this.__defaultConfig.aggregatedTooltip;
            }

            if(typeof this.chartConfig.drawCircle !== "boolean" && typeof this.chartConfig.drawCircle !== "undefined"){
                (console ? (console.warn || console.log) : function (m) { return m; })("drawCircle should be a boolean value");
                            this.chartConfig.drawCircle = this.__defaultConfig.drawCircle;
            }

            if(typeof this.chartConfig.gridLines !== "boolean" && typeof this.chartConfig.gridLines !== "undefined"){
                (console ? (console.warn || console.log) : function (m) { return m; })("gridLines should be a boolean value");
                            this.chartConfig.gridLines = this.__defaultConfig.gridLines;
            }

            //Safe check for xlabelRotate
            if(this.chartConfig.xlabelRotate && typeof this.chartConfig.xlabelRotate !== "number"){
                (console ? (console.warn || console.log) : function (m) { return m; })("xlabelRotate is not a valid number");
                this.chartConfig.xlabelRotate = this.__defaultConfig.xlabelRotate;
            }

            

            this.paintDelayedChart();
        }
      }
      paintDelayedChart(){
        var self = this;
        setTimeout(()=>self.drawAreaChartViz(),0)
      }
      drawAreaChartViz(){
        this.chartConfig.margin = Object.assign(JSON.parse(JSON.stringify(this.__defaultConfig.margin)),this.chartConfig.margin);
        this.chartConfig = Object.assign(JSON.parse(JSON.stringify(this.__defaultConfig)),this.chartConfig);

        if(this.chartConfig.legends && typeof this.chartConfig.legends === "string")
            this.chartConfig.legends = [this.chartConfig.legends];

        d3.selection.prototype.moveToFront = function() {  
          return this.each(function(){
            this.parentNode.appendChild(this);
          });
        };

        //Set Dimensions
        var self = this;
        var currHover = null;
        var ow = (this.offsetWidth == 0) ? this.chartConfig.chartSize : this.offsetWidth;
        var width = Math.floor(ow);
        var height = Math.floor(ow*0.70);
        var maxValue = 0;
        
        //safely parse label as date
        this.data.forEach((el)=>{
            maxValue = Math.max(maxValue,this.chartConfig.keys.reduce(function(m, k){ return el[k] > m ? el[k] : m }, -Infinity));
            if (!(el[this.chartConfig.label] instanceof Date))
                el[this.chartConfig.label] = new Date(el[this.chartConfig.label]);
        });

        //Remove the old scraps
        d3.select(this.$.groundAreaChart).html("");

        //Prepare playground
        var svg = d3.select(this.$.groundAreaChart).append("svg")
        .attr("width", width)
        .attr("height", height)
        .attr("id","ground")

        //In case of no data handle
        if(this.data.length == 0){
            svg.append("text").attr("x",width/2).attr("y",height/2).attr("text-anchor","middle").text("No Data Available to display");
            return;
        }

        // Add the clip path.
        svg.append("clipPath")
        .attr("id", "clip")
        .append("rect")
        .attr("width", width)
        .attr("height", height);

        //Set Margins
        var margin = this.chartConfig.margin;
        var width = svg.attr("width") - margin.left - margin.right;
        var height = svg.attr("height") - margin.bottom - margin.top;

        //Prepare scales
        var x = d3.scaleTime()
        .rangeRound([0, width]);

        var y = d3.scaleLinear()
        .rangeRound([height, 0]);

        //return continuous value
        var parseTime = function(d){
            return Date.parse(d)
        }

        //Set Domain for axis
        x.domain(d3.extent(this.data,(d) => parseTime(d[this.chartConfig.label])));
        y.domain([0, maxValue]);

        //X axis Tick
        var x_axis = d3.axisBottom(x).tickFormat((d)=>d3.timeFormat(this.chartConfig.timeFormat)(d));

        //Y Axis Tick
        var y_axis = d3.axisLeft(y)

        if(this.chartConfig.gridLines)
            y_axis = y_axis.tickSize(-width);

        y_axis.tickFormat((d)=>d3.format(this.chartConfig.valueFormat)(d));


        var multiline = (category)=>{
            var line = d3.line()
            .x((d) => x(parseTime(d[this.chartConfig.label])))
            .y((d) => y(d[category]));
            return line;
        }

        var multiarea = (category)=>{
            var area = d3.area()
            .x((d) => x(parseTime(d.date)))
            .y0(height)
            .y1((d)=> y(d[category]));
            return area;
        }

        var gradient = (gradientColor)=>{
            if(typeof gradientColor === "string"){
                return [{offset: "0%", color: "#ffffff"},{offset: "100%", color: gradientColor}];
            }
            
            var arrGradient = []
            for(var prop in gradientColor){
                arrGradient.push({offset:prop,color:gradientColor[prop]});
            }
            return arrGradient;
        }

        //Define Color
        var color = (this.chartConfig.color && this.chartConfig.color.length > 0) ? this.chartConfig.color : d3.schemeCategory10;
        var gradientColor = (this.chartConfig.color && this.chartConfig.color.length > 0) ? this.chartConfig.color : d3.schemeCategory10;

        //Bring chart to playground
        var g = svg.append("g")
        .attr("transform","translate(" + margin.left + "," + margin.top + ")");

        // Add the X Axis
        g.append("g")
        .attr("transform", "translate(0," + height + ")")
        .call(x_axis)
        .selectAll("text")
        .attr("y", 0)
        .attr("x", 5)
        .attr("dy", ".95em")
        .attr("transform", "rotate(" + this.chartConfig.xlabelRotate +")")
        .style("text-anchor", "start");

        // Add the Y Axis
        g.append("g")
        .attr("class", "grid")
        .call(y_axis)

        //Make the gradient for all keys

        this.chartConfig.keys.forEach((el,ind)=>{
            
            svg.append("linearGradient")
            .attr("id", "AreaFillgradient_"+ el)
            .attr("gradientUnits", "userSpaceOnUse")
            .attr("x1", 0).attr("y1", y(0))
            .attr("x2", 0).attr("y2", y(maxValue))
            .selectAll("stop")
            .data(gradient(gradientColor[ind]))
            .enter().append("stop")
            .attr("offset",(d)=> d.offset)
            .attr("stop-color",(d)=> d.color);    

            var lineFunction = multiline(el);
            var areaFunction = multiarea(el);

            g.append("path")
            .datum(this.data)
            .attr("class", "line")
            .attr("stroke",(d,i)=> color[ind])
            .attr("fill","none")
            .attr("d", lineFunction)

            g.append("path")
            .datum(this.data)
            .attr("class", "line")
            .attr("stroke", ()=> color[ind])
            .attr("fill","url(#AreaFillgradient_" + el + ")")
            .attr("d", areaFunction)

            g.append("text")
                  .datum((d) => { return {name: (this.chartConfig.legends.length > 0) ? this.chartConfig.legends[ind] : el[0].toUpperCase() + el.substr(1).toLowerCase(0) , value: this.data[this.data.length-1]}})
                  .attr("transform",(d) => { return "translate(" + x(parseTime(d.value[this.chartConfig.label])) + "," + y(d.value[el]) + ")"; })
                  .attr("x", 7)
                  .attr("dy", ".35em")
                  .text((d)=> d.name)
                  .attr("stroke-width",0.5)
                  .attr("stroke",()=>color[ind])
            if(this.chartConfig.drawCircle || (this.circleClick && typeof this.circleClick === "function")){
                g.selectAll(".circle."+el)
            .data(this.data)
            .enter()
            .append("circle")
            .attr("cx",(d)=> x(parseTime(d.date)))
            .attr("cy",(d)=> y(d[el]))
            .attr("r",5)
            .attr("class",(d)=>{return (self.circleClick && typeof self.circleClick === "function") ? "circle cursor-pointer "+ el : "circle " + el})
            .attr("stroke",(d,i)=>color[ind])
            .attr("fill",(d,i)=>color[ind])
            .on("click",function(d){
                if(self.circleClick && typeof self.circleClick === "function")
                   self.circleClick(d,el,this)         
            })
            .on('mouseenter',function(d,i){

                currHover = g.append("circle").attr("cx",this.getAttribute("cx"))
                .attr("cy",this.getAttribute("cy"))
                .attr("r",10)
                .attr("fill","none")
                .attr("stroke",this.getAttribute("stroke"))

            //console.log(this);
            }).on("mouseleave",function(d,i){
                currHover.remove();
            })
            .append("svg:title")
            .text((d, i)=>{
                if(this.tooltip && typeof this.tooltip === "function")
                   return this.tooltip(d,el);
                return el + " : " + d[el];
            });    
            }      
        });

        if(this.chartConfig.drawCircle || (this.circleClick && typeof this.circleClick === "function")){
            this.chartConfig.keys.forEach((el,ind)=>{
                g.selectAll(".circle."+el)
                //.transition().duration(300).delay((d,i)=> (i*300))
                //.attr('r', 5)
                .each(function(){
                    if(!self.chartConfig.aggregatedTooltip || self.chartConfig.keys.length > 1)
                        d3.select(this).moveToFront();
                });
            });    
        }
            

        
        
        //g.selectAll()
        

        //TODO Animation
        /*
        // Add 'curtain' rectangle to hide entire graph 
        var curtain = svg.append('rect')
        .attr('x', -1 * (width + margin.left + 10))
        .attr('y', -1 * (height + margin.top))
        .attr('height', (height + margin.top))
        .attr('width', width)
        .attr('class', 'curtain')
        .attr('transform', 'rotate(180)')
        .style('fill', '#ffffff');

        // Create a shared transition for anything we're animating 
        var t = svg.transition()
        .delay(750)
        .duration(2000)
        .ease(d3.easeLinear)
        .on('end', function() {
        d3.select('line.guide')
        .transition()
        .style('opacity', 0)
        .remove()
         //svg.append("text")
        //.attr("x", (width / 2))
        //.attr("y", (margin.top - margin.top/2))
        //.attr("text-anchor", "middle")
        //.style("font-size", "12px")
        //.text("Click on points to drill down and anywhere on chart to reset");

        });

        t.select('rect.curtain')
        .attr('width', 0);
        t.select('line.guide')
        .attr('transform', 'translate(' + width + ', 0)')

        */

        if(!this.chartConfig.aggregatedTooltip || this.chartConfig.keys.length > 1)
            return;

        //ToolTip formation
        var bisectDate = d3.bisector((d) => d.date).left;

        var rectHov = svg.append("svg:rect")
        .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")")
        .attr("height",height)
        .attr("width",width+margin.right)
        .attr("fill","none")
        .attr('pointer-events', 'all')
        .on("mouseout", hoverMouseOff)
        .on("mousemove", hoverMouseOn);

        var hoverLineGroup = svg.append("g")
        .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")")
        .attr("class", "hover-line");
        var hoverLine = hoverLineGroup
        .append("line")
        .attr("stroke", "#666666")
        .attr("x1", margin.bottom).attr("x2", 10)
        .attr("y1", 0).attr("y2", height)
        .style("stroke-dasharray", ("3, 3"));
        /*var hoverrect = hoverLineGroup.append("rect")
        .attr("width","70px")
        .attr("height","25px")
        .attr("fill","#e5e5e5")*/

        var hoverTT = hoverLineGroup.append('text')
        .attr("dy", ".35em")
        .attr("text-anchor","middle")
        .attr("class", "hover-tex capo")
        .style("font-size", "12px")
        //.attr('y', height-20);
        /*var cle = hoverLineGroup.append("circle")
        .attr("r", 4.5);*/
        /*var hoverTT2 = hoverLineGroup.append('text')
        .attr("class", "hover-text capo")*/

        hoverLineGroup.style("opacity", 1e-6);
        /*var rectHover = svg.append("rect")
        .data(data)
        .attr("fill", "none")
        .attr("class", "overlay")
        .attr("width", width)
        .attr("height", height);*/

        function hoverMouseOn() {
        var mouse_x = d3.mouse(this)[0];
        var mouse_y = d3.mouse(this)[1];
        var graph_y = y.invert(mouse_y);
        var graph_x = x.invert(mouse_x);
        var mouseDate = x.invert(mouse_x);
        var i = bisectDate(self.data, mouseDate); // returns the index to the current data item
        //console.log(i,graph_y,graph_x,mouseDate)
        //var d0 = data[i - 1]
        //var d1 = data[i];
        // work out which date value is closest to the mouse
        //var d = mouseDate - d0[0] > d1[0] - mouseDate ? d1 : d0;
        i = (i==0) ? 1 : i;
        hoverTT.text(
            (self.tooltip && typeof self.tooltip === "function") ? self.tooltip(self.data[i-1],self.chartConfig.keys[0]) : d3.timeFormat(self.chartConfig.timeFormat)(self.data[i-1][self.chartConfig.label]) + " ," + d3.format(self.chartConfig.valueFormat)(self.data[i-1][self.chartConfig.keys[0]])
            );
        //hoverrect.attr('x', x(self.data[i-1][self.chartConfig.label])-50);
        //hoverrect.attr('y', -25);
        hoverTT.attr('x', x(self.data[i-1][self.chartConfig.label])-15);
        hoverTT.attr('y', -12.5);


        /*cle.attr('x', mouse_x)
        .attr('y', mouse_y);*/

        hoverLine.attr("x1",x(self.data[i-1][self.chartConfig.label])).attr("x2", x(self.data[i-1][self.chartConfig.label]))
        hoverLineGroup.style("opacity", 1);
        }

        function hoverMouseOff() {
        hoverLineGroup.style("opacity", 1e-6);
        }
      }
    }

    window.customElements.define(AwesomeAreaChart.is, AwesomeAreaChart);
  </script>
</dom-module>