// Author: Atelier 138
var Conso = {};

$(document).ready(function() {
    
  // Country CO2 module behaviour     
  
  // Country list of CO2 emissions per capita, sorted alphabeticaly.
  // TODO: insert wikipedia link
  var COUNTRIES     = {"Afghanistan":0.0,"Albania":1.4,"Algeria":4.1,"Andorra":6.5,"Angola":1.4,"Anguilla":3.5,"Antigua and Barbuda":5.1,"Argentina":4.7,"Armenia":1.6,"Aruba":23.0,"Australia":17.9,"Austria":8.3,"Azerbaijan":3.7,"Bahrain":29.6,"Bangladesh":0.3,"Barbados":5.3,"Belarus":6.9,"Belgium":9.8,"Belize":1.4,"Benin":0.5,"Bermuda":7.9,"Bhutan":0.9,"Bolivia":1.4,"Bosnia and Herzegovina":7.7,"Botswana":2.6,"Brazil":1.9,"British Indian Ocean Territory":4.4,"Brunei":19.8,"Bulgaria":6.8,"Burkina Faso":0.1,"Burundi":0.0,"Cambodia":0.3,"Cameroon":0.3,"Canada":16.9,"Cape Verde":0.6,"Cayman Islands":9.8,"Central African Republic":0.1,"Chad":0.0,"Chile":4.3,"Colombia":1.4,"Comoros":0.2,"Cook Islands":3.4,"Costa Rica":1.8,"Croatia":5.6,"Cuba":2.4,"Cyprus":9.6,"Czech Republic":12.2,"Côte d'Ivoire":0.3,"Democratic Republic of the Congo":0.0,"Denmark":9.2,"Djibouti":0.6,"Dominica":1.8,"Dominican Republic":2.1,"East Timor":0.2,"Ecuador":2.2,"Egypt":2.3,"El Salvador":1.1,"Equatorial Guinea":7.5,"Eritrea":0.1,"Estonia":15.2,"Ethiopia":0.1,"Falkland Islands":19.7,"Faroe Islands":14.1,"Federated States of Micronesia":0.6,"Fiji":1.7,"Finland":12.1,"France":6.0,"French Guiana":4.2,"French Polynesia":3.1,"Gabon":1.4,"Georgia":1.4,"Germany":9.6,"Ghana":0.4,"Gibraltar":13.1,"Greece":8.8,"Greenland":9.1,"Grenada":2.3,"Guadeloupe":4.7,"Guatemala":1.0,"Guinea":0.1,"Guinea-Bissau":0.2,"Guyana":2.0,"Haiti":0.2,"Honduras":1.2,"Hong Kong":5.8,"Hungary":5.6,"Iceland":7.6,"India":1.4,"Indonesia":1.8,"Iran":6.8,"Iraq":3.4,"Israel":9.6,"Italy":7.7,"Jamaica":5.2,"Japan":9.8,"Jordan":3.6,"Kazakhstan":14.8,"Kenya":0.3,"Kiribati":0.3,"Kuwait":30.2,"Kyrgyzstan":1.1,"Laos":0.3,"Latvia":3.4,"Lebanon":3.2,"Liberia":0.2,"Libya":9.3,"Lithuania":4.6,"Luxembourg":22.8,"Macau":3.0,"Madagascar":0.1,"Malawi":0.1,"Malaysia":7.3,"Maldives":3.0,"Mali":0.0,"Malta":6.7,"Marshall Islands":1.7,"Martinique":4.8,"Mauritania":0.6,"Mauritius":3.1,"Mexico":4.4,"Moldova":1.3,"Mongolia":4.1,"Montserrat":13.1,"Morocco":1.5,"Mozambique":0.1,"Myanmar":0.3,"Namibia":1.5,"Nauru":14.1,"Nepal":0.1,"Netherlands":10.5,"Netherlands Antilles":32.5,"New Caledonia":11.7,"New Zealand":7.8,"Nicaragua":0.8,"Niger":0.1,"Nigeria":0.6,"Niue":2.6,"North Korea":3.0,"Norway":9.1,"Oman":13.7,"Pakistan":0.9,"Palau":10.5,"Palestinian territories":0.6,"Panama":2.2,"Papua New Guinea":0.5,"Paraguay":0.7,"People's Republic of China":4.9,"Peru":1.5,"Philippines":0.8,"Poland":8.3,"Portugal":5.5,"Qatar":55.4,"Republic of China":12.1,"Republic of Ireland":10.2,"Republic of Macedonia":5.5,"Republic of the Congo":0.4,"Romania":4.4,"Russia":10.8,"Rwanda":0.1,"Réunion":3.5,"Saint Kitts and Nevis":4.9,"Saint Lucia":2.3,"Saint Pierre and Miquelon":10.8,"Saint Vincent and the Grenadines":1.9,"Samoa":0.9,"Saudi Arabia":16.3,"Senegal":0.5,"Serbia":5.1,"Seychelles":7.5,"Sierra Leone":0.2,"Singapore":12.1,"Slovakia":6.9,"Slovenia":7.5,"Solomon Islands":0.4,"Somalia":0.1,"South Africa":8.8,"South Korea":10.5,"Spain":8.2,"Sri Lanka":0.6,"Sudan":0.3,"Suriname":4.8,"Swaziland":0.9,"Sweden":5.4,"Switzerland":5.1,"Syria":3.4,"São Tomé and Príncipe":0.8,"Tajikistan":1.1,"Tanzania":0.1,"Thailand":4.1,"The Bahamas":6.4,"The Gambia":0.2,"Togo":0.2,"Tonga":1.7,"Trinidad and Tobago":27.9,"Tunisia":2.4,"Turkey":4.0,"Turkmenistan":9.2,"Turks and Caicos Islands":4.9,"Uganda":0.1,"Ukraine":6.9,"United Arab Emirates":31.1,"United Kingdom":8.9,"United States":18.9,"Uruguay":1.9,"Uzbekistan":4.3,"Vanuatu":0.5,"Venezuela":6.0,"Vietnam":1.3,"Wallis and Futuna":1.9,"Western Sahara":0.5,"Yemen":1.0,"Zambia":0.2,"Zimbabwe":0.8},
      countrySelect = $('#consoPaysHome > select'),
      EARTH_TAKES_BACK = 2.0, // The amount of CO2, in tons/capita, the earth takes back each year
      graph;
  
  // Populate the country select input
  for(var c in COUNTRIES) {
    countrySelect.append('<option value="'+c+'">'+c+'</option>');
  }
  
  countrySelect.bind('change', function(e) {
    //  Value is a country name
    var country = e.target.value;
    if (country) {
      var consumption = COUNTRIES[country].toString();
      // In case hidden, show
      $('#consoPays').css('display', 'block');
      // Dim the world map
      $('#consoPaysHome > img').css('opacity', 0.14);
      // Update the text
      $('#pays').text(country);
      $('#conso').text(consumption);
      // Update the Graph
      var graphContainer   = $('#consoGraphContainer'),
          cornerRadius     = 10,
          lengendGutter    = 14,
          width = barWidth = graphContainer.width(),
          height           = graphContainer.height(),
          barHeight        = height - lengendGutter,
          greenFill        = '90-#73be1e-#aadc69:70-#aadb6a',
          redFill          = '90-#bc3a20-#e96f5c:70-#e56551';

      // Lazy load graph
      if (Conso.graph === undefined)
        Conso.graph = Raphael(graphContainer.get(0), width, height); 
      
      graph = Conso.graph;
      
      // Always redraw
      graph.clear();

      if (consumption <= EARTH_TAKES_BACK) { // There is only a single green rect
        var r = graph.rect(0, 0, barWidth, barHeight, cornerRadius);
        r.attr('fill', greenFill);
        r.attr('stroke-width', 0);
      } else { // There are two rects, CO2 intake vs prodction
        var mid_x = width * (2/consumption),
            r1    = graph.rect(0,     0, mid_x,          barHeight, cornerRadius),
            r2    = graph.rect(mid_x, 0, barWidth-mid_x, barHeight, cornerRadius),
            t1;
        r1.attr({'fill': greenFill, 'stroke-width': 0});
        r2.attr({'fill': redFill,   'stroke-width': 0});
        
        // Legend at the midpoint
        t1 = graph.text(mid_x,     barHeight+8, EARTH_TAKES_BACK.toString() + ' tons')
          .attr({'font-weight': 600, 'font-size': 12});;
        
        // Hack to hide the rouded corners at the intersection (mid_x)
        graph.rect(mid_x-cornerRadius, 0, cornerRadius, barHeight) 
          .attr({'fill': greenFill, 'stroke-width': 0});
        graph.rect(mid_x,              0, cornerRadius, barHeight) 
          .attr({'fill': redFill,   'stroke-width': 0});
      }
      // Legend at the end of the bar (country co2 consumption)
      var t2 = graph.text(barWidth, barHeight+8, consumption + ' tons')
        .attr({'font-weight': 600, 'font-size': 12, 'text-anchor': 'end'});
      
      // The following bit ensures t1 is not overlapping or off-canvas
      if (t1) {
        var t1Dims = t1.getBBox(),
            t2Dims = t2.getBBox();

        // Move t1 if it is over the left edge
        if (t1Dims.x < 0)
          t1.attr({'x': 0, 'text-anchor': 'start'});
          
        // Move t1 if...
        if (t1Dims.x+t1Dims.width >= barWidth-t2Dims.width || // it overlays t2 or...
            t1Dims.x >= barWidth) // it is over the right edge
            t1.attr({'x': t2Dims.x-2, 'text-anchor': 'end'});
      }
    }
  });

  // Email submition module behaviour 
  
  var SUBMIT_SUCCESS_TEXT = 'Thank you',
      EMAIL_INVALID_TEXT  = 'Your email seems invalid',
      EMAIL_VALIDATION_REGEXP = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;             
  
  // Clear input upon first focus
  $('#consoPaysHome input[name="email"]').focus(function(e) {
    $(this)
      .val('') // Remove default text 
      .unbind('focus', arguments.callee); // Remove this listener
  });       
  
  // Email submit behaviour
  var handleEmailSubmit = function(e) {
    var email, 
        value = $('#consoPaysHome input[name="email"]').val();
    
    // Validate the email format
    if (value.match(EMAIL_VALIDATION_REGEXP)) {
       email = value;
    }
    
    if (email) { // The format is valid
      $.post('ajax/subscribe_endpoint.php', {email: email }, function (data, status) { 
        // alert(data, status);
        var inputs = $('#consoPaysHome input');
        // Let'em know it worked
        $(inputs[0]).replaceWith('<p>'+ SUBMIT_SUCCESS_TEXT +'</p>');
        // Remove the form
        inputs.remove();
      });
    } else { // Its not
      alert(EMAIL_INVALID_TEXT);
    }
  };
  
  // React if to either submit button click or input Enter-key press
  $('#consoPaysHome input[type="submit"]').click(handleEmailSubmit);
  $('#consoPaysHome input[name="email"]').bind('keypress', function(e) {
    if (e.keyCode==13) {
      handleEmailSubmit(e);
    }
  });
});
