/*jslint onevar: true, browser: true, devel: true, debug: true, undef: true, eqeqeq: true, bitwise: true, newcap: true, immed: true */
/*global jQuery,window,$NBtheseTagsAreForJSLint */
/* Copyright London Analytics Ltd 2009-2010, all rights reserved */

(function($){

var 
  debuglog = function(){}, // console.log,
  units,                 // so many different units of power
  EN = {},               // the encapsulation object for publicly visible properties & methods for the site
  unitDiv,               // the jQuery DOM of the unit selector
  currentUnit = "GW";

//---------------------------------------------------------------------------
//  fundamental arrays

  units = {
    "kWh/d" : { name: "kWh per person per day", perGW: 0.4, thermal: false },
    "GW"    : { name: "gigawatts mean power", perGW: 1.0, thermal: false },
    "TWh/y" : { name: "terawatt-hours per year", perGW: 8.76, thermal: false },
    "EJ/y"  : { name: "exajoules per year", perGW: 0.031536, thermal: false },
    "Q/y"   : { name: "quads per year", perGW: 0.0298968, thermal: true },
    "Mboe/y": { name: "Million Barrels of Oil per year", perGW: 5.3804, thermal: true },
    "Mtoe/y": { name: "Million Tonnes of Oil per year", perGW: 0.75324, thermal: true },
    "kboe/d": { name: "Thousand Barrels of Oil per day", perGW: 14.74, thermal: true }
  };

window.EN = EN;

// =============================================================================
// internal functions

//---------------------------------------------------------------------------

function sig_figs(x) {
  var strx, x3, dp, rgx, 
      absx = Math.abs(x),
      sig25limit = 200;

  if (0 == x) return '0';

  if (absx > sig25limit) {

    // display it to 2.5 significant figures

    dp = Math.floor(Math.log( absx )/Math.log(10)) - 2;
    x3 = x * Math.pow( 10, -dp );
    if ( x3 > sig25limit )
      x3 = Math.round( x3 / 5 ) * 5;

    strx = x3.toFixed(0);
    while (--dp >= 0) strx += "0";

    // now add thin non-breaking spaces to separate groups of 3 digits

    rgx = /(\d+)(\d{3})$/;
    while (rgx.test(strx))
      strx = strx.replace( rgx, "$1" + "&#x202f;" + "$2" );
    return strx;
  }

  if (1 > absx)
    dp = 2;
  else if (10 > absx)
    dp = 1;
  else
    dp = 0;

  return x.toFixed( dp );
}
//---------------------------------------------------------------------------

function unitChanger() {
  var newunit,
      factor = units[currentUnit];
      
  newunit = unitDiv.val();
  if (units[newunit] && newunit !==  currentUnit) {
    factor = units[newunit].perGW;
    $(".enq").each(function updateQuantitiesWithNewUnits() {
      var span = $(this);
      span.html( ( newunit === span.data("qrawunit") ) ? span.data("qraw") :
                     ( sig_figs( factor * span.data("qgw") ) + "&nbsp;" + newunit ) );
    });
    currentUnit = newunit;
  }
  return true;
}

//---------------------------------------------------------------------------

function saveGWQuantities() {
  var powerPattern = /([0-9.,-]+)/,
      unitsPattern = /([a-zA-Z\/]+)/;
  $(".enq").each( function() {
      var thisGW, 
          i = $(this), 
          txt = i.text(),
          thisPower = parseFloat( ( powerPattern.exec( txt ) )[0]),
          thisUnit = ( unitsPattern.exec( txt ) )[0],
          thisGW = thisPower / units[thisUnit].perGW;
      i.html( txt = txt.replace( " ","&nbsp;" ) );
      i.data( { qgw: thisGW, qrawunit: thisUnit, qraw: txt } ); // store each quantity as GW, as well as the original value in its original precision
      if ( "GW" !== thisUnit )
        i.html( sig_figs( thisGW ) + "&nbsp;GW" );
    });
}

//---------------------------------------------------------------------------

EN.setToggler = function setToggler() {
  $(".toggler").
    removeClass("toggler").
    addClass("togglershow").
    click(function togglerClick() {
      $(this).
        addClass("toggler").
        removeClass("togglershow").
        nextAll().
          removeClass("hidden");
    }).
    nextAll().
      addClass("hidden");
};

//---------------------------------------------------------------------------
/*
EN.mapInit = function mapInit() {
  // callback used by google maps script once it's loaded
debugger;
var myLatlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
    zoom: 8,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("container"), myOptions);

  var latlong = new google.maps.LatLng(56, 8.2),
      myOptions = {
	zoom: 8,
	center: latlong,
	mapTypeId: google.maps.MapTypeId.SATELLITE
	},
      map = new google.maps.Map(document.getElementById("content"), myOptions); // map_canvas

}

//---------------------------------------------------------------------------

EN.makeMap = function makeMap() {
var sc = $("<script>").
  attr( { "type" : "text/javascript" ,
	  "src"  : "http://maps.google.com/maps/api/js?sensor=false&callback=EN.mapInit" // &key=ABQIAAAAy-UKJj_v0CsPnvDw9iph3BSquXiM-cdzCi1LAaQcT8Rw6whwhhSLKz78tk-xpBi1OJkg6gpdUGSISQ" 
      } );
$(document).append(sc);
}
*/
//---------------------------------------------------------------------------

$(document).ready(function en_docready() {
  if ( $(".enq").length && 
        ( unitDiv = $(".widget_unitswitcher").
            animate({
	      height: ['toggle', 'swing'],
	      opacity: 'toggle' }, "slow" ).
            find("select:first").
              bind("keypress change click", unitChanger)
        ).length) {
    saveGWQuantities();
    unitChanger();
  }
  /*
  $(".enparent").each( function resizeImagsToParentHeight() {
    var i = $(this);
    i.height( i.parent().height() * 0.97 );
  });
  */
});

}(jQuery));
