//http://alexmarandon.com/articles/web_widget_jquery/
(function(arg1) {
  $.ajaxSetup({ cache: true });
  var url = window.location.href;
var prto = url.split("//");
  var base_url =  prto[0]+'//'+base_url;
var arg = {};

  // Localize jQuery variable
  var jQuery;

  /** ****** Load jQuery if not present ******** */
  if (window.jQuery === undefined || window.jQuery.fn.jquery !== '2.1.1') {    
    var jquery_tag = addScript(base_url+"/js/jquery.js");    
    addScriptLoadCallback(jquery_tag, function(){
      console.log("jquery loaded");
      var d3js_tag = addScript(base_url+"/js/d3.js");
      addScriptLoadCallback(d3js_tag, function(){
        console.log("d3js loaded");
        var d3js_cloud = addScript(base_url+"/js/c3.js");
        addScriptLoadCallback(d3js_cloud, function(){
          console.log("c3js loaded");
          $('<link/>', {
            rel : 'stylesheet',
            type : 'text/css',
            href : base_url+'/css/c3.css'
          }).appendTo('head');
          scriptLoadHandler();          
        });
      });
    });    
  } else {
    // The jQuery version on the window is the one we want to use
    jQuery = window.jQuery;
    main();
  }
  
  function addScript(src){
    var script_tag = document.createElement('script');
    script_tag.setAttribute("charset", "utf-8");
    script_tag.setAttribute("type", "text/javascript");
    script_tag.setAttribute("src", src);
    return script_tag;    
  }
  
  function addScriptLoadCallback(script_tag, callback){
    if (script_tag.readyState) {
      script_tag.onreadystatechange = function() { // For old versions of IE
        if (this.readyState == 'complete' || this.readyState == 'loaded') {
          callback();
        }
      };
    } else {
      script_tag.onload = callback;
    }
    //Try to find the head, otherwise default to the documentElement
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
  }
  
  /** ****** Called once jQuery has loaded ***** */
  function scriptLoadHandler() {

    // Restore $ and window.jQuery to their previous values and store the
    // new jQuery in our local jQuery variable
    jQuery = window.jQuery.noConflict(true);
    // Call our main function
    main();
  }

  /** ****** Our main function ******* */
  function main() {
    jQuery(document).ready(function($) {
      // Deep copy
      arg = jQuery.extend(true, {}, arg1);
      loadChart();     
    });
  }
  

  /** Loading Chart * */
  function loadChart() {
    var container = '#' + arg.chart_div;
    // jQuery(container).css({"height": arg.c_heigth, "width": arg.c_width});
    // cleaning container
    jQuery(container).empty();  

    var jsonp_url = base_url+"/stats?domain="+arg.domain+"&ana_type="+arg.ana_type;
    jQuery.ajax({
      url : jsonp_url,
      dataType : "jsonp",
      timeout : 15000,
      jsonpCallback: "browser_cat_chart_cb",
      cache: true,

      success : function(data) {
        console.log(data);
        data.json = d3.nest().key(function(d){return d.browser_cat}).rollup(function(d){return d3.sum(d, function(g) {return g.count; })}).entries(data.json);
        var tmp ={};
        data.json.forEach(function(d) {
          if(d.key != 'null'){
            tmp[d.key] = d.values;
          }
        });
        var  chart = c3.generate({
          bindto : container,
          size : {
            width : arg.c_width,
            height : arg.c_height
          },
          data: {
            type: 'pie',
            json:  tmp
          }         
        });
        jQuery('.c3-line-count').css('stroke-width', '2px');
        jQuery('g>text').attr('font-family', 'Arial').attr('font-size', 12);
        jQuery(container).css("background-color","white");
      },

      error : function(parsedjson, textStatus, errorThrown) {
        console.log("parsedJson: " + JSON.stringify(parsedjson));
      }
    });

}

})(
{"c_height":"8000","ana_type":"browser_cat","chart_div":"browser_cat","domain":"ayush.gov.in","c_width":"800","base_url":"http://analytics.wrc.nic.in/cmfanalytics"}  
); // We call our anonymous function immediately
