google.load("visualization", "1", {'packages':['corechart']});

var lang = trad.themoney_lang;

var jQuery_money = jQuery.noConflict();

switch(lang) {
  case "fr_FR":
    ht = "HT";
    pj = "Revenues";
    break;
  default:
    ht = "ex-Tax";
    pj = "Incomes";
}
cj = "CPM";

jQuery_money( document ).ready(function() {
  jQuery_money( "#form_stats" ).click(function() {
    var data = {
      action: 'get_stats',
      periode: jQuery_money('#periode').val(),
      date_from: jQuery_money('#custom_date_from').val(),
      date_to: jQuery_money('#custom_date_to').val(),
      format : jQuery_money('#formats').val(),
      imp_yes: 1
    };
    jQuery_money.post(the_ajax_script.ajaxurl, data, function(response) {
      jQuery_money("#chart_div").empty();
      drawBasic(response);
    });
  });
  
  jQuery_money( "#stats_csv" ).click(function() {
    var periode   = jQuery_money('#periode').val();
    var format    = jQuery_money('#formats').val();
    var date_from = jQuery_money('#custom_date_from').val();
    var date_to   = jQuery_money('#custom_date_to').val();
    
    var data = {
      action: 'get_stats',
      periode: periode,
      date_from: date_from,
      date_to: date_to,
      format : format,
      imp_yes: 1
    };
    jQuery_money.post(the_ajax_script.ajaxurl, data, function(response) {
      var parsed = JSON.parse(response);
      ExcelGenerator(parsed,format);
    });
  });
});

function ExcelGenerator(parsed,format){
  var dt = new Date();
  var day = dt.getDate();
  var month = dt.getMonth() + 1;
  var year = dt.getFullYear();
  var postfix = day + "." + month + "." + year;
  var tab_html = "<table><tr><th>Date</th><th>Format</th><th>Impressions</th><th>CPM</th><th>Income</th></tr>";
  var imp_somme = 0;
  var rev_somme = 0;
  var cpm = 0;
  for(var date_perf in parsed){
    for(var format_perf in parsed[date_perf]){
      cpm = parsed[date_perf][format_perf][1]*1000/parsed[date_perf][format_perf][0];
      tab_html = tab_html+"<tr><td>"+date_perf+"</td><td><center>"+format_perf+"</center></td><td><center>"+parsed[date_perf][format_perf][0]+"</center></td><td><center>"+cpm.toFixed(2)+"</center></td><td><center>"+parsed[date_perf][format_perf][1]+"</center></td></tr>";
      imp_somme += parseInt(parsed[date_perf][format_perf][0]);
      rev_somme += parseFloat(parsed[date_perf][format_perf][1]);
    }
  }
  tab_html = tab_html+"<tr><td></td><td>Total</td><td>"+imp_somme+"</td><td>"+(rev_somme*1000/imp_somme).toFixed(2)+"</td><td>"+rev_somme.toFixed(2)+"</td></tr></table>";
  
  //creating a temporary HTML link element (they support setting file names)
  var a = document.createElement('a');
  //getting data from our div that contains the HTML table
  var data_type = 'data:application/vnd.ms-excel';
  a.href = data_type + ', '+tab_html ;
  //setting the file name
  if (format != ""){
    a.download = 'themoneytizer_'+format.toLowerCase()+'_'+ postfix + '.xls';
  }
  else{
    a.download = 'themoneytizer_'+ postfix + '.xls';
  }
  //triggering the function
  a.click();
}

