<div class="graphunit"><?php echo urldecode($units); ?></div>
<div id="placeholder-weekly_<?php echo $observable; ?>" class="modal-vital-graph"></div>


<div class="modal-vital-legend">
    <h5>Legends</h5>
    <ul>
        <li><span style="display:inline-block;width:20px;color:rgb(255, 153, 0);font-size: 15px; font-weight: bold;text-align: center;">&mdash;</span> Last measured value</li>
        <li><span style="display:inline-block;width:20px;color:rgb(0, 204, 0);font-size: 15px; font-weight: bold;text-align: center;">&mdash;</span> Average measured value</li>
        <li><span style="display:inline-block;width:20px;color:rgb(204, 204, 204);font-size: 15px; font-weight: bolder;text-align: center;">&mdash;</span> Standard deviations from average </li>
    </ul>
</div>

<script language="javascript" type="text/javascript">
    //<![CDATA[
    (function() {

        // setup background areas
        var actualDateTimeStamp =parseInt("<?php echo $graphLastUpdated; ?>",10);
        var now = new Date(actualDateTimeStamp  * 1000); // local date

        // UTC date
        var d = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
        var dlabel = d.format('M dS Y G:i') + ' (UTC)';
        // getday sunday is 0 .. so we need to align this with the current data
        var weekday=new Array();
        weekday[0]=144;
        weekday[1]=0;
        weekday[2]=24;
        weekday[3]=48;
        weekday[4]=72;
        weekday[5]=96;
        weekday[6]=120;




        var alignX = weekday[d.getDay()] + d.getHours();
        var markings = [

            { color: '#000', lineWidth: 1, xaxis: { from: alignX, to: alignX } }
        ];

        var magnifiedViewdata = <?php echo ($graphdata); ?>;
        var lineSeries1 = <?php echo ($graphdatalineseries1); ?>;
        var lineSeries2 = <?php echo ($graphdatalineseries2); ?>;

        var deviationAboveSeries = [];
        var deviationBelowSeries = [];
        var lengthData = magnifiedViewdata.length;

        for (var i = 0; i<lengthData; i++ ) {

            deviationAboveSeries.push([magnifiedViewdata[i][0],magnifiedViewdata[i][2] + magnifiedViewdata[i][3] ]);
            deviationBelowSeries.push([magnifiedViewdata[i][0],magnifiedViewdata[i][2] - magnifiedViewdata[i][3]]);
        }


        var daySubstractCounter = 6;

        var options = { series: {
                magnifiedView: {
                    active: true,
                    lastUpdated : "<?php echo $graphLastUpdated; ?>"
                }
            }
            ,grid:   { hoverable: true, clickable: true,axisMargin: 15,labelMargin: 15,markings: markings},
            yaxis: {
                min: <?php echo $graphdatamin; ?>,
                max: <?php echo $graphdatamax; ?>
            },

            xaxis: {
                max:167,
                tickSize:24,
                tickFormatter: function(val,axis) {

                    var lookupArray = ['Mon','Tue','Wed','Thurs','Fri','Sat','Sun'];
                    var nowPoint = alignX;
                    var lastupdatedDate = d;

                    if (val%24 == 0) {
                        var check = Math.floor((nowPoint - val) / 24);
                        if (check < 0 ) {
                            check = check + 7; // a week old data
                        }
                        var newdate = new Date(lastupdatedDate);
                        newdate.setDate(newdate.getDate() - check);
                        var index = val/24;
                        var display = lookupArray[index];
                        var dateDisplay = (newdate.getMonth() +1) + '/' + newdate.getDate();
                        return display + ' ' + dateDisplay;
                    }

                }

            }
        };




        var placeholder = $("#placeholder-weekly_<?php echo $observable; ?>");
        var plot = $.plot(placeholder,
        [
            { data:lineSeries1,id:'last-measured',lines: {show:true},color:"rgb(255, 153, 0)"},
            { data:lineSeries2,id:'average',lines: {show: true, lineWidth: 1},color:"rgb(0, 204, 0)"},
            { label:"",data:deviationAboveSeries,fillBetween:'average',lines: {show: true, lineWidth: 0,fill:true},color:"rgb(204, 204, 204)"},
            { label:"",data:deviationBelowSeries,fillBetween:'average',lines: {show: true, lineWidth: 0,fill:true},color:"rgb(204, 204, 204)"}
        ]
        ,options);
        drawDateLabel();
        placeholder.resize(drawDateLabel);

        function drawDateLabel() {
            // add labels

            var o;


            o = plot.pointOffset({ x: alignX, y: <?php echo $graphdatamax; ?>});
            // we just append it to the placeholder which Flot already uses
            // for positioning
            //var labelDate = d.toGMTString();
            if (!isNaN(actualDateTimeStamp)) {
                var labelDate = dlabel;

                placeholder.find('.current-datelabel').remove();
                placeholder.append('<div class="current-datelabel" style="position:absolute;left:' + (o.left + 14) + 'px;top:' + (o.top+5) + 'px;color:#666;font-size:smaller">'+labelDate+'</div>');
                // draw a little arrow on top of the last label to demonstrate
                // canvas drawing
                var ctx = plot.getCanvas().getContext("2d");
                ctx.beginPath();
                o.left += 1;
                var ttop = o.top+20;
                ctx.moveTo(o.left, ttop-5);
                ctx.lineTo(o.left, ttop - 10);
                ctx.lineTo(o.left + 10, ttop-5);
                ctx.lineTo(o.left, ttop);
                ctx.fillStyle = "#000";
                ctx.fill();
            }
        }

        $(placeholder).on("plothover", function (event, pos, item) {
            if (item) {
                if (previousPoint != item.datapoint) {
                    previousPoint = item.datapoint;

                    $("#tooltip").remove();
                    var x = item.datapoint[0].toFixed(2),
                    y = item.datapoint[1].toFixed(2);

                    showTooltip(item.pageX, item.pageY, y);
                }
            }
            else {
                $("#tooltip").remove();
                previousPoint = null;
            }
        });
        function showTooltip(x, y, contents) {


            $('<div id="tooltip">' + contents + '</div>').css( {
                position: 'absolute',
                display: 'none',
                top: y + 5,
                left: x + 5,
                border: '1px solid #fdd',
                padding: '10px',
                color: '#000',
                'background-color': '#fee',
                opacity: 0.80,
                zIndex:10000
            }).appendTo("body").fadeIn(200);
        }



    })();
    //]]>
</script>

