<ul id="[{$unique_id}]-object-list" class="list-style-none m10"></ul>

<div id="canvas_[{$unique_id}]" class="cb">
	<div class="box-blue m5 p5">
		<img src="[{$dir_images}]icons/silk/information.png" class="vam mr5" /><span>[{isys type="lang" ident="LC__CMDB__BROWSER_OBJECT__PLEASE_CHOOSE"}]</span>
	</div>
</div>

<style type="text/css">
	#[{$unique_id}]-object-list li {
		float: left;
		margin-right: 5px;
		cursor: pointer;
	}

	#canvas_[{$unique_id}] {
		height: 400px;
	}

	#canvas_[{$unique_id}] text {
		font-size: 10px;
	}

	#canvas_[{$unique_id}] path.line {
		fill: none;
		stroke: #888;
		stroke-width: 3px;
		clip-path: url(#clip);
	}

	#canvas_[{$unique_id}] path.line.filtered {
		opacity: 0.25;
	}

	#canvas_[{$unique_id}] .zoom {
		cursor: move;
		fill: none;
		pointer-events: all;
	}
</style>

<script type="text/javascript">
    (function () {
        "use strict";

        var $canvas     = $('canvas_[{$unique_id}]'),
            $objectList = $('[{$unique_id}]-object-list'),
            margin      = { top: 20, right: 20, bottom: 150, left: 120 },
            margin2     = { top: 270, right: 20, bottom: 30, left: 120 },
            width       = $canvas.getWidth() - margin.left - margin.right,
            height      = $canvas.getHeight() - margin.top - margin.bottom,
            height2     = $canvas.getHeight() - margin2.top - margin2.bottom,
            data        = JSON.parse('[{$objectData|json_encode|escape:"javascript"}]'),
            cmdbStatus  = JSON.parse('[{$cmdbStatus|json_encode|escape:"javascript"}]');

        if (Object.isArray(data) && data.length === 0) {
            return;
        }

        idoit.Require.require(['d3'], function () {
            var cmdbStatusRange  = $R(0, cmdbStatus.length).map(function (index) {
                    return index * (height / cmdbStatus.length);
                }),
                cmdbStatusRange2 = $R(0, cmdbStatus.length).map(function (index) {
                    return index * (height2 / cmdbStatus.length);
                }),
                i, min = [], max = [];

            for (i in data) {
                if (data.hasOwnProperty(i)) {
                    $objectList
	                    .insert(new Element('li', {'data-object-id': data[i][0].objectId, title: data[i][0].objectTypeTitle + ' » ' + data[i][0].objectTitle})
                            .update(new Element('div', {className: 'cmdb-marker mr5', style: 'background-color:' + data[i][0].objectColor}))
                            .insert(new Element('span').update(data[i][0].objectTitle))
                    );

                    min.push(d3.min(data[i][1], function (d) {
                        return new Date(d.date);
                    }));
                    max.push(d3.max(data[i][1], function (d) {
                        return new Date(d.date);
                    }));
                }
            }

            min = d3.min(min);
            max = d3.max(max);

            $canvas.on('render:chart', function () {
                width = $canvas.getWidth() - margin.left - margin.right;

                var x = d3.scaleTime()
                          .range([0, width])
                          .domain([min, max]);

                var y = d3.scaleOrdinal()
                          .range(cmdbStatusRange)
                          .domain(cmdbStatus);

                var line = d3.line()
                             .x(function (d) {
                                 return x(new Date(d.date));
                             })
                             .y(function (d) {
                                 return y(d.status);
                             })
                             .curve(d3.curveStepAfter);

                var svg = d3.select('#canvas_[{$unique_id}]').html(null).append('svg')
                            .attr('width', width + margin.left + margin.right)
                            .attr('height', height + margin.top + margin.bottom);

                svg.append("defs").append("clipPath")
                   .attr("id", "clip")
                   .append("rect")
                   .attr("width", width)
                   .attr("height", height);

                var vis = svg
                    .append('g')
                    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

                vis.append('g')
                   .attr('class', 'x axis')
                   .attr('transform', 'translate(0,' + height + ')')
                   .call(d3.axisBottom(x));

                vis.append('g')
                   .attr('class', 'y axis')
                   .call(d3.axisLeft(y));

                vis.append('g')
                   .attr('class', 'x grid')
                   .call(xAxis().tickSize(-width).tickFormat(''));

                vis.append('g')
                   .attr('class', 'y grid')
                   .call(yAxis().tickSize(height).tickFormat(''));

                vis.selectAll('path.line')
                   .data(data)
                   .enter()
                   .append('path')
                   .attr('data-object-id', function (d) {
                       return d[0].objectId
                   })
                   .attr('class', 'line')
                   .attr('d', function (d) {
                       return line(d[1]);
                   })
                   .style('stroke', function (d) {
                       return d[0].objectColor;
                   });

                var x2 = d3.scaleTime()
                           .range([0, width])
                           .domain([min, max]);

                var y2 = d3.scaleOrdinal()
                           .range(cmdbStatusRange2)
                           .domain(cmdbStatus);

                var line2 = d3.line()
                              .x(function (d) {
                                  return x2(new Date(d.date));
                              })
                              .y(function (d) {
                                  return y2(d.status);
                              })
                              .curve(d3.curveStepAfter);

                var brush = d3.brushX()
                              .extent([
                                  [0, 0], [width, height2]
                              ])
                              .on("brush end", brushed);

                var zoom = d3.zoom()
                             .scaleExtent([
                                 1, Infinity
                             ])
                             .translateExtent([
                                 [0, 0], [width, height]
                             ])
                             .extent([
                                 [0, 0], [width, height]
                             ])
                             .on("zoom", zoomed);

                var context = svg
                    .append('g')
                    .attr('transform', 'translate(' + margin2.left + ',' + margin2.top + ')');

                context
                    .selectAll('path.line')
                    .data(data)
                    .enter()
                    .append("path")
                    .attr("class", "line")
                    .attr("d", function (d) {
                        return line2(d[1]);
                    });

                context.append("g")
                       .attr("class", "axis axis-x")
                       .attr("transform", "translate(0," + height2 + ")")
                       .call(d3.axisBottom(x2));

                context.append("g")
                       .attr("class", "brush")
                       .call(brush)
                       .call(brush.move, x.range());

                svg.append("rect")
                   .attr("class", "zoom")
                   .attr("width", width)
                   .attr("height", height)
                   .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
                   .call(zoom);

                function xAxis() {
                    return d3.axisLeft(y);
                }

                function yAxis() {
                    return d3.axisBottom(x);
                }

                function zoomed() {
                    // ignore zoom-by-brush
                    if (d3.event.sourceEvent && d3.event.sourceEvent.type === "brush") {
                        return;
                    }
                    var t = d3.event.transform;
                    x.domain(t.rescaleX(x2).domain());
                    vis.selectAll(".line").attr("d", function (d) {
                        return line(d[1]);
                    });
                    vis.select(".axis.x").call(d3.axisBottom(x));
                    context.select(".brush").call(brush.move, x.range().map(t.invertX, t));

                    vis.select('.grid.y')
                       .call(yAxis().tickSize(height).tickFormat(''));

                    gridCleanup();
                }

                function brushed() {
                    // ignore brush-by-zoom
                    if (d3.event.sourceEvent && d3.event.sourceEvent.type === "zoom") {
                        return;
                    }
                    var s = d3.event.selection || x2.range();
                    x.domain(s.map(x2.invert, x2));
                    vis.selectAll(".line").attr("d", function (d) {
                        return line(d[1]);
                    });
                    vis.select(".axis.x").call(d3.axisBottom(x));
                    svg.select(".zoom").call(zoom.transform, d3.zoomIdentity
                                                               .scale(width / (s[1] - s[0]))
                                                               .translate(-s[0], 0));

                    vis.select('.grid.y')
                       .call(yAxis().tickSize(height).tickFormat(''));

                    gridCleanup();
                }

                function gridCleanup() {
                    // Cleanup the grid.
                    vis.selectAll('.grid.x line')
                       .style('stroke', '#eee')
                       .style('stroke-dasharray', '3,3')
                       .attr('stroke', null);

                    vis.selectAll('.grid.y line')
                       .style('stroke', '#eee')
                       .style('stroke-dasharray', '3,3')
                       .attr('stroke', null);

                    vis.selectAll('.grid.y path,.grid.x path,.grid text').remove();
                }
            });

            $objectList.on('click', 'li', function (ev) {
                var $li      = ev.findElement('li'),
                    objectId = $li.readAttribute('data-object-id');

                if ($li.hasClassName('text-bold'))
                {
                    $li.removeClassName('text-bold');
                    d3.selectAll('path.line').classed('filtered', false);
                }
                else
                {
                    $objectList.select('li').invoke('removeClassName', 'text-bold');
                    $li.addClassName('text-bold');

                    d3.selectAll('path.line').classed('filtered', true);
                    d3.select('path.line[data-object-id="' + objectId + '"]').classed('filtered', false);
                }
            });

            $canvas.fire('render:chart');
        });
    })();
</script>
