// Set up our one global variable if it isn't present
// IE Breaks with this
//if (!window.hasOwnProperty('carbon_culture')) {
//  window.carbon_culture = {}
//}

// Using growing white boxes everywhere rather than shrinking ones, just for IE.
carbon_culture.realtime_animation_value = 0;
carbon_culture.paper = null; // Initialised later
carbon_culture.interval = null; // Initialised each time the real-time data animates
carbon_culture.realtime_bar = null;
carbon_culture.realtime_animate_bar = null;
carbon_culture.already_fetched_history = false;
carbon_culture.already_fetched_realtime = false;
carbon_culture.realtime_energy = ''; // Initialised each time the real-time data bar starts again
carbon_culture.elec_max = 0;
carbon_culture.next_elec_max = 0;
carbon_culture.gas_max = 0;
carbon_culture.next_gas_max = 0;
carbon_culture.event_loop_steps = 80;
carbon_culture.ie_gt_7 = false;
carbon_culture.event_loop_time = 20;
carbon_culture.units = 'energy';
carbon_culture.max = 740;
carbon_culture.top_offset = 0;
carbon_culture.bottom_offset = 0;
carbon_culture.event_loop_counters = {tick: 0, realtime: 0, unit: 0, realtime_tick: 0}
carbon_culture.bars = []; // Initialised later
carbon_culture.graph_width = 258;
carbon_culture.graph_height = 120;
carbon_culture.realtime_bar_width = 60;
carbon_culture.static_url = 'http://webarchive.nationalarchives.gov.uk/+/http://decc.carbonculture.net/static/';
carbon_culture.feed_url = 'http://webarchive.nationalarchives.gov.uk/+/http://decc.carbonculture.net/';
carbon_culture.cc_url = 'http://webarchive.nationalarchives.gov.uk/+/http://www.carbonculture.net/orgs/decc/';
carbon_culture.feedback_url = 'http://webarchive.nationalarchives.gov.uk/+/http://decc.carbonculture.net/feedback/';
carbon_culture.variant = '';
carbon_culture.epor_colour_band = function(proportion) {
    var colour;
    if (proportion < 0.1) {
        colour = '#0E6A36';
    } else if (proportion < 0.2) {
        colour = '#109748';
    } else if (proportion < 0.3) {
        colour = '#84B841';
    } else if (proportion < 0.4) {
        colour = '#FBC622';
    } else if (proportion < 0.6) {
        colour = '#F3A554';
    } else if (proportion < 0.8) {
        colour = '#E96C25';
    } else {
        colour = '#DD1F26';
    }
    return colour;
};
carbon_culture.on_new_loop = function() {
    var self = carbon_culture;
    if (self.event_loop_counters.unit === 0) {
        self.units = 'energy'
        jQuery('div.rtd-reading').html(Math.floor(self.make_total(self.elec_max, self.gas_max, 'energy')))
        jQuery('div.rtd-units').html('units<br />per hour');
        jQuery('div p.rtd-normal').html('This is our total energy demand right now.');
    } else if (self.event_loop_counters.unit === 1) {
        self.units = 'co2';
        jQuery('div.rtd-reading').html(self.make_total(self.elec_max, self.gas_max, 'co2').toFixed(2));
        jQuery('div.rtd-units').html('kg CO<sub>2</sub><br />per hour');
        jQuery('div p.rtd-normal').html('This is the CO<sub>2</sub> impact of our energy use.');
    } else if (self.event_loop_counters.unit === 2){
        self.units = 'money';
        jQuery('div.rtd-reading').html('&pound;'+self.make_total(self.elec_max, self.gas_max, 'money').toFixed(2));
        jQuery('div.rtd-units').html("per hour");
        jQuery('div p.rtd-normal').html('This is the money we are spending on energy.');
    } else {
        alert('Unknown units')
    }
};
carbon_culture.on_start_bar = function() {
    var self = carbon_culture;
    var animation_length = 3600;
    self.elec_max = self.next_elec_max;
    self.gas_max = self.next_gas_max;
    self.realtime_animation_value = 0;
    var proportion = self.make_total(self.elec_max, self.gas_max, 'energy')/self.max;
    var colour = self.epor_colour_band(proportion);
    var bar_area_height = self.graph_height-self.top_offset;
    var bar_height = bar_area_height * proportion;
    var gap_at_top = bar_area_height - bar_height;
    if (proportion > 1) {
        animation_length = 1900;
    }
    self.realtime_animate_bar.attr({height: 0});
    self.realtime_bar.attr({
        "x": self.graph_width-self.realtime_bar_width-1,
        "width": self.realtime_bar_width,
        "y": self.graph_height, 
        "height": 0, 
        "fill": colour,
        "fill-opacity": 1
    }); // Could use a gradient here {gradient: '90-#526c7a-#64a0c1'}; 
    self.realtime_bar.animate({y: self.top_offset+gap_at_top, height: bar_height}, animation_length);
    self.realtime_energy.attr({"y": self.graph_height-10, "height": 0}).toFront();
    var counter_max_height = self.top_offset+gap_at_top-10;
    if (!self.ie_gt_7) {
        self.realtime_energy.animate({y: counter_max_height}, animation_length);
    }
};

