//http://alexmarandon.com/articles/web_widget_jquery/
(function(arg1) {
  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 script_tag = document.createElement('script');
    script_tag.setAttribute("type", "text/javascript");
    script_tag.setAttribute("src", base_url+"/js/jquery.js");
    if (script_tag.readyState) {
      script_tag.onreadystatechange = function() { // For old versions of IE
        if (this.readyState == 'complete' || this.readyState == 'loaded') {
          scriptLoadHandler();
        }
      };
    } else {
      script_tag.onload = scriptLoadHandler;
    }
    // Try to find the head, otherwise default to the documentElement
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
  } else {
    // The jQuery version on the window is the one we want to use
    jQuery = window.jQuery;
    main();
  }

  /** ****** 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);
      if(!window.c3){
        // load c3js
        jQuery('<link/>', {
          rel : 'stylesheet',
          type : 'text/css',
          href : base_url+'/css/c3.css'
        }).appendTo('head');
        jQuery.when(
          jQuery.getScript("http://d3js.org/d3.v3.min.js"), 
          jQuery.getScript(base_url+"/js/c3.js"), 
          jQuery.Deferred(function(deferred) {
            jQuery(deferred.resolve);
          })).done(function() {
            loadChart();
        })
      }else{
        // assuming c3js there
        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,

      success : function(data) {
        console.log(data);
        var chart = c3.generate({
          bindto : container,
          size : {
            width : arg.c_width,
            height : arg.c_height
          },
          color : {
            pattern : [ '#fba714', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2',
                '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5' ]
          },
          padding : {
            top : 10,
            right : 20,
            bottom : 20,
            left : 30
          },
          data : {
            type: 'bar',            
            json: data.json,
	    labels: true,
            keys: {
              x: 'date', // it's possible to specify 'x' when category axis
              value: ['count'],
            }
          },
          legend : {
            show : false
          },         
          axis : {
            x : {
              type : 'timeseries',              
	       height: 20,
              tick : {
                rotate: 25,
	        centered: true,
                multiline: false,
                format : function(x) {
                  var format = d3.time.format("%d-%b");
                  return format(x)
                }                 
              }
            },
            y : {              
              min : 0,
              label: {
                text: 'Visitors',
                position: 'inner-middle'
              },
              tick: {
		count: 4,
		format: function(x){return d3.round(x);}
	      },
              padding : {
                top : 100,
                bottom : 0
              }
            }
          }
        });
        debugger;
        jQuery('.c3-line-count').css('stroke-width', '2px');
        jQuery('g>text').attr('font-family', 'Arial').attr('font-size', 12);
        jQuery('#chartdiv_ana').css("background-color","white");
        // chart.transform('pie');
        
        
        
        // $('#' + arg.chart_div).html(data.html);
      },

      error : function(parsedjson, textStatus, errorThrown) {
        console.log("parsedJson: " + JSON.stringify(parsedjson));
        // $('body').append("parsedJson status: " + parsedjson.status + '</br>' + "errorStatus: " + textStatus + '</br>' + "errorThrown: " + errorThrown);

      }
    });

  }

})(
 {"c_height":"250","ana_type":"pageviews","chart_div":"cmf-analytics","domain":"rajbhasha.gov.in","c_width":"250","base_url":"http://analytics.wrc.nic.in/cmfanalytics"}  
); // We call our anonymous function immediately
