// *** TRENDS *** //
function trendCallback(data){      
  // locate the binding based on the inbound data
  tb = OPC.Trend.getTrendBinding(data);
  var grid_options = {
    series: { shadowSize: 2}, // drawing is faster without shadows
    lines:  { show: true, fill: true }, 
    grid: {  hoverable: true, clickable:true, autoHighlight: false, backgroundColor:"#FFE"},
    crosshair: { mode: "x"},
    legend: { backgroundOpacity: 0.3},
    xaxis: {
      mode: "time",
      font: { size: 10, lineHeight: 10, family: "sans-serif", color:"#000000" },
      tickSize: [2, "second"],
      tickFormatter: function (v, axis) {
        // display axis label every 30 seconds
        // format label to include date and time
        // only show in "trend" mode - not "history"
        var dt = new Date(v);
        if (tb.mode == "trend" && dt.getSeconds() % 30 == 0) {
          return OPC.Util.formatDate(dt,"mm/dd/yyyy hh:MM:ss")
        }
        return "";
      }
    },
    yaxes: [
      { position: 'left', min:0, max:100 }, 
      { position: 'left', min:-1, max:1  }, 
      { position: 'left', min:0, max:100  }
    ]
  };
  // set axes based on mode
  if (tb.mode == "history") { 
    setHistoryAxes(data); 
  }
  else {
    clearHistoryAxes(data); 
  }
  // format the data as a Flot series
  fd = OPC.Flot.buildTrendData(data);
  // call $.plot to draw the chart
  $.plot("#" + tb.chartid, fd, grid_options);
}


// hide the tooltip element
function hideToolTip(){ $("#tooltip").hide(); }

// show tooltip on demand
function showToolTip(item){
  hideToolTip(); 
  tt = $("#tooltip")
  if (tt.length == 0) {
    // create tooltip element if it doesn't exist
    tt = $("<div id='tooltip' style='position:absolute;z-index:9999;border:2px solid #fff;padding:2px;background-color:#666;color:#fff;box-shadow:2px 2px 2px 0px rgba(0,0,0,0.2);'></div>")
    $("body").append(tt)
    tt.hide();
  }
  $("#tooltip").css("background-color",item.series.color);
  var x = item.datapoint[0].toFixed(2);
  var dt = new Date(parseInt(x));
  var dtf = OPC.Util.formatDate(dt,"hh:MM:ss&nbsp;aa");
  var y = item.datapoint[1].toFixed(2);

  $("#tooltip").html(dtf + " = " + y).css({
    top: item.pageY + 5, 
    left: item.pageX + 5
  }).fadeIn(200);
}
      
// display history axes for just start and end time since
//  data points may be spread over a long period of time
function setHistoryAxes(data){
  var ha = $("<div id='historyAxes'></div>");
  $("#trend-outer").append(ha);
  sd = $("<div style='float:left;'>" + OPC.Util.formatDate(data.firsttime, "mm/dd/yyyy<br/>hh:MM:ss&nbsp;aa") + "</div>");
  ed = $("<div style='float:right;'>" + OPC.Util.formatDate(data.lasttime, "mm/dd/yyyy<br/>hh:MM:ss&nbsp;aa") + "</div>");
  ha.append(sd).append(ed).append($("<div stye='clear:both;'></div>"));
  var hah = sd.outerHeight();
  var tb = OPC.Trend.getTrendBinding(data);
  $("#" + tb.chartid).height($("#" + tb.chartid).height() - hah);
}
function clearHistoryAxes(data){
  $("#historyAxes").remove();
  var tb = OPC.Trend.getTrendBinding(data);
  $("#" + tb.chartid).css("height","100%");
}
function validDate(d) {
  if ( Object.prototype.toString.call(d) === "[object Date]" ) {
    if ( !isNaN( d.getTime() ) ) {
      return true;
    }
  }
  return false;
}

function initTrends() {
  window.previousPoint = null;
  // 'plothover' event is fired by Flot when mouse hovers over
  //  any plot points on the chart
  $("#trend1").bind("plothover", function (event, pos, item) {
    // item represents the plot point
    if (item) {
      if (previousPoint != item.dataIndex) {
        previousPoint = item.dataIndex;
        showToolTip(item)
        // stop the OPC Trend data calls to the server
        if (OPC.is_refreshing()) OPC.toggle_refresh(false);
      }
    } else {
      // restart refreshes
      if (!OPC.is_refreshing()) OPC.toggle_refresh(true);
      hideToolTip();
      previousPoint = null;            
    }
  });

  $("#showHistory").unbind("click");  
  $("#showHistory").click(function(){
    try {
      dts = new Date($("#startDate").val())
      dte = new Date($("#endDate").val())
      if (validDate(dts) && validDate(dte)){
        OPC.Trend.getHistoryData("trend1",dts,dte);
      }
      $("#showHistory").hide();
      $("#resumeTrend").show();
    }
    catch(err) {
      alert(err.message);
    }
  });
  $("#resumeTrend").unbind("click");
  $("#resumeTrend").click(function(){
    OPC.Trend.resumeTrendData("trend1");
    $("#showHistory").show();
    $("#resumeTrend").hide();
  });


  $("#showHistory").show();
  $("#resumeTrend").hide();
}