var Graph = Array();
var globGraphid = 0;


function FillText(text, inbox){
  if(document.getElementById(inbox).value == text){
    document.getElementById(inbox).value = "";
  }else{
    document.getElementById(inbox).value = text;
  }
}

function Check(){
  extra = document.getElementById('suchtext').value.split(" ");
  fund = true;
  for(i=0;i<extra.length;i++){
    if(extra[i].indexOf("Autor:") == 0){
      extra2 = extra[i].split(":");
      checkit = confirm("Sie suchen gerade in dem Text nach 'Autor:"+ extra2[1] +"', wollten Sie nicht nach Beitraegen des Autors suchen?");
      if(checkit == true){
        if(extra2.length > 1)document.getElementById('suchautor').value = extra2[1];
        document.getElementById('suchtext').value = document.getElementById('suchtext').value.replace(new RegExp("\\s*Autor:"+ extra2[1]+"\\s*"), "");
        fund=false;
      }
    }
  }
  return fund;
}

//Init Tool Tips
$(function(){
  BT_setOptions({openWait:300, closeWait:200, enableCache:false});
})

function showTooltip(x, y, contents, name) {
//document.body.offsetWidth

  $('<div id="'+ (name != null ? name : 'tooltip') +'">' + contents + '</div>').css( {
    position: 'absolute',
    display: 'none',
    top: y + 5,
    left: 0,
    border: '1px solid #fdd',
    padding: '2px',
    'background-color': '#fee',
    opacity: 1.00
  }).appendTo("body").fadeIn(200);

  if(($("#"+ (name != null ? name : 'tooltip')).attr("offsetWidth") + x) > $("body").attr("offsetWidth")) {
    $("#"+ (name != null ? name : 'tooltip')).css("left", x - $("#"+ (name != null ? name : 'tooltip')).attr("offsetWidth"));
  } else {
    $("#"+ (name != null ? name : 'tooltip')).css("left", x + 5);
  }

}

function makeDate(x) {
    var Zeit = new Date(x);

    return (Zeit.getDate() < 10 ? "0" : "") + Zeit.getDate() +"."+
    ((Zeit.getMonth()+1) < 10 ? "0" : "") +(Zeit.getMonth()+1) +"."+ (Zeit.getFullYear()) +" "+
    (Zeit.getHours() < 10 ? "0" : "") + Zeit.getHours() +":"+ (Zeit.getMinutes() < 10 ? "0" : "") + Zeit.getMinutes();
}

function findValue(data, date){
  var lastValue = null;
  var ergebnis = -1;
  var erstes = 0;
  var letztes = data.length - 1;
  var mitte = -1;
  var find = false;
  
  while(erstes <= letztes && ergebnis < 0){
    mitte = parseInt(erstes + (( letztes - erstes) / 2));
    if(parseFloat(data[mitte]) < parseFloat(date)){
      erstes = mitte + 1;
      find = true;
    }else if(parseFloat(data[mitte]) > parseFloat(date)){
      letztes = mitte - 1;
      find = true;
    }else{
      ergebnis = mitte;
    } 
  }
  //alert(mitte +":"+ erstes +":"+ letztes +":"+ ergebnis +" = ");
  if(find == false)
    return null;
  else
    return data[letztes][1];
}

function in_array(needle, hackstack){
  var ergebnis = -1;
  var erstes = 0;
  var letztes = hackstack.length - 1;
  var mitte = -1;
  
  while(erstes <= letztes && ergebnis < 0){
    mitte = parseInt(erstes + (( letztes - erstes) / 2));
    if(parseFloat(hackstack[mitte]) < parseFloat(needle)){
      erstes = mitte + 1;
    }else if(parseFloat(hackstack[mitte]) > parseFloat(needle)){
      letztes = mitte - 1;
    }else{
      ergebnis = mitte;
    } 
  }
  return ergebnis;
}

