var jq = jQuery.noConflict();
jq(document).ready(function() {
    var flotOptions = {
        colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"],
        legend: {
            position: "nw",
            margin: 5, // distance from grid edge to default legend container within plot
            backgroundOpacity: 0.0 // set to 0 to avoid background
        },
        xaxis: { mode: "time" }
    };
    jq('.timeseries').each(function(){
        var timeseries = jq(this);

        // add hide/show button for data table
        var hider = jq('<span class="hideShowData">hide/show data table</span>');
        timeseries.before(hider);
        hider.bind('click', function() { timeseries.slideToggle(); });

        var labels = [];
        timeseries.find('thead tr th').each(function(){labels.push(jq(this).text());});

        // this will hold N objects that look like this {data:[],label:''}
        // where the data array contains date/value pairs, the date is in millis from the epoch
        var series = [];

        timeseries.find('tr').each(function() {
            var cells = jq('>td',this);
            if (cells.size() > 0) {
                // do the date processing, it should always be in column one
                var dateTimeStr = cells.eq(0).html();
                var dateStr = dateTimeStr.split(' ')[0].split('/');
                var timeStr = dateTimeStr.split(' ')[1].split(':');
                // yyyy, mm, dd, hh, mm, ss
                var date = new Date(dateStr[2], dateStr[0], dateStr[1], timeStr[0], timeStr[1], 0);
                var time = date.getTime();

                // for each remaining column create a time series and change
                // background color of cells to match color in graph
                for(var i=1;i<cells.size();i++) {
                    if(!series[i-1]) {
                        series.push({data:[], label:'Series ' + i});
                    }

                    var cell = cells.eq(i);
                    series[i-1].data.push([time, cell.html()]);
                    cell.css('background-color',flotOptions.colors[i-1]);
                }
            }

        });

        // if there are header cells, we'll use those as the labels for each series
        for(var i=1;i<labels.length;i++) {
            series[i-1].label = labels[i];
        }

        jq.plot(jq('#' + this.id + '_target'), series, flotOptions);
    });
});

