<script>

  var folium_event = new CustomEvent(
    "folium_libs_loaded",
    {bubbles: true, cancelable: true}
  );

  var load_folium_charts = function(){
    window.dispatchEvent(folium_event);
  };

 var load_folium_libs = function(){
    console.log('Loading all Folium libraries...')
    $.getScript("https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.js", function(){
      $.getScript('//cdnjs.cloudflare.com/ajax/libs/leaflet-dvf/0.2/leaflet-dvf.markers.min.js', function(){
          if (window['vg'] === undefined){
            $.getScript("https://cdnjs.cloudflare.com/ajax/libs/vega/1.4.3/vega.min.js", function(){
              load_folium_charts();
          });
        } else {
          load_folium_charts();
        }
      });
    });
  };

 if(typeof define === "function" && define.amd){
      var load_paths = {
        paths: {
          topojson:'https://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.9/topojson.min.js',
          queue: 'https://cdnjs.cloudflare.com/ajax/libs/queue-async/1.0.7/queue.min.js',
          d3: 'https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js'
        }
      };
      var libs = ['d3', 'queue', 'topojson'];
      for (var i=0; i < libs.length; i++){
        lib = libs[i]
        if (window[lib] !== undefined){
          delete load_paths.paths[lib]
        };
      };
      if (Object.keys(load_paths.paths).length != 0){
        require.config(load_paths);
        require(["queue"], function(queue){
          window.queue = queue;
        });
        require(["d3"], function(d3){
            console.log('Loading from require.js...')
            window.d3 = d3;
            require(["topojson"], function(topojson){
                window.topojson = topojson;
                load_folium_libs();
            });
        });
      } else {
        load_folium_libs();
      }

 }else{
      console.log('Require.js not found!');
      throw "Require.js not found!"
 };

</script>