function drawBasic(response) {
  var result = jQuery_money.parseJSON(response);
  var my_result = [];
  var imp_somme = [];
  var rev_somme = [];
  var somme = 0;
  
  for(var date_perf in result){
    imp_somme[date_perf] = 0;
    rev_somme[date_perf] = 0;
    for(var format_perf in result[date_perf]){
      imp_somme[date_perf] += parseInt(result[date_perf][format_perf][0]);
      rev_somme[date_perf] += parseFloat(result[date_perf][format_perf][1]);
    }
  }
  for(var i in rev_somme){
    my_result.push({c:[{v: i}, {v: rev_somme[i]}, {v: (rev_somme[i]*1000/imp_somme[i]).toFixed(2)}]});
    somme += rev_somme [i];
  }
  somme = somme.toFixed(2);
  var data = new google.visualization.DataTable({
    cols: [{id: 'Date', label: 'Date', type: 'string'},
      {id: 'Euros', label: pj, type: 'number'},
      {id: 'IMP', label: cj, type: 'number'}],
    rows: my_result
  }, 0.10);
  
  var options = {
    backgroundColor: 'transparent',
    height: '500' ,
    colors: ['#db0436','#383838'],
    legend: { position: 'bottom' },
    seriesType: 'bars',
    series: {1: {type: 'line',targetAxisIndex:1}}
  };
  if(document.getElementById('chart_div') != null){
    var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  }
  jQuery_money('#total').html('Total = '+somme+' '+ht);
}

jQuery_money( document ).ready(function() {
  var data = {
    action: 'get_stats',
    periode: 'main_30',
    imp_yes: 1
  };
  // the_ajax_script.ajaxurl is a variable that will contain the url to the ajax processing file
  jQuery_money.post(the_ajax_script.ajaxurl, data, function(response) {
    jQuery_money("#chart_div").empty();
    drawBasic(response);
  });
  
});

if (lang === "en" || lang === "us") {
  (function( factory ) {
    if ( typeof define === "function" && define.amd ) {
      
      // AMD. Register as an anonymous module.
      define([ "../jQuery_money.ui.datepicker" ], factory );
    }
    else {
      
      // Browser globals
      factory( jQuery_money.datepicker );
    }
  }(function( datepicker ) {
    datepicker.regional['en'] = {
      closeText: 'Done',
      prevText: 'Prev',
      nextText: 'Next',
      currentText: 'Today',
      monthNames: ['January','February','March','April','May','June',
        'July','August','September','October','November','December'],
      monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
        'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
      dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
      dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
      dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'],
      weekHeader: 'Wk',
      dateFormat: 'mm/dd/yy',
      firstDay: 1,
      isRTL: false,
      showMonthAfterYear: false,
      yearSuffix: ''};
    datepicker.setDefaults(datepicker.regional['en']);
    
    return datepicker.regional['en'];
    
  }))
}
else if (lang === 'fr'){
  (function( factory ) {
    if ( typeof define === "function" && define.amd ) {
      
      // AMD. Register as an anonymous module.
      define([ "../jQuery_money.ui.datepicker" ], factory );
    }
    else {
      
      // Browser globals
      factory( jQuery_money.datepicker );
    }
  }(function( datepicker ) {
    datepicker.regional['fr'] = {
      closeText: 'Fermer',
      prevText: 'Précédent',
      nextText: 'Suivant',
      currentText: 'Aujourd\'hui',
      monthNames: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin',
        'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
      monthNamesShort: ['janv.', 'févr.', 'mars', 'avril', 'mai', 'juin',
        'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.'],
      dayNames: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
      dayNamesShort: ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'],
      dayNamesMin: ['D','L','M','M','J','V','S'],
      weekHeader: 'Sem.',
      dateFormat: 'dd/mm/yy',
      firstDay: 1,
      isRTL: false,
      showMonthAfterYear: false,
      yearSuffix: ''};
    datepicker.setDefaults(datepicker.regional['fr']);
    
    return datepicker.regional['fr'];
  }))
}
else{
  (function( factory ) {
    if ( typeof define === "function" && define.amd ) {
      
      // AMD. Register as an anonymous module.
      define([ "../jQuery_money.ui.datepicker" ], factory );
    } else {
      
      // Browser globals
      factory( jQuery_money.datepicker );
    }
  }(function( datepicker ) {
    datepicker.regional['en'] = {
      closeText: 'Done',
      prevText: 'Prev',
      nextText: 'Next',
      currentText: 'Today',
      monthNames: ['January','February','March','April','May','June',
        'July','August','September','October','November','December'],
      monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
        'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
      dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
      dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
      dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'],
      weekHeader: 'Wk',
      dateFormat: 'dd/mm/yy',
      firstDay: 1,
      isRTL: false,
      showMonthAfterYear: false,
      yearSuffix: ''};
    datepicker.setDefaults(datepicker.regional['en']);
    
    return datepicker.regional['en'];
  }))
}