function getLoc(id){
var result = "ua="+ escape(navigator.userAgent) +"&sol="+ escape(screen.width) + "x" + escape(screen.height)
+"&java="+ escape((navigator.javaEnabled() == true ? "1" : "0"))
+"&cook="+ escape((navigator.cookieEnabled == true ? "1" : "0"))
+"&speak="+ escape(navigator.language) +"&ref="+ escape(document.referrer)
+"&os="+ escape(navigator.platform)
+"&id="+ escape(id)
+"&href="+ escape(window.location.hostname + window.location.pathname + window.location.search);
$.ajax({
url: "ajax.php",
type: "POST",
data: ({data : result}),
dataType: "html",
success: function(msg){
}
});
}
function makeMovAvg(data, graphid) {


  dummyData = [];
  plotData = [];
  
  var parts = 3;  
  
  var lastDate = null;
  var lastValue = null;
  var date;
  var value;
  var timespace;
  var len = 0;
  var val = Array();
  var dates = "";

  //Alle [Timestamp1, Value1] [Timestamp2,Value2] und diese Werte in $parts Parts unterteilen
  for(x in data.data) {
    date = parseInt(data.data[x][0]);
    value = parseInt(data.data[x][1]);
    
    if(lastDate == null){
      dummyData.push(data.data[x]);
      len++;
    }else{
      timespace = parseInt(date - lastDate);
      for(k=1, timeAdd = (timespace/parts) ; k<=parts; ++k){
        len++;
        dummyData.push([parseInt(parseInt(lastDate) + parseInt((timeAdd*k))),(k*value + (parts-k)*lastValue)/parts]);
      }
    }
    
    lastDate = date;
    lastValue = value;

    
  }
  //
  var werte;
  var count;
  var length = dummyData.length;
  var mm = 0;
  var nu = 0;
  var le = 0;

  //Gewichtung der einzelnen Werte berechnen
  for(z in dummyData){
    werte = 0;
    count = 0;
    for(min = -40; min <= 40; ++min){
      if(parseInt(parseInt(z)+parseInt(min)) > 0 && parseInt(parseInt(z)+parseInt(min)) < len){
        werte += parseInt(dummyData[parseInt(parseInt(z)+parseInt(min))][1]);
        ++count;
      }
    }
    if(count > 0) {
      plotData.push([ parseInt(dummyData[z][0]) , parseInt(werte/count) ]);
    }
  }

  dataset = {
        name: "avg",
        data: plotData,
        color: "#FF0000",
        hide: false,
        hoverAble: true,
        precision: 2,
        lines: {lineWidth: 2}
  };

  return dataset;
}

function makeAvg(data, graphid) {
  newData = [];
  date = [];

  Graph[graphid].data["0"] = [];

  if (data == null) {
    data = [];
    for(i in Graph[graphid].data) {
      if(Graph[graphid].data[i].hide == false)
        data.push(Graph[graphid].data[i]);
    }
  }

  if(data == null) return;
  
  for (i in data) {
    for(x in data[i].data) {
      if(in_array(data[i].data[x][0], date) == -1)  {
        date.push(data[i].data[x][0]);
      }
    }
  }

  //$('#graphausgabe0').html(string);
  for(x in data) {
    data[x].avgIndex = 0;
  }

  date.sort(function(a, b) { return a - b; });

  var lengther;

  for(i in date) {
    dummy = [];

    for (x in data) {
      lengther = data[x].data.length;
      lastValue = null;

      for (k=data[x].avgIndex; k<lengther; ++k) {
        if (data[x].data[k][0] > date[i])
          break;

        lastValue = data[x].data[k][1];
      }
      
      //lastValue = findValue(data[x].data, date[i]);

      if (lastValue != null)
        dummy.push(lastValue);
    }

    if (dummy.length > 0) {
      sum = 0;
      for (j in dummy) sum += dummy[j];
      newData.push([date[i], sum / dummy.length]);
    }

  }

  dataset = {
        name: "Durchschnitt",
        data: newData,
        color: "#000000",
        hide: false,
        hoverAble: true,
        identifier: " EUR",
        precision: 4,
        lines: {lineWidth: 4},
        price: 0
  };
  Graph[graphid].data["0"] = dataset;
  if(newData.length > 0)
    Graph[graphid].data["0"].price = newData[newData.length-1][1];
  else
    Graph[graphid].data["0"].price = 0;

  $("#graph"+ graphid +"avg0").html(parseFloat(Graph[graphid].data["0"].price*100).toFixed(2) +' ct./Mio.');
  //Graph[graphid].data["0"].price = newData[newData.length-1][1];


}


