function clearDivTrend() {
    var Jq$ = jQuery.noConflict();
    document.getElementById("choices").innerHTML = "";
    document.getElementById("flotChartplaceholder").innerHTML = "";
    Jq$("choices").empty();
    Jq$("flotChartplaceholder").empty();
}
var ctx;
function BindTrendChartP3(response, MinVal, MaxVal, Params) {
    console.log(response);
    var jt$ = jQuery.noConflict();
    clearDivTrend();
    var aData = response;
    var Paramlst = null;

    var str_arrayMinVal = MinVal;
    var str_arrayMaxVal = MaxVal;

    var str_arrayMin = str_arrayMinVal.toString().split(',');
    var str_arrayMax = str_arrayMaxVal.toString().split(',');

    var aDatasets1 = null;
    var aDatasets2 = null;
    var aDatasets3 = null;
    var aDatasets4 = null;
    var aDatasets5 = null;
    var aDatasets6 = null;
    var aDatasets7 = null;
    var aDatasets8 = null;

    if (Params != undefined && Params.length > 0) {
        Paramlst = JSON.parse(Params);
    }

    for (var i = 1; i < aData.length; i++) {
        if (i == 1 && aData[1] != undefined && aData[1].length > 0) {
            aDatasets1 = JSON.parse('[' + [aData[1]] + ']');
        }
        if (i == 2 && aData[2] != undefined && aData[2].length > 0) {
            aDatasets2 = JSON.parse('[' + [aData[2]] + ']');
        }
        if (i == 3 && aData[3] != undefined && aData[3].length > 0) {
            aDatasets3 = JSON.parse('[' + [aData[3]] + ']');
        }
        if (i == 4 && aData[4] != undefined && aData[4].length > 0) {
            aDatasets4 = JSON.parse('[' + [aData[4]] + ']');
        }
        if (i == 5 && aData[5] != undefined && aData[5].length > 0) {
            aDatasets5 = JSON.parse('[' + [aData[5]] + ']');
        }
        if (i == 6 && aData[6] != undefined && aData[6].length > 0) {
            aDatasets6 = JSON.parse('[' + [aData[6]] + ']');
        }
        if (i == 7 && aData[7] != undefined && aData[7].length > 0) {
            aDatasets7 = JSON.parse('[' + [aData[7]] + ']');
        }
        if (i == 8 && aData[8] != undefined && aData[8].length > 0) {
            aDatasets8 = JSON.parse('[' + [aData[8]] + ']');
        }
    }



    var dataSetP3 = [{
        label: Paramlst[0],
        data: aDatasets1,
        yaxis: 1,
        points: { symbol: "circle", show: true, radius: 1 },
        lines: { show: true, fill: false }
    }, {
        label: Paramlst[1],
        data: aDatasets2,
        yaxis: 2,
        points: { symbol: "circle", show: true, radius: 1 },
        lines: { show: true, fill: false }
    }, {
        label: Paramlst[2],
        data: aDatasets3,
        yaxis: 3,
        points: { symbol: "circle", show: true, radius: 1 },
        lines: { show: true, fill: false }
    }, {
        label: Paramlst[3],
        data: aDatasets4,
        yaxis: 4,
        points: { symbol: "circle", show: true, radius: 1 },
        lines: { show: true, fill: false }
    },
    {
        label: Paramlst[4],
        data: aDatasets5,
        yaxis: 5,
        points: { symbol: "circle", show: true, radius: 1 },
        lines: { show: true, fill: false }
    }, {
        label: Paramlst[5],
        data: aDatasets6,
        yaxis: 6,
        points: { symbol: "circle", show: true, radius: 1 },
        lines: { show: true, fill: false }
    }, {
        label: Paramlst[6],
        data: aDatasets7,
        yaxis: 7,
        points: { symbol: "circle", show: true, radius: 1 },
        lines: { show: true, fill: false }
    }
    , {
        label: Paramlst[7],
        data: aDatasets8,
        yaxis: 8,
        points: { symbol: "circle", show: true, radius: 1 },
        lines: { show: true, fill: false }
    }
    ];

    var optionsP3 = {
        xaxis: {
            mode: "time",
            timeformat: "%d-%m-%y %H:%M:%S",
            //tickSize: [1, 'hours'],
            twelveHourClock: true,
            timezone: "browser",
            overflow: scroll
        },
        canvas: true,
        pan: { interactive: true },
        zoom: {
            interactive: true,
        },
        shadowSize: 5,

        //ignoreZeroValuePoints: false,
        colors: ["#ff9900", "#2E7D32", "#64DD17", '#9900ff', "#cc0099", "#000099", "#99ccff", "#795548"],
        yaxes: [
            {
                position: "left",
                axislabelfontsizepixels: 12,
                axislabelfontfamily: 'verdana, arial',
                color: "#ff9900",
                axislabel: Paramlst[0],
                axislabelusecanvas: true,
                axislabelfontsizepixels: 12,
                axislabelfontfamily: 'verdana, arial, helvetica, tahoma, sans-serif',
                axislabelpadding: 2,
                min: str_arrayMin[0],
                max: str_arrayMax[0],
                tickDecimals: 0
            }, {
                position: "left",
                axislabelfontsizepixels: 12,
                axislabelfontfamily: 'verdana, arial',
                color: "#2E7D32",
                axislabel: Paramlst[1],
                axislabelusecanvas: true,
                axislabelfontsizepixels: 12,
                axislabelfontfamily: 'verdana, arial, helvetica, tahoma, sans-serif',
                axislabelpadding: 3,
                min: str_arrayMin[1],
                max: str_arrayMax[1],
                tickDecimals: 0
            }, {
                position: "left",
                axislabelfontsizepixels: 12,
                axislabelfontfamily: 'verdana, arial',
                color: "#64DD17",
                axislabel: Paramlst[2],
                axislabelusecanvas: true,
                axislabelfontsizepixels: 12,
                axislabelfontfamily: 'verdana, arial, helvetica, tahoma, sans-serif',
                axislabelpadding: 3,
                min: str_arrayMin[2],
                max: str_arrayMax[2],
                tickDecimals: 0
            }, {
                position: "left",
                axislabelfontsizepixels: 12,
                axislabelfontfamily: 'verdana, arial',
                color: "#9900ff",
                axislabel: Paramlst[3],
                axislabelusecanvas: true,
                axislabelfontsizepixels: 12,
                axislabelfontfamily: 'verdana, arial, helvetica, tahoma, sans-serif',
                axislabelpadding: 3,
                min: str_arrayMin[3],
                max: str_arrayMax[3],
                tickDecimals: 0
            }, {
                position: "left",
                axislabelfontsizepixels: 12,
                axislabelfontfamily: 'verdana, arial',
                color: "#cc0099",
                axislabel: Paramlst[4],
                axislabelusecanvas: true,
                axislabelfontsizepixels: 12,
                axislabelfontfamily: 'verdana, arial, helvetica, tahoma, sans-serif',
                axislabelpadding: 3,
                min: str_arrayMin[4],
                max: str_arrayMax[4],
                tickDecimals: 0
            }, {
                position: "left",
                axislabelfontsizepixels: 12,
                axislabelfontfamily: 'verdana, arial',
                color: "#000099",
                axislabel: Paramlst[5],
                axislabelusecanvas: true,
                axislabelfontsizepixels: 12,
                axislabelfontfamily: 'verdana, arial, helvetica, tahoma, sans-serif',
                axislabelpadding: 3,
                min: str_arrayMin[5],
                max: str_arrayMax[5],
                tickDecimals: 0
            }, {
                position: "left",
                axislabelfontsizepixels: 12,
                axislabelfontfamily: 'verdana, arial',
                color: "#99ccff",
                axislabel: Paramlst[6],
                axislabelusecanvas: true,
                axislabelfontsizepixels: 12,
                axislabelfontfamily: 'verdana, arial, helvetica, tahoma, sans-serif',
                axislabelpadding: 3,
                min: str_arrayMin[6],
                max: str_arrayMax[6],
                tickDecimals: 0
            }, {
                position: "left",
                axislabelfontsizepixels: 12,
                axislabelfontfamily: 'verdana, arial',
                color: "#795548",
                axislabel: Paramlst[7],
                axislabelusecanvas: true,
                axislabelfontsizepixels: 12,
                axislabelfontfamily: 'verdana, arial, helvetica, tahoma, sans-serif',
                axislabelpadding: 3,
                min: str_arrayMin[7],
                max: str_arrayMax[7],
                tickDecimals: 0
            }
        ],
        legend: {
            noColumns: 2,
            show: true,
            canvas: true,
            labelFormatter: function (label, series) {
                return label;
            },
            backgroundColor: "white",
            backgroundOpacity: 0.9,
            labelBoxBorderColor: "#000000",
            position: "nw"  //"ne" or "nw" or "se" or "sw"             
        },
        grid: {
            hoverable: true,
            clickable: true,
            borderWidth: 1,
            //,borderWidth: 0, labelMargin: 5, axisMargin: 5, minBorderMargin: 5
            backgroundColor: { colors: ["#FFFFFF", "#FFFFFF"] }
        }
    }

    var placeholder = jt$("#flotChartplaceholder");

    // insert checkboxes 
    var i = 0, choiceContainer = jt$("#choices");
    jt$.each(dataSetP3, function (key, val) {

        val.color = i;
        ++i;
        l = val.label;
        if (l != undefined) {
            var li = jt$('<span />').appendTo(choiceContainer);
            jt$('<input name="' + l + '" id="' + l + '" type="checkbox" checked="checked" />').appendTo(li);
            jt$('<label>', {
                text: l,
                'for': l
            }).appendTo(li);
        }

    });

    plotAccordingToChoicesP3();

    choiceContainer.find("input").change(plotAccordingToChoicesP3);

    jt$('.legendColorBox > div').each(function (i) {
        jt$(this).clone().prependTo(choiceContainer.find("span").eq(i));
    });

    function plotAccordingToChoicesP3() {

        var data = [];

        choiceContainer.find("input:checked").each(function () {
            var key = this.name;

            for (var i = 0; i < dataSetP3.length; i++) {
                if (dataSetP3[i].label === key) {
                    if (dataSetP3[i].label != null) {
                        data.push(dataSetP3[i]);
                        return true;
                    }

                }
            }
        });

        if (data.length > 0) {
            //var Jq$ = jQuery.noConflict();
            if (data.length < 500) {
                jt$("#flotChartplaceholder").width(3500);
            }
            else {
                jt$("#flotChartplaceholder").width(8000);
            }
            //[{data : d8, bars: { show: true, fill: true}},{data : d9, lines: {lineWidth:5}, animator: {start:$("#start").val(), steps:$("#steps").val(), duration:$("#duration").val(), direction: $("#dir").val()}}]);
            var plot = jt$.plot(placeholder, data, optionsP3);
            jt$(placeholder).bind("plothover", function (event, pos, item) {
                jt$("#tooltip").remove();
                if (item) {
                    var x = item.datapoint[0].toFixed(2),
                       y = item.datapoint[1].toFixed(2), yvalues = item.datapoint[1];
                    var date = new Date(+x);
                    var color = item.series.color;

                    var day = date.getDate();
                    var month = date.getMonth() + 1; //months are zero based
                    var year = date.getFullYear();
                    var time = date.toLocaleTimeString('en-US', { hour12: true });
                    //date.toLocaleTimeString('en-US', { hour12: false })
                    var tooltip = "<strong>" + item.series.label + "</strong>" +
                       " : <strong>" + yvalues + "</strong><br><strong>Date</strong>:" + (day + '-' + month + '-' + year + ' ' + time)

                    jt$('<div id="tooltip">' + tooltip + '</div>')
                        .css({
                            position: 'absolute',
                            display: 'none',
                            top: item.pageY + 5,
                            left: item.pageX + 5,
                            border: '1px solid ' + color + '',
                            padding: '3px',
                            'background-color': 'white',
                            'font-family': 'Verdana, Arial, Helvetica, Tahoma, sans-serif, color:' + color + '',
                            'font-size': '9px',
                            'border-radius': '8px',
                            opacity: 0.9
                        })
                        .appendTo("body").fadeIn(200);
                }
            });
            validatedropdown();

            var myCanvas = plot.getCanvas();
            var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream");  /// here is the most important part because if you dont replace you will get a DOM 18 exception.
            var hdnChart = document.getElementById('hdnCaptureChar');
            hdnChart.value = null;
            hdnChart.value = image;
        }
    }
}
function draw() {
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(0, 0, 600, 400);
    ctx.fillStyle = 'red';
    ctx.fillRect(100, 100, 50, 50);
}
function gd(year, month, day) {
    return new Date(year, month - 1, day).getTime();
}

