// Stokersoft graph engine powered by Flot (C)2010 Stokersoft

function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}


function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}



function setInitialized(initialized) {
    window.isInitialized = initialized;
}

function getInitialized() {
    return window.isInitialized;
}


function setChoices(choices) {
    window.choices = choices;
}

function getChoices() {
    return window.choices;
}

function setSeries(series) {
    window.series = series;
}

function getSeries() {
    return window.series;
}

function setBarSeries(series) {
    window.barSeries = series;
}

function getBarSeries() {
    return window.barSeries;
}


function init() {
  setInitialized('false');
  fetchData();
  fetchBarData();
  setInterval(fetchData, 5000);  
  setInterval(fetchBarData, 100000);  
  
}

function rgbConvert(str) {
  str = str.replace(/rgb\(|\)/g, "").split(",");
  str[0] = parseInt(str[0], 10).toString(16).toLowerCase();
  str[1] = parseInt(str[1], 10).toString(16).toLowerCase();
  str[2] = parseInt(str[2], 10).toString(16).toLowerCase();
  str[0] = (str[0].length == 1) ? '0' + str[0] : str[0];
  str[1] = (str[1].length == 1) ? '0' + str[1] : str[1];
  str[2] = (str[2].length == 1) ? '0' + str[2] : str[2];
  return ('#' + str.join(""));
}

// plots after a click in the checkboxes.
// Stores the state of the checkboxes in cookies.
function plotAfterClick() {
  var choiceContainer = getChoices();
  var now = new Date();
  now.setTime(now.getTime() + 1000 * 60 * 60 * 24 * 365); // One year ahead
  var i = 0;
  choiceContainer.find("input").each(function () {
    var key = $(this).attr("name");
    var value = $(this).attr("checked");
    if (key!='') {
      setCookie('skv3_' + i, value, now);
      i++;  
    }
  });
  plotAccordingToChoices();
}

function plotAccordingToChoices() {
                       var data = [];
                       var choiceContainer = getChoices();
                       var datasets = getSeries(); 
                       var formatLabel = function(l, s) {
                       	  return '<font size="1">' + l + '</font>';
                       };


                       var options = {
	                       grid: { backgroundColor: { colors: ["#000", "#999"] } },
			               xaxis: { mode: "time", autoscaleMarginX: 0.2 },
			               legend: {
                                       show: false,
                                       margin: 5,
                                       position: "nw",
                                       backgroundOpacity:0.5, 
			               labelFormatter: formatLabel   
                                     }

                       };
                        
                       choiceContainer.find("input:checked").each(function () {
                       var key = $(this).attr("name");
                       if (key && datasets[key])
                          data.push(datasets[key]);
                       });

 
                       if (data.length > 0) {
                         $.plot($("#driftchart"), data, options);
		       }
                                           
}

function fetchData() {

	    function onErrorReceived(error) {
	      alert(error);
	    }

            function onDataReceived(series) {
		// we get all the data in one go, if we only got partial
                // data, we could merge it with what we already got
       		data = [ series ];
                setSeries(series);
                if (getInitialized()=='false') {            
                   // insert checkboxes 
                   var choiceContainer = $("#choices");
                   var i = 0;
                   $.each(series, function(key, val) {
                     var keyColor = rgbConvert(val.color);
                     var checked;
                     if (getCookie('skv3_' + i)=='false') {
                       checked = '';
                     } else {
                       checked = 'checked';
                     }
                     
                     choiceContainer.append('<input type="button" style="background-color:' + keyColor +';width:15px; height:15px" value="" disabled="disabled"><input type="checkbox" name="' + key +
                               '" ' + checked + ' id="id' + key + '">' +
                               '<label for="id' + key + '">'
                                + val.label + '</label><br/>');
                     i++;
                   });
                   choiceContainer.find("input").click(plotAfterClick);
                   setChoices(choiceContainer);

                   setInitialized('true');
                }
                plotAccordingToChoices();
            }
        
            $.ajax({
                url: 'drift24.txt?' + new Date().getTime(),
                method: 'GET',
                dataType: 'json',
                success: onDataReceived,
		error:function (xhr, ajaxOptions, thrownError){
                    alert(xhr.status);
                    alert(thrownError);
                }   
            });
            
};




function plotBarData() {
                       var data = [];
                       var datasets = getBarSeries(); 

                       var baroptions = {
	                       grid: { backgroundColor: { colors: ["#000", "#999"] } },
			       xaxis: {mode: "time",
			       timeformat: "%d/%m"},
			       fill: true
                       };
                        
                       data.push(datasets[0]);
 
                       if (data.length > 0) {
                         $.plot($("#consumechart"), data, baroptions);
		       }
                                           
}


function fetchBarData() {

            function onBarDataReceived(series) {
      		data = [ series ];
                setBarSeries(series);
                plotBarData();
            }
        
            $.ajax({
                url: 'consume30.txt?' + new Date().getTime(),
                method: 'GET',
                dataType: 'json',
                success: onBarDataReceived
            });
            
};