/*

Data Convention:
Data[index].data
            .options
Graph[graphid].data[index][data][label][color][others][hide][name][precision][hoverAble][identifier][divide][noToolTip][avgIndex]
Graph[graphid].options
Graph[graphid].selectAble?
Graph[graphid].hoverAble?
Graph[graphid].choiceAble?
Graph[graphid].durchschnitt?
Graph[graphid].lines = true;
Graph[graphid].points = true;
Graph[graphid].previousPoint = null;
Graph[graphid].yAxisIdentifier = "EUR";
Graph[graphid].yAxisPrecision = 4;
Graph[graphid].yAxisDivide = 1;
Graph[graphid].beginDate = 123456789;
Graph[graphid].endDate = 123456789;


Namensgebungen:
#graph'+ graphid
#reset'+ graphid
#tooltip'+ graphid
#choices'+ graphid
#showSite'+ graphid

Choices'+ graphid +'#
  <tr>: #graph'+ graphid +'row'+ key
  <td>: #graph'+ graphid +'Site'+ key
  <input>: #graph'+ graphid +'check' + key
  <span>: #graph'+ graphid +'checkSite'+ key
*/

function makeDefaultGraph(Graph, id){
  Graph[id] = Array();

  Graph[id].backgroundColor = "#ffffff";
  Graph[id].selectAble = true;
  Graph[id].hoverAble = true;
  Graph[id].clickAble = true;
  Graph[id].choiceAble = false;
  Graph[id].durchschnitt = false;
  Graph[id].resetAble = true;
  Graph[id].lines = true;
  Graph[id].points = false;
  Graph[id].previousPoint = null;
  Graph[id].yAxisIdentifier = null;
  Graph[id].yAxisPrecision = 0;
  Graph[id].yAxisDivide = null;
  Graph[id].beginDate = null;
  Graph[id].endDate = null;

  return Graph;

}

function numberformat(val, divide, precision, identifier) {
 rueck = "";

  //Zur Skalierung
  if(divide != null && divide != 1)
    val = (parseFloat(val)/divide);
  else
    val = parseFloat(val);

  //Nachkommastellen
  if(precision != null)
    val = val.toFixed(precision);
  isNeg = false;
  if(val < 0){
    val = val*(-1);
    isNeg = true;
  }

  //Nachkommateil speichern und später wieder anfügen.
  val = String(val);
  if (val.indexOf(".") != -1) {
    number = val.substring(0, val.indexOf("."));
    float = val.substring(val.indexOf(".")).replace(".",",");
  } else {
    number = val;
    float = "";
  }

  //Alle 3 Stellen einen Punkt setzenent
  for (i=0; i<number.length; i++) {
    rueck = number.charAt(number.length-i-1) + rueck;
    if((i+1)%3==0 && i !== number.length-1)
      rueck = "."+ rueck;
  }

  rueck += float;
  if(isNeg) rueck = "-"+ rueck;
  return rueck.toString() + (identifier != null ? ' '+ identifier : '');
}