var previousPoint = null, previousLabel = null;


//js$.fn.UseTooltip = function () {
//    js$(this).bind("plothover", function (event, pos, item) {
//        if (item) {
//            if ((previousLabel != item.series.label) || (previousPoint != item.dataIndex)) {
//                previousPoint = item.dataIndex;
//                previousLabel = item.series.label;
//                js$("#tooltip").remove();

//                var x = item.datapoint[0].toFixed(2),
//                y = item.datapoint[1].toFixed(2);
//                var date = new Date(+x);
//                var color = item.series.color;

//                showTooltip(item.pageX, item.pageY, color,
//                            "<strong>" + item.series.label + "</strong>" +
//                            " : <strong>" + y + "</strong><br><strong>Date</strong>:" + date.toLocaleString());
//            }
//        } else {
//            js$("#tooltip").remove();
//            previousPoint = null;
//        }
//    });
//};

function showTooltip(x, y, color, contents) {
    var js$ = jQuery.noConflict();
    js$('<div id="tooltip">' + contents + '</div>').css({
        position: 'absolute',
        display: 'none',
        top: y - 40,
        left: x - 120,
        border: '2px solid ' + color,
        //xDateFormat: "%d/%m/%y %H:%M:%S",
        padding: '3px',
        'font-size': '9px',
        'border-radius': '5px',
        'background-color': 'white',
        'font-family': 'Verdana, Arial, Helvetica, Tahoma, sans-serif, color:' + color + '',
        opacity: 0.9
    }).appendTo("body").fadeIn(200);
}