carbon_culture.log = function(msg) {
    //jQuery('#rtd-debug').html(msg+'<br />'+jQuery('#rtd-debug').html());
    //console.log(msg);
};

carbon_culture.on_tick = function() {
    // Increment the value for the realtime bar
    var self = carbon_culture;
    var total = self.make_total(self.elec_max, self.gas_max, 'energy');
    self.realtime_animation_value += (total/((3600/5000)*self.event_loop_steps))*4;
    if (self.realtime_animation_value > total-1) {
        self.realtime_animation_value = total;
        self.realtime_energy.attr({"text": Math.floor(self.realtime_animation_value/(60*60/5)*1000) + ' Wh'});
    } else {
        self.realtime_energy.attr({"text": Math.floor(self.realtime_animation_value/(60*60/5)*1000) + ' Wh'});
    }
    if (self.realtime_energy.attr("y") < 12 ){
        self.realtime_energy.stop();
        self.realtime_energy.attr({"y": 12});
    }
};
carbon_culture.on_animate_bar = function() {
    var self = carbon_culture;
    // Stop the animation if it hasn't already stopped
    self.realtime_energy.stop()
    self.realtime_bar.stop()
    self.realtime_bar.attr("fill-opacity", 0.7);
    var x = self.realtime_bar.attr("x")
    self.realtime_animate_bar.attr({
        fill: "white",
        x: x+self.realtime_bar.attr("width")+1,
        y: self.realtime_bar.attr("y")-1,
        height: self.realtime_bar.attr("height")+2,
        width: 0
    }).toFront();
    self.realtime_bar.animate({
        "x": x-17
        //"fill-opacity": 0.1
    }, 1000);
    self.realtime_animate_bar.animate({
        "x": x-17, 
        "width": self.realtime_bar.attr("width")+2+16
    }, 1000).toFront();
};
carbon_culture.tick = function() {
    var self = carbon_culture;
    // First call all the events
    // In the body of code below, tick goes from 0-79, realtime goes from 0-3 and unit goes from 0-2,
    self.log( "Tick: " + self.event_loop_counters.tick + " Realtime: " + self.event_loop_counters.realtime + " Unit: " + self.event_loop_counters.unit + " Realtime tick: " + self.event_loop_counters.realtime_tick);
    if (self.event_loop_counters.tick === 0) {
        // When a new loop starts
        self.on_new_loop();
    }
    // Now let's create a per-realtime loop counter:
    // 4 times a loop
    if (self.event_loop_counters.realtime_tick === 0) {
        self.on_start_bar();
    }
    if (self.event_loop_counters.realtime_tick === 16) {
        self.on_animate_bar();
    }
    if (true) {
        // Every tick
        self.on_tick();
    }
    // Now update all counters
    if (self.event_loop_counters.tick === 79) {
        self.event_loop_counters.unit += 1;
        if (self.event_loop_counters.unit === 3){
            self.event_loop_counters.unit = 0;
        }
    }
    if (self.event_loop_counters.tick === self.event_loop_steps-1) {
        self.event_loop_counters.tick = 0;
    } else {
        self.event_loop_counters.tick += 1
    }
    if (self.event_loop_counters.tick % ((self.event_loop_steps/4)) === 0) {
        if (self.event_loop_counters.realtime === 3) {
            self.event_loop_counters.realtime = 0;
        } else {
            self.event_loop_counters.realtime += 1;
        }
    }
    self.event_loop_counters.realtime_tick = self.event_loop_counters.tick - (self.event_loop_counters.realtime * 20);
};
carbon_culture.draw_graph_bars = function(paper, width, height, h, max) {
    var self = carbon_culture;
    var graph = paper.set()
    var scale = height/max;
    var bar_width = 1;
    var hist = h.reverse().slice(0, width)
    for (var i=1; i<hist.length+1; i++) {
        var x1 = (i*bar_width);
        var x2 = ((i+1)*bar_width);
        var y1 = height-(scale*hist[(hist.length)-i][0])+self.top_offset;
        var y2 = height+self.top_offset;
        var bar_height = y2-y1;
        var rect = paper.rect(x1, y1, bar_width, bar_height);
        var proportion = bar_height/height;
        var colour = self.epor_colour_band(proportion);
        self.bars.push(rect);
        if (bar_height > height) {
            color = "#a90505";
            //var c = paper.circle(x1+1, 3, 3);
            //c.attr({"fill": "red", "stroke": 0});
            //self.bars.push(c);
        }
        rect.attr({"fill": colour, "stroke": 0});
    };
};
carbon_culture.add_html = function(elem_id) {
    var self = carbon_culture;
    var widget_html = '';
    if (self.variant === 'decc.gov.uk') {
        widget_html += '  <div class="rtd-border-no-logo">\n';
    } else {
        widget_html += '  <div class="rtd-border">\n';
    }
    widget_html += '    <div class="rtd-std">\n';
    widget_html += '      <div class="rtd-title">\n';
    widget_html += '        DECC\'s Real-time Energy Use\n';
    widget_html += '      </div>\n';
    widget_html += '    </div>\n';
    widget_html += '    <div class="rtd-std">\n';
    widget_html += '      <div class="rtd-section">\n';
    widget_html += '        <div class="rtd-total">\n';
    widget_html += '            <div class="rtd-reading"><span style="color: #eee">Loading...</span></div>\n';
    widget_html += '            <div class="rtd-units"></div>\n';
    widget_html += '            <div class="rtd-clear"></div>\n';
    widget_html += '        </div>\n';
    widget_html += '      </div>\n';
    widget_html += '      <div class="rtd-section">\n';
    widget_html += '        <p class="rtd-normal">This is the money we are spending on energy</p>\n';
    widget_html += '      </div>\n';
    widget_html += '      <div class="rtd-std">\n';
    widget_html += '        <div class="rtd-graph">\n';
    widget_html += '          <div id="graph"></div>\n';
    widget_html += '        </div>\n';
    widget_html += '        <div class="rtd-clear"></div>\n';
    widget_html += '      </div>\n';
    widget_html += '      <div class="rtd-label">\n';
    widget_html += '        <div class="rtd-history_line"><div class="rtd-history_label">The last 24 hours</div></div>\n';
    widget_html += '        <div class="rtd-realtime_line"><div class="rtd-realtime_label">5 seconds</div></div>\n';
    widget_html += '        <div class="rtd-clear"></div>\n';
    widget_html += '       </div><br /><br />\n';
    widget_html += '    </div>\n';
    widget_html += '    <div class="rtd-footer">\n';
    widget_html += '	  <div style="float: left;">\n';
    widget_html += '	    <p><a target="_parent" href="http://webarchive.nationalarchives.gov.uk/+/http://decc.gov.uk/en/content/cms/about/low_carbon/low_carbon.aspx">Learn more about this</a></p>\n';
    widget_html += '        <p><a target="_parent" href="'+self.feedback_url+'">Submit feedback</a></p>\n';
    widget_html += '      </div>\n';
    widget_html += '      <div style="float: right;">\n';
    if (self.variant === 'decc.gov.uk') {
        widget_html += '        <a target="_parent" href="'+self.cc_url+'" class="rtd-powered-by">Powered by<br />CarbonCulture</a>\n';
    } else {
        widget_html += '        <a target="_parent" href="'+self.cc_url+'" class="rtd-no-border"><img id="cc-logo" src="'+self.static_url+'carbon-culture-logo-mask.gif" class="rtd-no-border" /></a>\n';
    }
    widget_html += '      </div>\n';
    widget_html += '       <br /><br />\n';
    widget_html += '    </div>\n';
    widget_html += '  </div><div id="rtd-debug"></div>\n';
    jQuery('#'+elem_id).html(widget_html);
};
carbon_culture.fetch_history = function() {
  var self = carbon_culture;
  self.log("Fetching history");
  jQuery.jsonp({
    url: self.feed_url+"daq/decc/history/?channels=decc-elec,main-gas",
    timeout: 8000,
    callbackParameter: 'callback',
    callback: 'decc_history',
    success: function(json, two){
      var total;
      if (json.length) { 
          h = json;
          var data = [];
          for (var i=0; i<h.length; i++) {
              total = self.make_total(h[i][0], h[i][1], 'energy', true)
              data.push([total]);
          }
          for (var i=0; i<carbon_culture.bars.length; i++) {
            carbon_culture.bars[i].remove();
          }
          carbon_culture.bars = [];
          self.already_fetched_history = true;
          self.draw_graph_bars(self.paper, self.graph_width-self.realtime_bar_width-20, self.graph_height, data, self.max);
      };
      // Set off the realtime graph
      if (!self.already_fetched_realtime){
        self.already_fetched_realtime = true;
        self.log("Triggering realtime fetch loop");
        self.set_next_max();
        setInterval("carbon_culture.set_next_max()", 5000);
      }
    },
    error: function(json){
      if (!self.already_fetched_history) {
        self.already_fetched_history = true;
        jQuery('div.rtd-reading').html('<div class="rtd-units">Yesterday\'s data</div>');
        var data = [];
        var total;
        for (var i=0; i<self.backup_history.length; i++) {
            total = self.make_total(self.backup_history[i][0], self.backup_history[i][1], 'energy');
            data.push([total]);
        }
        for (var i=0; i<carbon_culture.bars.length; i++) {
          carbon_culture.bars[i].remove();
        }
        carbon_culture.bars = [];
        self.draw_graph_bars(self.paper, self.graph_width-self.realtime_bar_width-20, self.graph_height, data, self.max);
      }
      // Set off the realtime graph
      if (!self.already_fetched_realtime){
        self.already_fetched_realtime = true;
        self.log("Triggering realtime fetch loop");
        self.set_next_max()
        setInterval("carbon_culture.set_next_max()", 5000);
      }
    }
  });
};
carbon_culture.make_total = function(elec, gas, units, should_log) {
  var self = carbon_culture;
  var final_gas, final_elec
  if (units === 'energy') {
    // I believe this is the (electricity in KWh) + (volume of gas in m3 * calorific value * correction factor)
    // resulting units KWh
    final_gas  = gas  * 39.26207*1.022640/3.6;
    final_elec = elec;
    // check again - against IP.
  } else if (units === 'co2') {
    // Gas will be 0.20374, both these came from http://www.defra.gov.uk/environment/business/reporting/pdf/20090928-guidelines-ghg-conversion-factors.pdf
    final_gas  = gas  * 39.26207*1.022640*0.20374/3.6;
    final_elec = elec * 0.54303;
  } else if (units === 'money') {
    // This is from the bills from May 2010 // 1.3960
    final_elec = elec * 0.0830659615;
    final_gas  = gas  * 39.26207*1.022640/3.6*0.01396;
  } else {
    alert('No such unit: '+units);
  }
  // co2 0 1978.7220294566666 1074.50542365585370    487
  self.log(' '+units+' '+gas+' '+elec+' '+final_elec + final_gas);
  return final_elec + final_gas;
};
carbon_culture.set_next_max = function() {
  var self = carbon_culture; 
  jQuery.jsonp({
    url: self.feed_url+"daq/decc/realtime/?channels=decc-elec,main-gas",
    timeout: 4000,
    callbackParameter: 'callback',
    callback: 'decc_realtime',
    success: function(json, two){
        self.next_elec_max = json['decc-elec']
        self.next_gas_max = json['main-gas']
        if (!self.interval) {
            self.elec_max = self.next_elec_max;//self.realtime_animation_value = json['decc-elec'];
            self.gas_max = self.next_gas_max;//self.realtime_animation_value = json['decc-elec'];
            self.interval = setInterval("carbon_culture.tick()", self.event_loop_time*1000 / self.event_loop_steps);
        }
        self.already_fetched_realtime = true;
    },
    error: function(json, error1, error2){
    }
  });
};
carbon_culture.start = function() {
    if ( typeof( window[ 'carbon_culture_settings' ] ) !== "undefined") {
        carbon_culture.variant = carbon_culture_settings.variant;
    }
    var self = carbon_culture; 
    if (jQuery.browser.msie && jQuery.browser.version >= 7 && jQuery.browser.version < 9) {
        self.ie_gt_7 = true;
    }
    self.add_html('rtd-widget');
    // Create the paper object now
    self.paper = Raphael("graph", self.graph_width, self.graph_height);
    // Create the text element for the odometer
    // -20 is a hack to make it not visible to start with.
    self.realtime_energy = self.paper.text(self.graph_width-(self.realtime_bar_width/2), -20, self.realtime_animation_value + '');
    self.realtime_bar = self.paper.rect(self.graph_width-self.realtime_bar_width-1, self.graph_height-1, self.realtime_bar_width, 10);
    self.realtime_bar.attr({"fill": "#eebf24", "stroke": 0});
    self.realtime_animate_bar = self.paper.rect(0, 0, 0, 0);
    self.realtime_animate_bar.attr("stroke", 0);
    self.fetch_history();
    setInterval("carbon_culture.fetch_history()", 5*60*1000);
};
jQuery(document).ready(function() {
    carbon_culture.start();
})