function plotGraph(graphid, Graph) {

  $(function () {

    function formatYAxis(val, axis) {
      return format(val, Graph[graphid].yAxisDivide, Graph[graphid].yAxisPrecision, Graph[graphid].yAxisIdentifier);
    }

    function format(val, divide, precision, identifier) {
      rueck = "";

      //Zur Skalierung
      if(divide != null && divide != 1)
        val = (parseFloat(val)/divide);
      else
        val = parseFloat(val);

      //Nachkommastellen
      if(precision != null)
        val = val.toFixed(precision);
      isNeg = false;
      if(val < 0){
        val = val*(-1);
        isNeg = true;
      }

      //Nachkommateil speichern und später wieder anfügen.
      val = String(val);
      if (val.indexOf(".") != -1) {
        number = val.substring(0, val.indexOf("."));
        float = val.substring(val.indexOf(".")).replace(".",",");
      } else {
        number = val;
        float = "";
      }

      //Alle 3 Stellen einen Punkt setzenent
      for (i=0; i<number.length; i++) {
        rueck = number.charAt(number.length-i-1) + rueck;
        if((i+1)%3==0 && i !== number.length-1)
          rueck = "."+ rueck;
      }

      rueck += float;
      if(isNeg) rueck = "-"+ rueck;
      return rueck.toString() +" "+ (identifier != null ? identifier : '');
    }

    function setTimeFormat(begin, end, options) {
      var spandays = Math.floor((end - begin)/86400000);
      if (spandays < 1) {
        options["xaxis"] = { mode: "time", timeformat: "%H:%M"};
      } else if (spandays >= 1 && spandays <= 4) {
        options["xaxis"] = { mode: "time", timeformat: "%d.%m %H:%M"};
      } else if (spandays >= 4) {
        options["xaxis"] = { mode: "time", timeformat: "%d.%m.%y"};
      }
      return options;
    }

    var options = {
        grid : {},
        lines : false,
        lines : false,
        selection: { mode: "xy" },
        xaxis:  { mode: "time" },
        yaxis:  { tickFormatter: formatYAxis }
    };

    if (Graph[graphid].hoverAble)
      options["grid"] = {hoverable: true};
    if (Graph[graphid].clickAble)
      options["grid"]["clickable"] = true;
    if (Graph[graphid].lines)
      options["lines"] = {show: true};
    if (Graph[graphid].points)
      options["points"] = {show: true};
    if (Graph[graphid].backgroundColor != null)
      options["grid"]["backgroundColor"] = Graph[graphid].backgroundColor;

    //Anhand des Zeitraums wird die "Date" - Beschreibung festgelegt
    var lowTime = 0;
    var maxTime = 0;
    for (i in Graph[graphid].data) {
      for (x in Graph[graphid].data[i].data) {
        if (lowTime == 0 || lowTime > Graph[graphid].data[i].data[x][0])
          lowTime = Graph[graphid].data[i].data[x][0];
        if (maxTime == 0 || maxTime < Graph[graphid].data[i].data[x][0])
          maxTime = Graph[graphid].data[i].data[x][0];
      }
    }
    Graph[graphid].beginDate = lowTime;
    Graph[graphid].endDate = maxTime;
    options = setTimeFormat(Graph[graphid].beginDate, Graph[graphid].endDate, options);

    if (Graph[graphid].durchschnitt)
      makeAvg(null, graphid);

    if (Graph[graphid].choiceAble) {
      var choiceContainer = $("#choices"+ graphid);
      var str="";
      var setrank = 0;
      var lastrank = 0;
      var last = 0;
      $.each(Graph[graphid].data, function(key, val) {
        if (last == 0 && val.name != "Durchschnitt" || last != val.price && val.name != "Durchschnitt") {
          ++setrank;
        }
        var rank = setrank;
        var idg = graphid;
        
        str="";
        str += '<tr id="graph'+ graphid +'row'+ key +'">';
        str += '<td id="graph'+ graphid +'Site'+ key  +'" style="display:inline;vertical-align:top;color:'
            + (val.name == "Durchschnitt" ? "#000000" : "#00008B") +';">';
        (val.name != "Durchschnitt" ? str += '<input type="checkbox" id="graph'+ graphid +'check' + key +'" name="'
            + key +'" '+ (String(val.hide) == "true" ? '' : 'checked="checked"') +' style="padding:0px;margin:0px;border-style:none;color:'+ val.color +';"/>' : '');
        str += '<div class="quad" style="background-color:'+ val.color +';">&nbsp;';
        
        str += (parseInt(last*1000) == parseInt(val.price*1000) ? '"' : rank);
        str += '&nbsp;</div>';
        str += '&nbsp;<span id="graph'+ graphid +'checkSite'+ key +'" style="display:inline;"> ';
        str += (val.name != "Durchschnitt" && Graph[idg].yAxisIdentifier == " EUR" ? '<a href="index.php?mode=Losepreis&p='+ val.name +'&b='+ (graphid+1) +'" target="_blank">' : '');
        str += val.name ;
        str += (val.name != "Durchschnitt" && Graph[idg].yAxisIdentifier == " EUR" ? '</a>' : '');
        str += ' </span>';
        if (val.price) {
          str += '</td>';
          str += '<td id="graph'+ graphid +'avg'+ key +'" style="text-align:right;color:#000000;">';
          str += (setrank == '"' ? '"' : parseFloat(val.price*100).toFixed(2) +' ct./Mio.' );
          str += '</td>';
        } else {
          str += '</td>';
          str += '<td style="width:0px;text-align:right;color:#000000;">';
          str += '</td>';
        }
        str += '</tr>';

        last = parseFloat(val.price);

        choiceContainer.append(str);
        $("#graph"+ graphid +"check"+ key).click(function(){
          if (Graph[graphid].data[key].hide)
            Graph[graphid].data[key].hide = false;
          else
            Graph[graphid].data[key].hide = true;
            plotIt();
        });

        if (val.hoverAble) {
          $("#graph"+ graphid +"row"+ key).hover(function(){
            $("#showSite"+ graphid).css("visibility", "visible");
            $("#graph"+ graphid +"row"+ key).attr("style", "background-color:#A9A9F5");
            $("#showSite"+ graphid).attr("innerHTML", '<span class="shop"><span class="quad" style="background-color:'+ val.color +';">'+ rank +'</span> '+ val.name
            +'<br/>&nbsp;&nbsp;'+ (val.link != null ? '<a href="'+ val.link +'" target="_blank">Zur Website</a>' : '' ) +'<br/>'
            + (val.amount > 0 ? '&nbsp;&nbsp;Akt. Menge: '+ String(parseFloat(val.amount/1000000000).toFixed(2)).replace(".", ",") +' MRD.<br>' : '')
            +'</span>');
          }, function(){
            $("#graph"+ graphid +"row"+ key).attr("style", "background-color:#CECEF6;;");
          });
        }
      });
    }

    function plotIt() {

      //Hier werden die wirklich gezeichneten Daten zwischen gespeichert
      var data = [];
      var dummy = null;

      if (Graph[graphid].durchschnitt)
        makeAvg(null, graphid);

      //ueberprüft und schreibt die Data, welche nicht gehided werden sollen
      for (i in Graph[graphid].data) {
        dummy = null;
        if (Graph[graphid].data[i].movAvg != null && Graph[graphid].data[i].movAvg == true && Graph[graphid].data[i].hide == false){
          dummy = makeMovAvg(Graph[graphid].data[i], graphid);
          if(dummy.length != 0)
            data.push(dummy);
        }
        if (Graph[graphid].data[i].hide == false)
          data.push(Graph[graphid].data[i]);

      }
      data.reverse();
      if (data.length == 0) data.push({"leer":{data:[[new Date().getTime(),1]]}});
      if (data.length > 0)
        plot = $.plot($("#graph"+ graphid), data, options);

      if (Graph[graphid].selectAble) {
        $("#graph"+ graphid).bind("plotselected", function (event, ranges) {
          options = setTimeFormat(ranges.xaxis.from, ranges.xaxis.to, options);
          $("#reset"+ graphid).attr("disabled", "");
          plot = $.plot($("#graph"+ graphid), data,
          $.extend(false, options, {
            xaxis: $.extend(false, options.xaxis, { min: ranges.xaxis.from, max: ranges.xaxis.to }),
            yaxis: $.extend(false, options.yaxis, { min: ranges.yaxis.from, max: ranges.yaxis.to })
          }));
        });

      }

      if (Graph[graphid].selectAble) {
        $("#reset"+ graphid).click(function() {
          $("#reset"+ graphid).attr("disabled", "disabled");
          options = setTimeFormat(Graph[graphid].beginDate, Graph[graphid].endDate, options);
          $.plot($("#graph"+ graphid), data, options);
        });
      }

      if (Graph[graphid].clickAble) {
        $("#graph"+ graphid).bind("plotclick", function (event, pos, item) {
            if (item) {
              var x = item.datapoint[0];
              var y = parseFloat(item.datapoint[1]).toFixed(item.series.precision);
              if (item.series.otherData != null)
                y = item.series.otherData[item.dataIndex];
              if ($("#graphausgabe"+ graphid) != null) $("#graphausgabe"+ graphid).html(item.series.name + " ("+
                makeDate((item.series.correctDate != null ? x+item.series.correctDate : x)) +") : " +
                format(y, (item.series.divide != null ? item.series.divide : 1),
                (item.series.precision != null ? item.series.precision : 0),
                (item.series.identifier != null ? item.series.identifier : null)));
            }
        });
      }

      if (Graph[graphid].hoverAble) {
        $("#graph"+ graphid).bind("plothover", function (event, pos, item) {
          if (item) {
            if (Graph[graphid].previousPoint != item.datapoint) {
              Graph[graphid].previousPoint = item.datapoint;

              $("#tooltip"+ graphid).remove();
              var x = item.datapoint[0];
              var y = parseFloat(item.datapoint[1]).toFixed(item.series.precision);
              if (item.series.otherData != null)
                y = item.series.otherData[item.dataIndex];

              if (!item.series.noToolTip)
                showTooltip(item.pageX, item.pageY, item.series.name + " ("+ makeDate((item.series.correctDate != null ? x+item.series.correctDate : x)) +") : "
                          + format(y, (item.series.divide != null ? item.series.divide : 1),
                                      (item.series.precision != null ? item.series.precision : 0),
                                      (item.series.identifier != null ? item.series.identifier : null)), "tooltip"+ graphid);
            }
          } else {
              $("#tooltip"+ graphid).remove();
              Graph[graphid].previousPoint = null;
          }
        });
      }
    }

    //Damit der Graph das erste mal gezeichnet wird.
    plotIt();

  });
}



