Prv8 Shell
Server : Apache/2.2.22 (Unix) mod_ssl/2.2.22 OpenSSL/1.0.0-fips mod_auth_passthrough/2.1 mod_bwlimited/1.4
System : Linux server.jackjohnson.com 2.6.32-279.5.2.el6.x86_64 #1 SMP Fri Aug 24 01:07:11 UTC 2012 x86_64
User : jackjohn ( 502)
PHP Version : 5.3.17
Disable Function : NONE
Directory :  /home/jackjohn/public_html/shopsite-images/en-CA/javascript/reports/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/jackjohn/public_html/shopsite-images/en-CA/javascript/reports/charts.js
  var sep = "\7";
  
  var week = {'Mon':1, 'Tue':2, 'Wed':3, 'Thu':4, 'Fri':5, 'Sat':6, 'Sun':7};
  
  var state = {
    report_section: 'per_global_1',
    time_unit: 'single',
    display_type: 'show_chart_ck',
    table_grouping: 1,
    reports_matrix: { 
      global_1: {
        current_reports: 'revenue=on'        
      },
      global_2: {
        current_reports: 'coupons=on'
      },
      products: {
        current_reports: 'sales=on',
        selector: 'selector_top',
        top_count: 2,
        specific_id_list: '',
        combine_options: 0
      },
      coupons: {
        current_reports: 'coupons=on',
        selector: 'selector_top',
        top_count: 5,
        specific_id_list: ''
      },
      global_3: {
        current_reports: 'giftcertsbought=on'
      },
      shipping: {
        current_reports:'shipping=on',
        selector: 'selector_top',
        top_count: 5,
        specific_id_list: ''
      },
      referers: {
        current_reports:'revenue=on',
        selector: 'selector_top',
        top_count: 5,
        specific_id_list: ''
      },
      customers: {
        current_reports:'revenue=on',
        selector: 'selector_top',
        top_count: 5,
        specific_id_list: ''
      },
      locations: {
        current_reports:'revenue=on',
        selector: 'selector_top',
        top_count: 5,
        specific_id_list: '',
        combine_zips: 0
      },
      paymentTypes: {
        current_reports:'revenue=on',
        selector: 'selector_top',
        top_count: 5,
        specific_id_list: ''
      },
      inventory: {
        current_reports:'inventory=on',
        selector: 'selector_inv',
        indexed_only: 1,
        specific_id_list: ''
      },
      global_4: {
        current_reports: 'cartsaccessed=on'
      }
    },
    start:'',
    end:'',
    shortcut: 'cur_day',
    week_start: 'ws_Sun',
    date_format: 'mdy',
    top_max: 50
  }
  

  
  var name_map = {
    'revenue': {name: 'Orders', type:1, restrict: 0},
    'orders': {name:'Orders', type:2, restrict: 0},
    'tax': {name:'Tax collected', type:1, restrict: 0},
    'shipping': {name:'Shipping costs', type:1, restrict: 0}, 
    'coupons':{name:'Redeemed coupons', type:1, restrict: 1}, 
    'discounts':{name:'Discounts applied', type:1, restrict: 1}, 
    'rewards':{name:'Rewards value', type:1, restrict: 1}, 
    'giftcertsbought':{name:'Gift certificate sales', type:1, restrict: 1}, 
    'giftcertsused':{name:'Redeemed gift certificates', type:1, restrict: 1},
    'sales':{name:'Product sales', type:1, restrict: 0},
    'productunits':{name:'Units sold', type:2, restrict: 0},
    'couponunits':{name:'Coupons used', type:2, restrict: 1},
    'inventory': {name:'Product inventory', type:1, restrict: 1},
    'surcharges': {name:'Surcharges', type:1, restrict: 1},
    'productvalue': {name:'Products', type:1, restrict: 0},
    'cartsaccessed': {name:'Abandoned carts', type:2, restrict: 1},
    'cartsaccessedtotal': {name:'Abandoned revenue', type:1, restrict: 1, stack: false},
    'cartsfirstabandonemail': {name:'First email sent', type:2, restrict: 1},
    'cartssecondabandonemail': {name:'Second email sent', type:2, restrict: 1},
    'cartsrecovered': {name:'Recovered carts from earlier', type:2, restrict: 1},
    'cartsrecoveredtotal': {name:'Recovered revenue from earlier', type:1, restrict: 1, stack: false}
  };
  
var reports_matrix = {
    global_1: {
      available_reports: ['revenue', 'orders', 'tax', 'shipping', 'surcharges'],
      selectors: [],
      name: '',
      pretty_name: 'Sales',
      overview_type: 'pie',
      yaxis: 'Orders'
    },
    global_2: {
      available_reports: ['coupons', 'discounts', 'giftcertsused', 'rewards'],
      selectors: [],
      name: '',
      pretty_name: 'Merchandising expense',
      overview_type: 'pie',
      yaxis: null
    },
    products: {
      available_reports: ['sales', 'productunits', 'rewards'],
      selectors: ['top', 'specific', 'all'],
      name: 'products',
      search_text: 'Product name, SKU, or option',
      empty_name: 'Product name missing',
      pretty_name: 'Product',
      overview_type: 'pie',
      top_max: false,
      yaxis: 'Units'
    },
    coupons: {
      available_reports: ['coupons', 'couponunits'],
      selectors: ['top', 'specific', 'all'],
      name: 'coupons',
      search_text: 'Coupon name',
      empty_name: 'No name',
      pretty_name: 'Coupon',
      overview_type: 'pie',
      top_max: false,
      yaxis: 'Coupons'
    },
    global_3: {
      available_reports: ['giftcertsbought', 'giftcertsused'],
      selectors: [],
      name: '',
      pretty_name: 'Gift Certificate',
      overview_type: 'bar',
      yaxis: null
    },
    shipping: {
      available_reports: ['revenue', 'orders', 'shipping', 'surcharges'],
      selectors: ['top', 'specific', 'all'],
      name: 'shipping options',
      search_text: 'Shipping option name',
      empty_name: 'No shipping/Free shipping',
      pretty_name: 'Shipping',
      overview_type: 'pie',
      top_max: 10,
      yaxis: 'Orders'
    },
    referers: {
      available_reports: ['revenue', 'orders', 'coupons', 'discounts', 'rewards', 'giftcertsbought', 'giftcertsused'],
      selectors: ['top', 'specific', 'all'],
      name: 'associates',
      search_text: 'Associate\'s name',
      empty_name: 'No associate',
      pretty_name: 'Associate',
      overview_type: 'pie',
      top_max: false,
      yaxis: 'Orders'
    },
    customers: {
      available_reports: ['revenue', 'orders', 'coupons', 'discounts', 'rewards'],
      selectors: ['top', 'specific', 'all'],
      name: 'customers',
      search_text: 'Customer\'s name or email',
      empty_name: 'Customer\'s information missing',
      pretty_name: 'Customer',
      overview_type: 'pie',
      top_max: false,
      yaxis: 'Orders'
    },
    locations: {
      available_reports: ['revenue', 'orders', 'tax', 'shipping'],
      selectors: ['top', 'specific', 'all'],
      name: 'locations',
      search_text: 'State code, country, or zip',
      empty_name: 'Location info not available',
      pretty_name: 'State and country',
      overview_type: 'pie',
      top_max: false,
      yaxis: 'Orders'
    },
    paymentTypes: {
      available_reports: ['revenue', 'orders', 'tax'],
      selectors: ['top', 'specific', 'all'],
      name: 'payment types',
      search_text: 'Payment type',
      empty_name: 'None',
      pretty_name: 'Payment types',
      overview_type: 'pie',
      top_max: 10,
      yaxis: 'Orders'
    },
    inventory: {
      available_reports: ['inventory'],
      selectors: ['low_inventory', 'top', 'specific'],
      name: 'products',
      search_text: 'Product name, SKU, or option',
      empty_name: 'Product name missing',
      pretty_name: 'Product',
      overview_type: 'pie',
      top_max: false,
      yaxis: null
    },
    global_4: {
      available_reports: ['cartsaccessed', 'cartsaccessedtotal', 'cartsfirstabandonemail', 'cartssecondabandonemail', 'cartsrecovered', 'cartsrecoveredtotal'],
      selectors: [],
      name: '',
      pretty_name: 'Cart abandonment',
      overview_type: 'bar',
      yaxis: null
    }
  };
  
  var config = {
    currency: {
      code: "",
      symbol: "",
      formatter: function(val) {return val; }
    },
    level:2
  }
  
function setup_reports(currency, tops, level) 
{
  
  config.level = level;
  ar = currency.split("|");
  config.currency.code = ar[0];
  config.currency.symbol = ar[1];
  
  config.currency.formatter = function (amount, mode)
  {
    var s;
    var minus = '';
    var format = ar[2];
    var i;
    //http://www.web-source.net/web_development/currency_formatting.htm
    {
      i = parseFloat(amount);
      if(isNaN(i)) { i = 0.00; }
      if(i < 0) { minus = '-'; }
      i = Math.abs(i);
      i = parseInt((i + .005) * 100);
      i = i / 100;
      
      if (mode == 1 && i > 10000) {
        s = new String(i/1000+"K");
      } else
        s = new String(i);
      if (mode == 0) {
        if (format.indexOf('.') >= 0) {
          if(s.indexOf('.') < 0) { s += '.00'; }
          if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
        } else
          if( (i = s.indexOf('.')) > 0) { s = s.substring(0,i); }
      }
    }
    
    
    var result = "";
    var value_placed = false;
    var len = format.length;
    //for (var symb in format) {
    for (var symb = 0; symb < len ; symb++) {
      switch (format.charAt(symb)) {
        case '-':
          result += minus;
          break;
        case '$':
          result += config.currency.symbol;
          break;
        case '#':
        case ',':
        case '.':
          if (!value_placed) {
            result += s;
            value_placed = true;
          }
          break;
        default:
          result += format[symb];
          break;
      }
    }
    //alert(result);
    return result;
  }
  
  //moved from AA file top open config
  /*tops = tops.split("|");
  for (i = 0; i < tops.length-1; i++) {
    var pair = tops[i].split(":");
    reports_matrix[pair[0]].top_max = parseInt(pair[1]);
  }*/
  
}


var chart = false;
var global_color_pointer = -1;

var options = {
    chart: {
        renderTo: 'chart-container',
        defaultSeriesType: 'column',
        zoomType: 'x',
        animation: false
        /*animation: {
          duration: 100
        }*/
        //ignoreHiddenSeries: false,
    },
    colors: [
      '#4572A7', 
      '#AA4643', 
      '#89A54E', 
      '#80699B', 
      '#3D96AE', 
      '#DB843D', 
      '#92A8CD', 
      '#A47D7C', 
      '#B5CA92'
    ],
    plotOptions : {
      column: {
//        animation: false
      },
      area: {
//        animation: false
      },
      series: {
        animation: false,
        /*animation: {
          duration: 100
        },*/
        shadow: false,
        stacking: 'normal',
        dataLabels: {
          enabled: false
        }
      },
      pie: {
        
        point: {
          events: {
            legendItemClick: function() { return false;}
          }
        }
      }
    },
    title: {
        text: 'ShopSite Report',
        style: {
          font: 'normal 18px Arial, sans-serif'
        }
    },
    xAxis: {
        type: 'datetime',
        showFirstLabel: true,
        labels: {
          enabled: true
        },
        dateTimeLabelFormats: {
          day: '%m/%d',
          week:'%m/%d'
        }
    },
    yAxis: [{ // Primary yAxis
       title: {
          text: ""
       },
       min: 0,
       labels: {
          formatter: function() {
            return config.currency.formatter(this.value,1);
          }
        }
    }, { // Secondary yAxis
      title: {
        text: null
      },
      min: 0,
      allowDecimals: false,
       opposite: true
    }],
    
    legend: {
      backgroundColor: '#FFFFFF'
    },

    series: [],
    credits: {enabled: false},
    
    navigation: {
        buttonOptions: {
            align: 'left'
        }
    },
    
    exporting: {
        enabled: false
    },
    
    tooltip: {
     /* formatter: function(){return 0;}*/
    }
};


function kill_chart(kill_selected) {
    
    if (kill_selected)
      $('#selected').html('');
    if (chart) {
      chart.destroy();
      chart = false;
    }
    options.series = [];
    $('#table-container').html("");
    $(document).off('click', '#export_excel');
}





function get_matches(input) {


  var report = state.report_section.substr(4);
  
  var dates = twiddle_dates(get_date_from_input(0), get_date_from_input(1), "bypass"/*state.time_unit*/);
  var start_string = Highcharts.dateFormat('%Y-%m-%d', dates[0].getTime());
  var end_string = Highcharts.dateFormat('%Y-%m-%d', dates[1].getTime());
  
  
  var process_options = 0;
  /*if ($('#combine_options:checked').length > 0)
    state.reports_matrix['products'].combine_options = 1;*/
    
  /*if ($('#combine_zips:checked').length > 0)
    combine_zips = 1;*/
  
    
  switch(report) {
    case "inventory":
    case "products":
        populate_item = function(line) {
          var item = line.split(sep);
          var max_name_length = 40;
          var id = parseInt(item[0],10);
          var option = "";
          if (item.length > 4) {
            id *= 1000000000;
            option = item[4];
            if (item[3].length)
              id += parseInt(item[3],10);
          }
          var name = strip(item[1]);
          
          var title = name.replace(/\"/g,"&quot;");//.replace("\"","&quot;");
          var p_sku = item[2];
          if (option.length) {
            max_name_length -= 10;
          }
          if (p_sku.length)
            max_name_length -= 5;
          if (name.length > max_name_length)
              name = name.substr(0,max_name_length)+"...";
          if (p_sku.length) {
            name += ", SKU:" + p_sku;
            title += ", SKU:" + p_sku;
          }
          if (option.length) {
            var max_option_length = 20;
            var o_sku = item[5];
            if (o_sku.length)
              max_option_length -= 5;
            title += " [OPTION:" + option;
            if (option.length > max_option_length)
              option = option.substr(0,max_option_length) + "...";
            name += " [OPTION:" + option;
            if (o_sku.length) {
              name += ", SKU:" + o_sku;
              title += ", SKU:" + o_sku;
            }
            name += "]";
            title += "]";
          }
          if (!title.length)
            title = reports_matrix[report].empty_name;
          if (!name.length)
            name = reports_matrix[report].empty_name;
          return [id, title, name];
        }
      break;
    case "customers":
      populate_item = function(line) {
        var item = line.split(sep,3);
        var id = item[0];
        var name = item[1] + " (" + item[2] +")";
        var title = name.replace(/\"/g,"&quot;");
        if (!title.length)
          title = reports_matrix[report].empty_name;
        if (!name.length)
          name = reports_matrix[report].empty_name;
        return [id, title, name];
      }
      break;
    case "locations":
      populate_item = function(line) {
        var item = line.split(sep);
        var id = item[0];
        var name = item[1];
        if (item[2].length) {
          if (name.length)
            name += ", ";
          name += item[2];
        }
        if (item.length > 4) {
          if (item[3].length) {
            if (name.length)
              name += ", ";
            name += item[3];
          }
          id += "_" + item[1].replace(/ /i, "_");
          
        }
        if (!name.length)
          name = reports_matrix[report].empty_name;
        return [id, name, name];
      }
      break;
    default:
      populate_item = function(line) {
        var item = line.split(sep,2);
        var id = item[0];
        var name = item[1];
        if (!name.length)
          name = reports_matrix[report].empty_name;
        return [id, name, name];
      }
      break;
  }

  var type = $(input).attr('id');
  if (type == 'selector_search') {
    var name = $(input).val();
    if (name.length > 0) {
      var request = "ajax=gimmematches&table=" + report + "&input=" + encodeURIComponent(name) + "&start=" + start_string + "&end=" + end_string;
      if (state.reports_matrix['products'].combine_options)
        request += '&combine_options=1';
      if (state.reports_matrix['locations'].combine_zips)
        request += '&combine_zips=1';
      //alert("sending request: " + request);
      $.get("stathandler.cgi",request, function(data) {
        var html = "";
        //alert(data);
        if (data.length < 2)
          html += '<p id=no_results>No results</p>';
        else {
          html += '<ul id=matches_list>';
          var lines = data.split("\6");
          var item_info;
          for (var i = 0; i < lines.length -1; i++) {
            item_info = populate_item(lines[i]);
            html += '<li class=match id=match_' + item_info[0] + ' title=\"'+ item_info[1] +'\">' + item_info[2] + '</li>\n';
          }
        }
        html += '</ul>';
        $('#matches').html(html);
      });
      
    } else {
      $('#matches').html('');
    }
  } else {
    $('#selected').html('');
      
    var request;
    if (type == 'selector_top') {
      var count = state.reports_matrix[report].top_count;//$('#selector_top_count').val();
      request = "ajax=gimmematches&table=" + report + "&input=__top_" + count + "&start=" + start_string + "&end=" + end_string;
    }
    
    if (type == 'selector_inv') {
      var count = $('#selector_inv_count').val();
      var out = $('#selector_inv_out:checked').length;
      var low = $('#selector_inv_low:checked').length;
      var indexed = state.reports_matrix['inventory'].indexed_only;
      request = "ajax=gimmematches&table=" + report + "&input=__inv_" + count + "&out=" + out + "&low=" + low +
        "&indexed=" + indexed + "&start=" + start_string + "&end=" + end_string;
    }
    
    if (type == 'selector_all') {
      request = "ajax=gimmematches&table=" + report + "&input=__all" + "&start=" + start_string + "&end=" + end_string;
    }
    
    if (type == 'selector_specific') {
      request = "ajax=gimmematches&table=" + report + "&input=__titles" + "&which=" + state.reports_matrix[report].specific_id_list;
    }
    
    if (state.reports_matrix['products'].combine_options)
      request += '&combine_options=1';
    if (state.reports_matrix['locations'].combine_zips)
      request += '&combine_zips=1';

    
    //$.get("stathandler.cgi",request, function(data) {
    //alert("sending request: " + request);
    $.ajax({
    async: false,
    data: request,
    url: "stathandler.cgi",
    success: 
      function(data) {
        //alert(data);
        var html = "";
        var lines = data.split("\6");
        var id_list = "";
        var item_info;
        for (var i = 0; i < lines.length -1; i++) {
          item_info = populate_item(lines[i]);
          html += ('<li><input class=selected_input type=checkbox name=which value=' + item_info[0] + ' id=match_'+ item_info[0] +' checked>' 
                    + '<a title=\"'+item_info[1] +'\">'+ item_info[2] + '</a></li>\n');
          //id_list += (item_info[0] + ",");
        }
        
        
        $('#selected').html(html);
        $('.selected_input').on('click',function() { selected_click(this); });
        
        /*if (id_list.length > 0) {
          id_list = id_list.substr(0, id_list.length-1);
        }*/
        //if (type != 'selector_specific')
        chart_from_matches(get_id_list());
      }
    });
  
  }
}

function get_id_list() {
  //alert("get_id_list called");
  var id_list = "";
  jQuery.each($('#selected').find('input:checked'), function() {
    if (isNaN($(this).val())) {
      id_list += "'" + ($(this).val() + "',");
    }
    else {
      id_list += ($(this).val() + ",");
    }
  });
  if (id_list.length > 0) {
    id_list = id_list.substr(0, id_list.length-1);
  }
  return id_list;
}


function chart_from_matches(id_list) {
  var unit = state.time_unit;
  var rep = state.report_section;
  if (rep != "per_inventory") {
    $('#reports_wtt').css({display:"inline"});
    
    $('#unit').closest('tr').removeAttr('style');
    $('#show_table').css({display:"block"});
    //if (!$('#show_table_ck').is(':checked')) 
    if (state.display_type == "show_chart_ck") {
      show_chart(0);
    } else {
      show_table(0);
    }
    
    var section = rep.substr(4);
    if (unit == 'single' && reports_matrix[section].overview_type == 'pie' && reports_matrix[section].selectors.length == 0) {
      var reports_list = '';
      for (var r = 0; r < reports_matrix[section].available_reports.length-1; r++) {
        if (reports_matrix[section].available_reports[r] == 'revenue')
          reports_list += ('productvalue=on&');
        else if (name_map[reports_matrix[section].available_reports[r]].type == 1)
          reports_list += (reports_matrix[section].available_reports[r] + '=on&');
      }
      reports_list += (reports_matrix[section].available_reports[r] + '=on');
      load_chart_data(get_date_from_input(0), get_date_from_input(1), unit, reports_list, rep, id_list);
      //state.reports[section] = reports_list;
    } else {
      $('#reports_form').css({display:"block"});
      //var reports_list = $('#reports_form').serialize();
      state.reports_matrix[section].current_reports = $('#reports_form').serialize();
      load_chart_data(get_date_from_input(0), get_date_from_input(1), unit, state.reports_matrix[section].current_reports, rep, id_list);
    }
    //alert(reports_list);
    
  }
  else {
    $('#reports_wtt').css({display:"none"});
    $('#reports_form').css({display:"none"});
    $('#unit').closest('tr').css({display:"none"});
    
    $('#show_table').css({display:"none"});
    show_table(0);
    //$('#table-container').css({clear: "none", "float": "left"});
    //$('#chart-container').css({display:"none"});
    state.reports_matrix['inventory'].current_reports = $('#reports_form').serialize();
    inventory_report(state.reports_matrix['inventory'].current_reports, id_list);
  }
      
}


function option_generator(start,max) {
  var i = start;
  var extra = 0;
  if (i == 1)
    sub = 1;
  var res = [];
  var inc = 1;
  while (i <= max) {
    res.push(i);
    var dif = i;
    if (dif < 10000)
      inc = 1000;
      
    if (dif < 1000)
      inc = 100;
      
    if (dif < 500)
      inc = 50;
      
    if (dif < 200)
      inc = 10;
    
    if (dif < 100)
      inc = 5;
      
    if (dif < 10)
      inc = 1;
    
    i += inc;
  }
  return res;
}

function display_available_reports() {

  var per = state.report_section;
  var spec = per.substr(4);
  var chart_spawned = 0;
  
  $('#' + per).addClass("current_per");
  
  $('#reports').remove();
  
  {
  
    
    var available_reports = reports_matrix[spec].available_reports;
    var rep; 
    var s;
    
    
    
      var html = '<div id=reports><h3 id=reports_wtt>What to report:</h3><form id=reports_form><table>';
      for (var i in available_reports) {
        rep = available_reports[i];    
        //s = rep.split('_');
        if (!name_map[rep].restrict || config.level == 2) {
          html += '<tr><td><label for='+rep+ '>'+ name_map[rep].name;
          if (name_map[rep].type == 1)
            html += " (" + config.currency.symbol + ")";
          else
            html += " (qty.)";
          html += '</label></td><td><input type=checkbox name=' + rep + ' id=' + rep + ' ';
          //if (reports_matrix[spec].default_selected == rep)
          if (state.reports_matrix[spec].current_reports.search(rep + "=on") != -1)
            html += ' checked ';
          html += '></td></tr>\n';
        }
      } 
      html += '</table></form></div>';
      
      $('#'+per).after(html);
    
    if (state.time_unit == 'single' &&  reports_matrix[spec].overview_type == 'pie' && reports_matrix[spec].selectors.length == 0) 
      $('#reports').css({display:'none'});
    else
      $('#reports').css({display:'block'});
    
    
    
    $('#selectors').remove();
    var name = reports_matrix[spec].name;
    var selectors = reports_matrix[spec].selectors;
    var selector;
    html = '';
    
    if (selectors.length > 0) 
      html += '<div id=selectors><h3>For which ' + name + ':</h3>\n';
      
    var current_selector = state.reports_matrix[state.report_section.substr(4)].selector;
    //alert(state.reports_matrix[spec].top_count);

    for (var i in selectors) {
      selector = selectors[i];    
      switch (selector) {
        case 'top':
          html += '<div class=selector id=selector_top_wrap><input type=radio name=selector value=top id=selector_top';
          if (current_selector == 'selector_top') {
            html += ' checked';
          }
          html += '><label for=selector_top>Top </label><select name=selector_top_count id=selector_top_count>\n';
          var top_max = reports_matrix[spec].top_max;
          if (top_max == false)
            top_max = state.top_max;
          var cntlist = option_generator(1,top_max);
          
          //for (var j = 1; j <= reports_matrix[spec].top_max; j++) 
          var len = cntlist.length;
          for (var q = 0; q < len; q++)
          {
            j = cntlist[q];
            html += ('<option value=' + j);
            if (j == state.reports_matrix[spec].top_count)
              html += ' selected';
            html += (' >' + j + '</option>\n');
          }
          //html += "<option value='more'>More...</option>\n";
          html += '</select><label for=selector_top> ' + name + '</label>';
          
          if (current_selector == 'selector_top') {
            html += '<form id=selected_form><ul id=selected></ul></form>\n';  
          }
          html += '</div>\n';
          
          
          break;
        case 'low_inventory':
          html += '<div class=selector id=selector_inv_wrap><input type=radio name=selector value=top id=selector_inv';
          if (current_selector == 'selector_inv') {
            html += ' checked';
          }
          html += '><select name=selector_inv_count id=selector_inv_count>\n';
          var cntlist = option_generator(20,state.top_max);
          var len = cntlist.length;
          for (var q = 0; q < len; q++) {
            j = cntlist[q];
            html += ('<option value=' + j + '>' + j + '</option>\n');
          }
          /*for (var j = 20; j <= 50; j+=10)
            html += ('<option value=' + j + '>' + j + '</option>\n');*/
          html += '</select><label for=selector_inv> low stock ' + name + '</label>\n';
          html += '<div><input type=checkbox name=selector_inv_out class=selector_inv_chk id=selector_inv_out checked>';
          html += '<label for=selector_inv_out>Out of stock products</label></div>';
          html += '<div><input type=checkbox name=selector_inv_low class=selector_inv_chk id=selector_inv_low checked>';
          html += '<label for=selector_inv_low>Low stock products</label></div>';
          if (current_selector == 'selector_inv') {
            html += '<form id=selected_form><ul id=selected></ul></form>\n';  
          }
          html += '</div>\n';
          break;
        case 'specific':
          html += '<div class=selector id=selector_specific_wrap><input type=radio name=selector value=specific id=selector_specific';
          if (current_selector == 'selector_specific') {
            html += ' checked';
          }
          html += '><label for=selector_specific>Specific ' + name + ': </label><input type=text name=selector_search id=selector_search size=25 value=\"'+reports_matrix[spec].search_text+'\">';
          html += '<div id=matches></div>';
          if (current_selector == 'selector_specific') {
            html += '<form id=selected_form><ul id=selected></ul></form>\n';  
          }
          html +='</div>\n';
          break;
        case 'all':
          html += '<div class=selector id=selector_all_wrap><input type=radio name=selector value=all id=selector_all';
          if (current_selector == 'selector_all') {
            html += ' checked';
          }
          html += '><label for=selector_all>All ' + name + '</label></div>\n';
          break;
      }
    } 
    if (spec == "products") {
      html += '<p><label for=combine_options>Combine product options</label><input type=checkbox name=combine_options id=combine_options';
      if (state.reports_matrix['products'].combine_options) {
        html += ' checked ';
      }
      html +='></p>\n';
    }
    
    if (spec == "locations") {
      html += '<p><label for=combine_zips>Combine by state or country</label><input type=checkbox name=combine_zips id=combine_zips';
      if (state.reports_matrix['locations'].combine_zips) {
        html += ' checked ';
      }
      html += '></p>\n';
    }
    html += "</div>";
    
    //$('#selectors').html(html);
    $('#reports').after(html);
    if (state.time_unit == 'single') 
      $('#selector_all').parent().css({display:'none'});
    else
      $('#selector_all').parent().css({display:'block'});
    
    
    /*if (current_selector == "selector_specific" && state.reports_matrix[state.report_section.substr(4)].specific_id_list.length)
      get_matches($('#selector_specific'));*/
  }
  
  if ($('#selectors').find(':checked').length) {
    //get_matches($('#selectors').find(':checked'));
    generate_report();
    chart_spawned = 1;
  }
  
  
  $('#reports').find('input').on('click',function() { 
    if (chart)
      chart.showLoading("Loading...");
      
    if (state.display_type == 'show_table_ck') {
      //alert("loading 1");
      $('#table-container').html("<h3>Loading...</h3>");
    }
    
    var section = state.report_section.substr(4);
    if ($(this).is(':checked')) {
      var report = $(this).attr('name') + "=on";
      if (state.reports_matrix[section].current_reports.length)
        state.reports_matrix[section].current_reports = state.reports_matrix[section].current_reports + "&" + report;
      else
        state.reports_matrix[section].current_reports = report;
      load_chart_data(get_date_from_input(0), get_date_from_input(1), state.time_unit,  report, state.report_section, get_id_list());
    } else {
      var ck_name = $(this).attr('name');
      var report = ck_name + "=on";
      state.reports_matrix[section].current_reports = 
        state.reports_matrix[section].current_reports.replace(new RegExp(report + "&|&" + report + "|" + report , 'g'), "");
      if (options.chart.defaultSeriesType != "pie") {
        for (var i = chart.series.length-1; i >= 0; i--) {
          if (chart.series[i].options.report == ck_name)  {
            chart.series[i].remove(false);
          }
          
        }
        make_table();
      } else {
        for (var i = chart.series.length-1; i >= 0; i--) {
          if (chart.series[i].options.id == ck_name) {
            chart.series[i].remove();
            options.series.splice(i,1);
            
          }
        }
        make_table();
        set_pie_sizes();
        chart.destroy();
        chart = new Highcharts.Chart(options); 
        //chart.redraw();
      }
      memorize(1);
    }
  });
  
  $('#selector_top').on('click',function() {  
    kill_chart(1);
    var p = $('#selected_form').detach();
    $('#selector_top').parent().append(p);
    state.reports_matrix[state.report_section.substr(4)].selector = "selector_top";
    state.reports_matrix[state.report_section.substr(4)].specific_id_list = '';
    get_matches($('#selector_top'));
  });
  
  //change the number of top items to display
  $('#selector_top_count').on('change',function() { 
    state.reports_matrix[state.report_section.substr(4)].top_count = $(this).val();
    $('#selector_top').click();
  });
  $('#selector_inv_count').on('change',function() { $('#selector_inv').click();/*attr('checked', true);*/ });
  $('#selector_inv_low').on('change',function() { $('#selector_inv').click();/*attr('checked', true);*/ });
  $('#selector_inv_out').on('change',function() { $('#selector_inv').click();/*attr('checked', true);*/ });
  
  //click on search field for specific items
  $('#selector_search').bind('focusin', function() { 
    state.reports_matrix[state.report_section.substr(4)].selector = "selector_specific";
    if ($('#selector_search').val() == reports_matrix[state.report_section.substr(4)].search_text) 
      $('#selector_search').val(''); 
    else {
      get_matches(this);
    }
    
  });
  
  $(document).mouseup( function (event) { if (!$(event.target).closest('#matches').length) $('#matches').html('');});
  
  //type stuff into search field
  //$('#selector_search').on('keyup',function() { get_matches(this); });
  $('#selector_search').bind('paste keyup', function() { 
    state.reports_matrix[state.report_section.substr(4)].selector = "selector_specific";
    setTimeout(function() { get_matches($('#selector_search')); }, 50);
    
  });
  
  
  //click on low stock items
  $('#selector_inv').on('click',function() { 
    state.reports_matrix['inventory'].selector = "selector_inv";
    state.reports_matrix['inventory'].specific_id_list = '';
    var p = $('#selected_form').detach();
    $('#selector_inv').parent().append(p);
    get_matches($('#selector_inv'));    
  });
   
  //click on all items
  $('#selector_all').on('click',function() {  
    state.reports_matrix[state.report_section.substr(4)].selector = "selector_all";
    state.reports_matrix[state.report_section.substr(4)].specific_id_list = '';
    kill_chart(1);
    get_matches($('#selector_all'));
  } );
  
  //click on specific items radio button
  $('#selector_specific').on('click',function() { $('#selector_search').focusin();} );
  
  //click on specific items radio button
  $('#selector_specific').on('change',function() {  kill_chart(1); } ) ;
  
  
  //click on search result
  $(document).on('click', '.match', function() { 
    var section = state.report_section.substr(4);
    state.reports_matrix[section].selector = "selector_specific";
    if ($('#selected_form').prev().attr('id') != "matches") {
      var p = $('#selected_form').detach();
      $('#selector_specific').parent().append(p);
    }
    if ($('#selector_specific').attr('checked') == false) {
      $('#selector_specific').attr('checked', true);
      kill_chart(1);
    }
    var t = $(this);
    var id = t.attr('id');
    $(this).attr('id','used_'+id);
    if ((id.search('used') == -1) && ($('#selected').find('#' + id).length == 0)) {
      var html = '<li><input type=checkbox class=selected_input name=which value=' + id.substr(6) + ' id='+id+' checked><a title=\"'+t.attr('title').replace(/\"/g,"&quot;")+'\">' + t.html() + '</a></li>\n';
      $(html).appendTo($('#selected'));
      $('#'+id).on('click',function() { selected_click(this);});
      id = id.substr(6);
      if (isNaN(id))
        id = "'" + id + "'";
      
      if (state.reports_matrix[section].specific_id_list.length)
        state.reports_matrix[section].specific_id_list = state.reports_matrix[section].specific_id_list + "," + id;
      else
        state.reports_matrix[section].specific_id_list = id;
      
      chart_from_matches(id);
    }    
    //$('#selector_search').focusin();
  });
  
    //click on combine options
  $('#combine_options').on('change',function() {
    if ($('#combine_options:checked').length > 0)
      state.reports_matrix['products'].combine_options = 1;
    else
      state.reports_matrix['products'].combine_options = 0;
    state.reports_matrix['products'].specific_id_list = '';
    kill_chart(1);
    if (state.reports_matrix[state.report_section.substr(4)].selector != "selector_specific")
      get_matches($('#' + state.reports_matrix[state.report_section.substr(4)].selector));
    else
      memorize(1);
  });
  
      //click on combine zips
  $('#combine_zips').on('change',function() {
    if ($('#combine_zips:checked').length > 0)
      state.reports_matrix['locations'].combine_zips = 1;
    else
      state.reports_matrix['locations'].combine_zips = 0;
    state.reports_matrix['locations'].specific_id_list = '';
    kill_chart(1);
    if (state.reports_matrix[state.report_section.substr(4)].selector != "selector_specific")
      get_matches($('#' + state.reports_matrix[state.report_section.substr(4)].selector));
    else
      memorize(1);
  });
  
  
  
  
 
  
  
  //show_group_items();
  return chart_spawned;
  
}


function selected_click(el) {
  if (chart)
    chart.showLoading("Loading...");
    
  if (state.display_type == 'show_table_ck') {
    //alert("Loading 2");
    $('#table-container').html("<h3>Loading...</h3>");
  }
    
  var id = $(el).attr('id').substr(6);
  
  
  var section = state.report_section.substr(4);
  if (state.report_section == "per_inventory" ||  $(el).is(':checked')) {
    if (isNaN(id))
      id = "'"+id+"'";
    
    
    if (state.reports_matrix[section].selector == "selector_specific") {
      if (state.reports_matrix[section].specific_id_list.length)
        state.reports_matrix[section].specific_id_list = state.reports_matrix[section].specific_id_list + "," + id;
      else
        state.reports_matrix[section].specific_id_list = id;
    }
    
    chart_from_matches(id);
    
    
  } else {
  
    if (state.reports_matrix[section].selector == "selector_specific") {
      var idfix = id;
      if (isNaN(idfix))
        idfix = "'"+idfix+"'";
      var ar = state.reports_matrix[section].specific_id_list.split(",");
      for (var k in ar) { if (ar[k] == idfix) { ar.splice(k,1); break; }}
      state.reports_matrix[section].specific_id_list = ar.toString();
      memorize(1);
    }
    
    if (options.chart.defaultSeriesType != "pie") {
      for (var i = chart.series.length-1; i >= 0; i--) {
        if (chart.series[i].options.item_id == id) {
          chart.series[i].remove(false);
        }
      }
      /*alert("redraw 2");
      chart.isDirtyBox = false;
      chart.isDirtyLegend = false;*/
      make_table();
    } else {
      for (var i = 0; i < chart.series.length; i++) {
        for (var j = chart.series[i].data.length-1; j >=0 ; j--) {
          //alert(cid_ar + "   vs   " + id);
          if (chart.series[i].data[j].id == id) {
            chart.series[i].data[j].remove();
            options.series[i].data.splice(j,1);
            
          }
        }
      }
      make_table();
    }
  }
}

function print_object(o) {
  var text = "";
  for (var i in o)
    text += i + "   ";
    //text += "o["+i+"]="+o[i]+"    ";
  alert(text);
}



//$(document).ready(function() {
$(window).on('load',function() {

    //state.time_unit = $("input[name='unit']:checked").val();  
  $('#' + state.date_format).attr('checked','checked');
  $('#' + state.week_start).attr('selected','selected');
  $('#top_max').val(state.top_max);
  $('#configure_popup').on('click',function() { $('#popup').modal({overlayClose:true, persist: false}); });
  $('#save_options').on('click',function() {
    state.date_format = $("input[name='date_format']:checked").val();
    state.week_start = $('#week_start option:selected').attr('id');
    state.top_max = $('#top_max').val();
    state.start = '';
    state.end = '';
    memorize(2);
    $.modal.close();
  });
  
  $('#cancel_options').on('click',function() {
    $.modal.close();
  });
  
  if (state.date_format == "dmy") {
    datepicker_date_format = "dd.mm.yy";
    highcharts_date_format = "%d.%m.%Y";
    week_date_format = "%d.%m";
  }
  else if (state.date_format == "ymd") {
    datepicker_date_format = "yy-mm-dd";
    highcharts_date_format = "%Y-%m-%d";
    week_date_format = "%m-%d";
  } else {
    datepicker_date_format = "mm/dd/yy";
    highcharts_date_format = "%m/%d/%Y";
    week_date_format = "%m/%d";
  }
  

  Highcharts.setOptions({
      global: {
          useUTC: false
      }
  });
  
  
  var chart_spawned = 0;
  $('#nav_menu, #reports_top_ui, #reports_left_ui, #footer').addClass('noprint');
  
  

  var today = new Date();
  $('#' + state.shortcut).attr('selected','selected');
  dates_from_shortcut(0);
  

    
  $('.date').datepicker({ changeMonth: true, changeYear: true, minDate: new Date(2005, 0, 1), maxDate: today, dateFormat: datepicker_date_format,
    onChangeMonthYear: function(year, month, inst) { 
      var day = 1;
      var d = $(this).datepicker("getDate");
      if (d != null)
        day = d.getDate();
      $(this).val(Highcharts.dateFormat(highcharts_date_format, (new Date(year, month-1, day)).getTime()));
    }

  });
  //$('#end').datepicker({ changeMonth: true, changeYear: true, minDate: new Date(2005, 0, 1), maxDate: today});
  
  $('#' + state.time_unit).attr("checked", "checked");
  $('#' + state.display_type).attr("checked", "checked");
  
  $('#shortcut').on('change',function() {
    state.shortcut = $('#shortcut option:selected').attr('id');
    dates_from_shortcut(1);
  });
  
  
  
  
  //click on generate report
  $('#button_generate_report').on('click',function() { 
    generate_report();
  });
  
  
  //click on report type
  $('#per').find('li').on('click',function() { 
    kill_chart(1);
    $('#' + state.report_section).removeClass("current_per");
    state.report_section = $(this).attr('id');
    display_available_reports();
    
    
    if (state.report_section.search('per_global') != -1) {
      chart_from_matches(get_id_list());
    }
  });

  //click on time unit
  $('#unit').find('input').on('change',function () {
    kill_chart(0);
    state.time_unit = $("input[name='unit']:checked").val();
    var spec = state.report_section.substr(4);
    if (state.time_unit == 'single' && reports_matrix[spec].overview_type == 'pie' && reports_matrix[spec].selectors.length == 0) 
      $('#reports').css({display:'none'});
    else
      $('#reports').css({display:'block'});
      
    if (state.time_unit == 'single') {
      $('#selector_all').parent().css({display:'none'});
      if ($('#selector_all').is(':checked')) {
        $('#selector_top').click();
        return;
      }
    }
    else
      $('#selector_all').parent().css({display:'block'});
    
    chart_from_matches(get_id_list());
  });
  
  

    
  
  //click on show table
  $('#show_table_ck').on('change',function () {
    show_table(1);
    make_table();
  });
  
  $('#show_chart_ck').on('change',function () {
    show_chart(1);
    make_table();
  });

  
  chart_spawned = display_available_reports(); 
  
  if (!chart_spawned) {
    chart_from_matches(get_id_list());
  }


  

  //chart = new Highcharts.Chart(options);       
});

function get_date_from_input(input) {
  if (input == 0) 
    state.start = input = $('#start').val();
  else
    state.end = input = $('#end').val();
    
  if (state.date_format == "dmy") {
    var spl = input.split(".");
    return new Date(parseInt(spl[2],10), parseInt(spl[1],10)-1, parseInt(spl[0],10));
  } else if (state.date_format == "ymd") {
    var spl = input.split("-");
    return new Date(parseInt(spl[0],10), parseInt(spl[1],10)-1, parseInt(spl[2],10));
  } else {
    var spl = input.split("/");
    return new Date(parseInt(spl[2],10), parseInt(spl[0],10)-1, parseInt(spl[1],10));
  }
  
}





function configure_chart(unit, per, start, end) {
  //alert(real_start);
  var ms = 86400000;
  
  //series_map = [];
  
  options.chart.defaultSeriesType = "column";
  //options.chart.margin = [0, 0, 0, 0];
  
  
  options.plotOptions.series.dataLabels.enabled = false;
  
  //options.plotOptions.series.animation = true;
  options.chart.zoomType = 'x';
  options.xAxis.labels.enabled = true;
  
  //options.xAxis.min = start.getTime();
  //options.xAxis.max = end.getTime();
  options.xAxis.type = 'datetime';
  options.xAxis.minPadding = 0.1;
  options.xAxis.maxPadding = 0.1;
  
  options.yAxis[0].title.text = config.currency.code + " amount"
  
  //options.plotOptions.series.pointWidth = 10;
  //options.plotOptions.series.pointPadding = 0.1;
  //options.plotOptions.series.groupPadding = 0.1;
  //options.plotOptions.series.minPointLength = 3;
  //options.xAxis.startOnTick = true;
  //options.xAxis.endOnTick = true;
  
  options.title.text = reports_matrix[per.substr(4)].pretty_name + " report for " 
    + Highcharts.dateFormat(highcharts_date_format, start.getTime()) + " - " + Highcharts.dateFormat(highcharts_date_format, end.getTime());
  options.legend.enabled = true;
  options.tooltip.enabled = true;
  options.plotOptions.series.enableMouseTracking = true;
  options.subtitle = null;
  
  options.yAxis[1].title.text = reports_matrix[per.substr(4)].yaxis;
  
  options.xAxis.dateTimeLabelFormats.day=week_date_format;
  options.xAxis.dateTimeLabelFormats.week=week_date_format;
  
  options.xAxis.startOfWeek = week[state.week_start.substr(3)];
    

  
  
  
  switch(unit) {
  
    case "date":
      //options.chart.defaultSeriesType = "area";
      ms = 86400000;
      options.xAxis.maxZoom = ms;    
      options.xAxis.tickInterval =  ms;
      options.plotOptions.series.pointRange = ms;
      options.xAxis.minRange = ms;
      //options.plotOptions.series.pointStart = real_start.getTime();
      //options.plotOptions.series.pointInterval = 86400000;
      options.tooltip.formatter = function() {
        var val = this.y;
        if (this.series.options.unittype == 1)
          val = config.currency.formatter(val,0);
        return "<b>" + this.series.name + '</b><br/>' + Highcharts.dateFormat(highcharts_date_format+': ', this.x) + val;
      }
      break;
    case 'week':
      //options.chart.defaultSeriesType = "line";
      ms = 604800000;
      options.xAxis.maxZoom = ms;    
      options.xAxis.tickInterval =  ms;
      options.plotOptions.series.pointRange = ms;
      options.xAxis.minRange = ms;
      options.tooltip.formatter = function() {
        var val = this.y;
        if (this.series.options.unittype == 1)
          val = config.currency.formatter(val,0);
        return "<b>" + this.series.name + '</b><br>' + Highcharts.dateFormat('Week of '+week_date_format+': ', this.x) + val;
      }
      break;
    case 'month':
      //options.chart.defaultSeriesType = "line";
      ms = 2635200000;
      options.xAxis.maxZoom = ms;    
      options.xAxis.tickInterval =  ms;
      options.plotOptions.series.pointRange = ms;
      options.xAxis.minRange = ms;
      options.tooltip.formatter = function() {
        var val = this.y;
        if (this.series.options.unittype == 1)
          val = config.currency.formatter(val,0);
        return "<b>" + this.series.name + '</b><br/>' + Highcharts.dateFormat('%b \'%y: ', this.x) + val;
      }
      break;
    case "single":
      options.xAxis.startOnTick = false;
      options.xAxis.endOnTick = false;
      if (reports_matrix[per.substr(4)].overview_type == 'pie') {
        options.chart.defaultSeriesType = "pie";
        options.xAxis.labels.enabled = false;
        options.chart.zoomType = null;

        
        //options.legend.enabled = false;
        if (reports_matrix[per.substr(4)].selectors.length > 0) {
          options.plotOptions.series.dataLabels = {
            enabled: true,
            distance: -40,
            formatter: function() {
                //print_object(this.series);
                var sum = 0;
                for (var i in this.series.data)
                  sum += this.series.data[i].y;
                  //alert(i + "    " + this.series.data[i]);
                if (this.y/sum > 0.008 * (this.series.index + 0.7) * ((this.y + '').length+1)) {
                  if (this.series.options.unittype == 1)
                    return config.currency.formatter(this.y,0);
                  else
                    return this.y;
                }
            },
            color: 'white'
          }
        
          options.tooltip.formatter = function() {
            var val = this.y;
            if (this.series.options.unittype == 1)
              val = config.currency.formatter(val,0);
            if (this.point.name != this.series.name)
              return "<b>" + this.series.name + "</b><br/>" + this.point.name + ': '+ val;
            else
              return "<b>" + this.point.name + '</b>: '+ val;
          }
        } else {
          options.tooltip.enabled = false;
          options.legend.enabled = false;
          options.plotOptions.series.enableMouseTracking = false;
          options.plotOptions.series.dataLabels = {
            enabled: true,
            distance: 50,
            formatter: function() {
              var r = this.point.name + ": ";
              if (this.series.options.unittype == 1)
                return r + config.currency.formatter(this.y,0);
              else
                return r + this.y;
            },
            color: 'black'
          }
        }
      } else {
        options.chart.zoomType = null;
        options.xAxis.type = 'linear';
        //options.xAxis.min = null;
        //options.xAxis.max = null;
        options.xAxis.labels.enabled = false;
        options.tooltip.formatter = function() {
          var val = this.y;
          if (this.series.options.unittype == 1)
            val = config.currency.formatter(val,0);
          return "<b>" + this.series.name + '</b><br/>' + val;
        }
      }
      break;
  }
    

    
  
  return ms;
  
} 


function twiddle_dates(start, end, unit) {
  //alert("Input:" + start + "           " + end + "             " + unit);
  start.setHours(0);
  end.setHours(0);
  if (unit == 'week') {
    var start_adjustment = week[Highcharts.dateFormat('%a', start.getTime())] - week[state.week_start.substr(3)]
    if (start_adjustment < 0)
      start_adjustment += 7;
    
      
    var end_adjustment = week[Highcharts.dateFormat('%a', end.getTime())] - week[state.week_start.substr(3)]
    if (end_adjustment < 0)
      end_adjustment += 7;
    
    
    start.setDate(start.getDate() - start_adjustment); //force Monday
    end.setDate(end.getDate() + 6 - end_adjustment); //force Sunday
  }
  
  if (unit == 'month') {
    
    start.setDate(1); //force 1st
    end.setMonth(end.getMonth() + 1);
    end.setDate(1);
    end.setDate(end.getDate()-1); //force last
  }
  
  if (unit == 'year') {
    start.setMonth(0,1);
    end.setMonth(11,31);
  }
  //alert("Result:"+ start + "           " + end);
  return [start, end];
}


function load_chart_data(start, end, unit, report, per, which) {
  
  var tsTimeStamp= new Date().getTime();

  var dates = twiddle_dates(start, end, "bypass"/*unit*/);
  start = dates[0];
  end = dates[1];
  
  var reports = report.split("&");
  var rep_count = reports.length;
      

  
  
  
  var report_request = "start=" + Highcharts.dateFormat('%Y-%m-%d', start.getTime()) + "&end=" + Highcharts.dateFormat('%Y-%m-%d', end.getTime()) + "&unit=" + unit + "&" + report + "&time=" + tsTimeStamp + "&ajax=gimmereports" + 
  "&per=" + per + "&which=" + which + "&week_start=" + week[state.week_start.substr(3)] + "&state=" + memorize(0);
  if (state.reports_matrix['products'].combine_options)
    report_request += '&combine_options=1';
    
  if (state.reports_matrix['locations'].combine_zips)
    report_request += '&combine_zips=1';
  //alert(report_request);
  $.get("stathandler.cgi",report_request, 
  /*$.ajax({
  async: false,
  data: report_request,
  success: */
    function(data) {
    

      //alert(data);
      
      if (data.search("ss_signin.cgi") > -1) {
        window.location = "stathandler.cgi";
        return;
      }

      var next_date;
      //var compare_dates;
      
      var get_date;
      var add_point;
      switch (unit) {
        case "date": 
          get_date = function(line) {return new Date(line.substr(0,4), parseInt(line.substr(5,2),10) - 1, line.substr(8,2));  }
          next_date = function(d) { var dd= new Date(d.getTime()); dd.setDate(dd.getDate() + 1); return dd; }
          //add_point = function(data, time, val) {  data.push(val); }
          add_point = function(data, time, val) {  data.push([time, val]); }
          break;
        case "week":
          get_date = function(line) { return new Date(line.substr(0,4), parseInt(line.substr(5,2),10) - 1, line.substr(8,2));  }
          next_date = function(d) { var dd= new Date(d.getTime()); dd.setDate(dd.getDate() + 7); return dd; }
          //add_point = function(data, time, val) {  data.push(val); }
          add_point = function(data, time, val) { data.push([time, val]); }
          break;
        case "month":
          get_date = function(line) {return new Date(line.substr(0,4), parseInt(line.substr(5,2),10) - 1 , 1);  }
          next_date = function(d) { var mon = d.getMonth(); var yr=d.getFullYear(); mon++; if (mon == 12) { mon = 0; yr++; } return new Date(yr, mon, 1); }
          add_point = function(data, time, val) {  data.push([time, val]); }
          break;
        case "single":
          get_date = function(line) {return end; }
          next_date = function(d) { return new Date(3000,0,1); }
          add_point = function(data, time, val) {  data.push(["Overview", val]); }
          break;
      }
      
      
      

      
      
      


        
      
        
          
      
      var lines = data.split('\6');
      var point_count = lines.length-1;
      
      
      var need_new = false;
      if (!(options.series.length > 0 || (chart && chart.series.length > 0))) {
        var ms = configure_chart(unit, per, start, end);
        need_new = true;
        if (state.display_type == 'show_table_ck') {
          //alert("Loading 3");
          $('#table-container').html("<h3>Loading...</h3>");
        }
        global_color_pointer=-1;
      }
      
      
      if (reports[0].length < 2)
        return;
      

      
      var series_array = [];
      var cleared_reports =[];
      
      if (point_count > 0) {
        if (options.chart.defaultSeriesType != 'pie') {
          
            
          
          if (need_new || chart.series.length == 0) {
            var real_start = get_date(lines[0]);
            var real_end = get_date(lines[lines.length-2]);
            //configure_chart(unit, report, rep_count, which.split(',').length, per, start, end);
          } else {
            var series_max_data = chart.series[chart.series.length-1].data;
            var real_start = new Date(Math.min(get_date(lines[0]).getTime(), series_max_data[0].x));
            var real_end = new Date(Math.max(get_date(lines[lines.length-2]).getTime(), series_max_data[series_max_data.length-1].x));
          } 
          
          if (need_new) {
            var count = (real_end.getTime() - real_start.getTime())/ms;
            //alert(count);
            if (options.xAxis.labels.enabled) {
              options.xAxis.labels = {
                step: Math.max(1,Math.round(count / 20)),
                style: {
                    font: 'normal 10px Arial, sans-serif'
                }
              }
              
              if (count > 10) {
                options.xAxis.labels.rotation = -45;
                options.xAxis.labels.y = 30;
              }
            }
            
            if (count > 100) {
              options.subtitle = {
                text: "If you can't see the chart try zooming in by selecting a part of the chart.",
                align: 'left'
              } 
            }
            
            if (count > 200) {
              options.xAxis.tickLength = 0;
            } else {
              options.xAxis.tickLength = 5;
            }
            
            chart = new Highcharts.Chart(options); 
            chart.showLoading("Loading...");
          }

          //real_start = start;
          //real_end = end;
          
          var populate_series = function(item_id) {
            
            var item_name = decodeEntities($('#selected').find('#match_' + item_id).next().html());
            //alert(item_name);
            
            var full_item_name = $('#selected').find('#match_' + item_id).next().attr('title');
            
            

            
            if (item_id != '-') {
              var name_appendix = ": " + item_name;
              
            } else {
              var name_appendix = "";
              item_name = full_item_name = "summary";
            }
            for (var j = 0; j < rep_count; j++) {
                  var cleared_report = reports[j].substr(0,reports[j].search('='));
                  cleared_reports.push(cleared_report);
                  var series = {data: [], id: (item_id + "_" + cleared_report), name: name_map[cleared_report].name + name_appendix, 
                    item_id:item_id, item_name: item_name, full_item_name: full_item_name, report:cleared_report};
                  
                  if (name_map[cleared_report].type == 2) {
                    series.type = 'line'; series.yAxis = 1; /*series.color= '#FF0000'; */
                    series.unittype = 2;
                    series.stacking = null;
                  } else {
                    series.unittype = 1;
                    if (unit != 'single') {
                      stack = true;
                      if (name_map[cleared_report].hasOwnProperty('stack')) {
                        stack = name_map[cleared_report].stack
                      }
                      
                      if (stack)
                        series.stack = item_id;
                      else
                        series.stacking = null;
                    }
                    else
                      series.stacking = null;
                  }
                  series_array[series.id] = series;
                  
                  
            }
            
            
          }
          
          var populate_data = function(time, items) {
              //var d = get_date(items[0]);
              var item_id = items[1];
              for (var s = 0; s < rep_count; s++) {
                add_point(series_array[item_id + "_" + cleared_reports[s]].data, time, parseFloat(items[s+2]));
              }
          }
          
          

            
            var ids_count = 1;
            var c_d_ar = [];
            var zeroes_ar = [];
            var ids = [];
            c_d_ar['-'] = real_start;
            if (which.length > 0) {
              ids = which.split(',');
              ids_count = ids.length;
              for (var i in ids) {
                if (isNaN(ids[i]))
                  ids[i] = ids[i].substr(1,ids[i].length-2);
                c_d_ar[ids[i]] = real_start;
                populate_series(ids[i]);
              }
            } else {
              ids[0] = "-";
              populate_series("-");
            }
            
            for (var s = 0; s < rep_count + 2; s++)
              zeroes_ar.push(0);
              
          
            if (unit != 'single') {
              var start_time = real_start.getTime();
              var end_time = real_end.getTime();
              
              var line_pointer = 0;
              var line_time;
              var expected_time;
              var item_id;
              while (line_pointer != point_count)
              {
                items = lines[line_pointer].split(sep);
                line_time = get_date(lines[line_pointer]).getTime();
                item_id = items[1];
                while ((expected_time = c_d_ar[item_id].getTime()) != line_time) {
                  zeroes_ar[1] = item_id;
                  populate_data(expected_time, zeroes_ar);
                  c_d_ar[item_id] = next_date(c_d_ar[item_id]);
                }
                populate_data(line_time, items);
                line_pointer++;
                c_d_ar[item_id] = next_date(c_d_ar[item_id]);
              }
            
            
              for (var i in ids) {
                item_id = ids[i];
                zeroes_ar[1] = item_id;
                while ((expected_time = c_d_ar[item_id].getTime()) <= end_time) {
                  populate_data(expected_time, zeroes_ar);
                  c_d_ar[item_id] = next_date(c_d_ar[item_id]);
                }
              }
            
            

            
            
              for (var i = 0; i < chart.series.length; i++) {
                //var i = 0;
                var c_d_time;
                var zeroes_prepend = [];
                var zeroes_append = [];
                var series_start = chart.series[i].data[0].x;
                
                var c_d = real_start;
                while ((c_d_time = c_d.getTime()) < series_start) {
                  add_point(zeroes_prepend, c_d_time, 0);
                  c_d = next_date(c_d);
                }
                
                var series_end = chart.series[i].data[chart.series[i].data.length-1].x;
                c_d = new Date(series_end);
                c_d_time = series_end;
                while (c_d_time < end_time) {
                  c_d = next_date(c_d);
                  add_point(zeroes_append, c_d_time = c_d.getTime(), 0);
                }
                  
                if (zeroes_prepend.length + zeroes_append.length > 0) {
                //for (var i in chart.series) {
                  var original_data = chart.series[i].options.data;
                  /*var original_data = [];
                  for (var p in chart.series[i].data)
                    original_data.push([chart.series[i].data[p].x, chart.series[i].data[p].y]);*/
                  chart.series[i].setData(zeroes_prepend.concat(original_data, zeroes_append), false);            
                  
                }
              
                
              }
              
              
            } else {
              items = lines[0].split(sep);
              //alert(end + "    " + end.getTime());
              populate_data(0, items);
            }
            
            for (var i in series_array) {
              if (chart.get(series_array[i].id) == null)
                chart.addSeries(series_array[i], false);
            }

            

              
            
            
            
            

              

        
        } else {
        
          if (need_new) {
            chart = new Highcharts.Chart(options); 
            chart.showLoading("Loading...");
          }
        
          if (reports_matrix[per.substr(4)].selectors.length > 0) {
            var series_indexes = [];
            var index;
            
            find_series_by_id = function(id) {
              for (var i = 0; i < options.series.length; i++)
                if (options.series[i].id == id)
                  return i;
              return -1;
            }
            
            
            for (var j = 0; j < rep_count; j++) {
              cleared_report = reports[j].substr(0,reports[j].search('='));
              //cleared_reports.push(cleared_report);
              
              //series_array[series.id] = series;
              if ((index = find_series_by_id(cleared_report)) == -1) {
                var series = {data: [], id: cleared_report, name: name_map[cleared_report].name, unittype:name_map[cleared_report].type};
                series_indexes.push(options.series.length);
                options.series.push(series);
              } else
                series_indexes.push(index);
            }
            
            

            var item_id;
            var items;
            
            var p_add_ser = 0;
            
            var current_point_count = options.series[0].data.length;
            
            if ($('#selected').find(':checked').length > 0) {
              for (var i in options.series) {
                options.series[i].showInLegend = false;
              }
            
              get_name = function(item_id, series_name) { return $('#selected').find('#match_' + item_id).next().html();}
              get_full_name = function(item_id, series_name) {return $('#selected').find('#match_' + item_id).next().attr('title');}
              get_color = function() {
                var v_color;
                if (options.series[series_indexes[s]].data.length + 1 > current_point_count) {
                  //if adding more points than already are in any of the series -- get new color value
                  global_color_pointer = (global_color_pointer + 1)%9;
                  v_color = options.colors[global_color_pointer];
                  current_point_count++;
                  p_add_ser = series_indexes[s];
                } else  {
                  //otherwise -- find a point with matching id in another series and get its color
                  for (var j = 0; j < options.series[p_add_ser].data.length; j++) {
                    if (options.series[p_add_ser].data[j].id == item_id) {
                      v_color =  options.series[p_add_ser].data[j].color;
                      break;
                    }
                  }  
                }
                return v_color;
              }
            } else {
              get_name = function(item_id, series_name) { return series_name;}
              get_full_name = function(item_id, series_name) {return series_name;}
              get_color = function() {return null;}
            }
            
            
            for (var i = 0; i < point_count; i++) {
              
              items = lines[i].split(sep);
              item_id = items[1];
              
              for (var s = 0; s < rep_count; s++) {
                var duplicate = 0;
                for (var j = 0; j < options.series[series_indexes[s]].data.length; j++) {
                  if (options.series[series_indexes[s]].data[j].id == item_id) {
                    duplicate = 1;
                    break;
                  } 
                }
                if (!duplicate) {
                  options.series[series_indexes[s]].data.push({id:item_id, name:get_name(item_id,options.series[series_indexes[s]].name), y:parseFloat(items[s+2]), 
                    color:get_color(), full_name:get_full_name(item_id, options.series[series_indexes[s]].name)});
                }
              }
            }

            set_pie_sizes();
          } else {
            var series = {data: [], name: reports_matrix[per.substr(4)].pretty_name, unittype:1};
            options.series.push(series);
            items = lines[0].split(sep);
            for (var s = 0; s < rep_count; s++) {
              cleared_report = reports[s].substr(0,reports[s].search('='));
              options.series[0].data.push({name: name_map[cleared_report].name, y:parseFloat(items[s+2]), full_name:name_map[cleared_report].name});
            }
          }
          
          
          if (chart)
            chart.destroy();
          //alert("before new chart");
          //alert(JSON.stringify(options));
          //memorize(1);
          chart = new Highcharts.Chart(options); 
          //chart.redraw();
          
        }
        
        make_table();  
        //print_series();
      } else //if (need_new || chart.series.length == 0) 
      {
        //alert("!");
        html = '<h1 class=table_header>'+ options.title.text +'</h1>';
        html += '<p class=center>No data for this time period.</p>';
        //alert("none1");
        $('#chart-container').html(html);
        
        
        /*if (state.display_type == "show_chart_ck") {
          $('#chart-container').html(html);
        } else {
          $('#table-container').html(html);
        }*/
        
        make_table();  

      }
      
    }
  );
  
  
}

function set_pie_sizes() {
  var quota = 95/options.series.length;
  var size = 95;
  options.series[0].showInLegend = true;
  for (var i in options.series) {
    
    options.series[i].size = size+"%";
    size = Math.round(size-quota);
    options.series[i].innerSize = Math.max(size,1)+"%";
    //alert("i:"+i+"  size:"+options.series[i].size+"  innerSize:"+options.series[i].innerSize);
  }
}




function print_series() {
  var i;
  var mes = "";
  var d;
  for (i = 0; i < chart.series.length; i++) {
    var ser_vals = "";
    var j;
    for (j = 0; j < chart.series[i].data.length; j++) {
      d = new Date(chart.series[i].data[j].x);
      ser_vals += (Highcharts.dateFormat('%Y-%m-%d', d.getTime()) + ":" + chart.series[i].data[j].y + "  ");
    }
    mes += (chart.series[i].name + "   " + ser_vals + "\n");
  }
  alert(mes);
}



function make_table() {
  var series_count = 0; 
  
  if (chart) {
    chart.hideLoading();
    series_count = chart.series.length;
  }
  
  if (series_count > 0)
    redraw();
      
  if ($('#show_table_ck').is(':checked')) { 
    $('#table-container').html("");
    
    var html ='';
    
    
    var series;
    var unit = state.time_unit;
    
    
    html += '<h1 class=table_header>'+ options.title.text +'</h1>';
    
    if (series_count > 0) {
    
      


      
      var length = chart.series[0].data.length;
    
      var name = reports_matrix[state.report_section.substr(4)].name;
      if (name.length) {
        html += "<div id=group_table><label for=group_table_ck>Group "+name+" together</label><input type=checkbox name=group_table id=group_table_ck ";
        if (state.table_grouping)
          html += " checked ";
        html += "></div>";
      }
      
      html += "<a id='excel_export'>Export to Excel</a>";
      
      $(document).off('click', '#excel_export');
      $(document).on('click', '#excel_export',  function () {
        var cp = $('#table-container').clone();
        //preprocess table to make it look good in excel
        $(cp).find('th').each(function(i,e) { $(this).html($(this).attr('title')); });
        cp.table2excel({
            //exclude: ".excludeThisClass",
            //sheetName: options.title.text,
            filename: options.title.text,
            fileext: ".xls"
        });
        //window.open('data:application/vnd.ms-excel,' + $('#table-container').html());
      });
      
      
      
      
      if (state.table_grouping == 1)
        mode = 1;
      else
        mode = 0;
        
        
        
      if ($('#selected').find(':checked').length > 0)
        header = function(report, name, full_name) { return '<th title=\"'+report + ': ' + full_name.replace(/\"/g,"&quot;")+'\">' + report + ': ' + name.replace(/\"/g,"&quot;") + '</th>'};
      else if  (reports_matrix[state.report_section.substr(4)].selectors.length == 0 && options.chart.defaultSeriesType == 'pie') {
        header = function(report, name, full_name) { return '<th>' + name + '</th>'};
        mode = 1;
      }
      else
        header = function(report, name, full_name) { return '<th>' + report + '</th>'};
        
      //if (mode == 0)
  //      header = function(name, full_name) { return '<h3 title=\"'+full_names[i]+'\">'+names[i]+'</h3>\n');};
      
      //if (unit != 'single') {
      if (options.chart.defaultSeriesType != 'pie') {
        var ids = [];
        var names=[];
        var full_names=[];
        var cleared_reports=[];
        
        
        //infer reports and ids
        for (var i = 0; i < series_count; i++) {
          var good = true;
          for (var j = 0; j < ids.length && good; j++) {
            if (ids[j] == chart.series[i].options.item_id)
              good = false;
          }
          if (good) {
            ids.push(chart.series[i].options.item_id);
            names.push(chart.series[i].options.item_name);
            full_names.push(chart.series[i].options.full_item_name);
          }
          
          good = true;
          for (var j = 0; j < cleared_reports.length && good; j++) {
            if (cleared_reports[j] == chart.series[i].options.report)
              good = false;
          }
          if (good)
            cleared_reports.push(chart.series[i].options.report);
        }

        var unit_name = "Summary";
        switch (unit) {
          case "date": 
            format_time = function(time) { return Highcharts.dateFormat(highcharts_date_format, time); }
            unit_name = "Date";
            break;
          case "week":
            format_time = function(time) { return Highcharts.dateFormat('Week of ' + week_date_format, time); }
            unit_name = "Week";
            break;
          case "month":
            format_time = function(time) { return Highcharts.dateFormat('%b \'%y', time); }
            unit_name = "Month";
            break;
          case "single":
            format_time = function(time) { return Highcharts.dateFormat('%Y-%m-%d', time); }
            break;
        }
        
        //alert(mode);
        
        //make_title = function(report_name, full_name, partial_name, 
             
        if (mode == 0) {
          
          for (var i in ids) {
            html += '<table>\n';
            /*if (full_names[0] != 'summary')
              html += ('<h3 title=\"'+full_names[i].replace(/\"/g,"&quot;")+'\">'+names[i]+'</h3>\n');
            html += '<table>\n<tr>';*/
            if (full_names[0] != 'summary')
              html += '<tr><th class=table_subheader colspan='+((unit!='single')+cleared_reports.length)+'>'+full_names[i]+'</th></tr>\n';
            html += '<tr>';
            if (unit != 'single')
              html += ('<th>'+unit_name+'</th>');
            for (var rep in cleared_reports) {
              html += ('<th>' + name_map[cleared_reports[rep]].name + '</th>');
            }
            html += '</tr>\n';
            for (var dd = 0; dd < length; dd++) {
              html += '<tr>';
              if (unit != 'single')
                html += '<td>' + format_time(chart.series[0].data[dd].x) + '</td>';
              for (var rep in cleared_reports) {
                series = chart.get(ids[i] +'_' + cleared_reports[rep]);
                if (series != null) {
                  if (name_map[cleared_reports[rep]].type == 2)
                    html += '<td>' + series.data[dd].y + '</td>';
                  else
                    html += '<td>' + config.currency.formatter(series.data[dd].y,0) + '</td>';
                }
              }
              html += '</tr>\n';
            }
            html += '</table>\n';
          }
        }
        
        if (mode == 1) {
          
          html += ('<table>\n<tr>');
          
          if (unit != 'single')
            html += ('<th>' + unit_name + '</th>');
          for (var rep in cleared_reports) {
            for (var i in ids) {
              html += header(name_map[cleared_reports[rep]].name, names[i], full_names[i]);
            }
          }
          html += '</tr>\n';
          
          for (var dd = 0; dd < length; dd++) {
            html += '<tr>';
            if (unit != 'single')
              html += '<td>' + format_time(chart.series[0].data[dd].x) + '</td>';
            for (var rep in cleared_reports) {
              for (var i in ids) {
                series = chart.get(ids[i] +'_' + cleared_reports[rep]);
                if (series != null) {
                  if (name_map[cleared_reports[rep]].type == 2)
                    html += '<td>' + series.data[dd].y + '</td>';
                  else
                    html += '<td>' + config.currency.formatter(series.data[dd].y,0) + '</td>';
                }
              }
            }
            html += '</tr>\n';
          }
          html += '</table>\n';
          
        }
      } else {
        if (mode == 0) {
          for (var i = 0; i < length; i++) {
            series = chart.series[0];
            html += '<table>\n';
            if ($('#selected').find(':checked').length > 0) 
              html += '<tr><th class=table_subheader colspan='+series_count+'>'+series.data[i].full_name+'</th></tr>\n';
              //html += ('<h3 title=\"'+series.data[i].full_name.replace(/\"/g,"&quot;")+'\">'+series.data[i].name+'</h3>\n');
            html += '<tr>';
            for (var rep = 0; rep < series_count; rep++) {
              html += '<th>' + chart.series[rep].name + '</th>';
            }
            html += '</tr>\n<tr>\n';
            for (var rep = 0; rep < series_count; rep++) {
              if (chart.series[rep].options.unittype == 2/*id.search(/orders|units/i) > -1*/)
                html += '<td>' + chart.series[rep].data[i].y + '</td>';
              else
                html += '<td>' + config.currency.formatter(chart.series[rep].data[i].y,0) + '</td>';
            }
            html +='</tr></table>\n';
          }
        }
        
        if (mode == 1) {
          html += '<table>\n<tr>';

          for (var rep = 0; rep < series_count; rep++) {
            for (var i = 0; i < length; i++) {
              html += header(chart.series[rep].name, chart.series[0].data[i].name, chart.series[0].data[i].full_name);
            }
          }
          
          html += '</tr>\n<tr>';      
          for (var rep = 0; rep < series_count; rep++) {
            for (var i = 0; i < length; i++) {
              if (chart.series[rep].options.unittype == 2)
                html += '<td>' + chart.series[rep].data[i].y + '</td>';
              else
                html += '<td>' + config.currency.formatter(chart.series[rep].data[i].y,0) + '</td>';
            }
          }
          html += '</tr></table>\n';
        }
      }
    } else {
      //alert("none2");
      html += '<p class=center>No data for this time period.</p>';
    }
    $('#table-container').html(html);    
    $('#group_table_ck').on('change',function () {
      state.table_grouping = $('#group_table_ck').is(':checked');
      memorize(1);
      make_table();
    });

  }
}


function inventory_report(report, which) {
  
  var html = '<h1 class=table_header>Inventory Report</h1>\n';
  if (state.reports_matrix['inventory'].selector == 'selector_inv') {
    html += '<div id=indexed_only><label for=selector_inv_indexed>Only display products assigned to pages</label>'
    html += '<input type=checkbox name=selector_inv_indexed id=selector_inv_indexed ';
    if (state.reports_matrix['inventory'].indexed_only)
      html += " checked";
    html += '></div>';
  }
  
  which = get_id_list(); //force redo
  
  if (which.length) {
    var tsTimeStamp= new Date().getTime();
    var report_request = report + "&time=" + tsTimeStamp + "&ajax=gimmereports" + "&per=per_inventory&which=" + which + "&state=" + memorize(0);
    $.get("stathandler.cgi",report_request, 
      function(data) {
        //alert(data);
        
        if (data.search("ss_signin.cgi") > -1) {
          window.location = "stathandler.cgi";
          return;
        }
        
        var lines = data.split('\6');
        var point_count = lines.length-1;
        if (point_count > 0) {
        
          html += "<a id='excel_export'>Export to Excel</a>";
        
          $(document).off('click', '#excel_export');
          $(document).on('click', '#excel_export',  function () {
            var cp = $('#table-container').clone();
            cp.table2excel({
                filename: "Inventory Report",
                fileext: ".xls"
            });
          });
          
          html += '<table>\n';
          html += '<tr><th>Product</th><th>Quantity on hand</th><th>Low stock threshhold</th><th>Out of stock limit</th></tr>\n';
          for (var i = 0; i < point_count; i++) {
            var item = lines[i].split('\7');
            var item_id = item[0];
            var item_name = $('#selected').find('#match_' + item_id).next().html();
            var full_item_name = $('#selected').find('#match_' + item_id).next().attr('title');
            html += '<tr><td title=\"' + full_item_name + '\">' + item_name +'</td><td>' + item[1] + '</td><td>' + item[2] + '</td><td>' + item[3] + '</td></tr>\n';
          }
          html += '</table>';
                    
        } else
          html += "<p class=center>No information for selected products</p>";
        $('#table-container').html(html);
        $('#selector_inv_indexed').on('change',function() { 
          state.reports_matrix['inventory'].indexed_only = $('#selector_inv_indexed:checked').length;
          $('#selector_inv').click();
        });
      }
    );
  } else {
    html += "<p class=center>No matching products</p>";
    $('#table-container').html(html);
    $('#selector_inv_indexed').on('change',function() { 
      state.reports_matrix['inventory'].indexed_only = $('#selector_inv_indexed:checked').length;
      $('#selector_inv').click();
    });
    memorize(1);
  }

}


function memorize(separate_request) {
  var request = JSON.stringify(state).replace(/&/g, "__AMP__").replace(/'/g, "__APS__");
  //var request = JSON.stringify(options);
  //alert(request);
  if (separate_request > 0) {
    $.ajax({
      async: true,
      data: "ajax=memorize&state=" + request,
      url: "stathandler.cgi",
      success: function(data) {
        if (separate_request == 2)
          document.location.reload();
      }
    });
  }
  else return request;
}

function recall(json_state) {
  //alert("parsing:" + json_state);
  state = JSON.parse(json_state.replace(/__AMP__/g, "&").replace(/__APS__/g,"'"));
  if (state.date_format == undefined) state.date_format = 'mdy';
  if (state.week_start == undefined) state.week_start = 'ws_Sun';
  if (state.top_max == undefined) state.top_max = 50;
  
}

function show_table(state_change) {
  $('#chart-container').css({display:'none'});
  $('#table-container').css({clear: "none", "float": "left", display:'block'});
  if (state_change) {
    state.display_type = 'show_table_ck';
    memorize(1);
  }
}

function show_chart(state_change) {
  $('#chart-container').css({display:'block'});
  $('#table-container').css({clear: "both", "float": "none", display:'none'});
  if (state_change) {
    state.display_type = 'show_chart_ck';
    memorize(1);
  }
  if (chart) {
    chart.isDirtyBox = true;
    chart.isDirtyLegend = true;
    redraw();
  }

}

function dates_from_shortcut(generate) {
  var today = new Date();
  today.setHours(0);
  if (state.shortcut == 'custom') {
    
    if (state.start.length) {
      $('#start').val(state.start);
    } else
      $('#start').val(Highcharts.dateFormat(highcharts_date_format, today.getTime()));//.val("01/01/"+ today.getFullYear());
    
    if (state.end.length)
      $('#end').val(state.end);
    else
      $('#end').val(Highcharts.dateFormat(highcharts_date_format, today.getTime()));
      
    $('#button_generate_report').css({display:'inline'});
    $('#custom_dates').css({display:'inline'});
  } else {
    
    $('#button_generate_report').css({display:'none'});
    $('#custom_dates').css({display:'none'});
    var dates = [new Date(), new Date()];
    switch (state.shortcut) {
      case 'cur_day':
        dates = twiddle_dates(dates[0], dates[1], 'day');
        
        break;
      case 'cur_week':
        dates = twiddle_dates(dates[0], dates[1], 'week');
        dates[1] = today;
        break;
      case 'cur_month':
        dates = twiddle_dates(dates[0], dates[1], 'month');
        dates[1] = today;
        break;
      case 'cur_year':
        dates = twiddle_dates(dates[0], dates[1], 'year');
        dates[1] = today;
        break;
      case 'all':
        dates[0].setFullYear(2005,0,1);
        dates = twiddle_dates(dates[0], dates[1], 'all time');
        break;
      case 'last_day':
        dates[0].setDate(dates[0].getDate()-1);
        dates[1].setDate(dates[1].getDate()-1);
        dates = twiddle_dates(dates[0], dates[1], 'day');
        break;
      case 'last_week':
        dates[0].setDate(dates[0].getDate()-7);
        dates[1].setDate(dates[1].getDate()-7);
        dates = twiddle_dates(dates[0], dates[1], 'week');
        break;
      case 'last_month':
        dates[0].setMonth(dates[0].getMonth()-1);
        dates[1].setMonth(dates[1].getMonth()-1);
        dates = twiddle_dates(dates[0], dates[1], 'month');
        break;
      case 'last_year':
        dates[0].setFullYear(dates[0].getFullYear()-1);
        dates[1].setFullYear(dates[1].getFullYear()-1);;
        dates = twiddle_dates(dates[0], dates[1], 'year');
        break;
        
    }
    
    
    $('#start').val(Highcharts.dateFormat(highcharts_date_format, dates[0].getTime()));
    $('#end').val(Highcharts.dateFormat(highcharts_date_format, dates[1].getTime()));
    state.start = $('#start').val();
    state.end = $('#end').val();
  
    if (generate)
      generate_report();  
    
  }
  
  
}

function generate_report() {
  kill_chart(0);
  //$('#selected_form').remove();
  if ($('#selector_top:checked').length)
    get_matches($('#selector_top'));
  else if ($('#selector_all:checked').length)
    get_matches($('#selector_all'));
  else if ($('#selector_inv:checked').length)
    get_matches($('#selector_inv'));
  else if ($('#selector_specific:checked').length && ($('#selected').find('input:checked').length == 0))
    get_matches($('#selector_specific'));
  else { 
    chart_from_matches(get_id_list()); 
  }
}

function redraw() {
  //if (state.display_type == 'show_chart_ck')
    chart.redraw();
}

function strip(html)
{
   var tmp = document.createElement("DIV");
   tmp.innerHTML = html;
   return tmp.textContent||tmp.innerText;
}

//http://stackoverflow.com/questions/5796718/html-entity-decode/9609450#9609450
var decodeEntities = (function() {
  // this prevents any overhead from creating the object each time
  var element = document.createElement('div');

  function decodeHTMLEntities (str) {
    if(str && typeof str === 'string') {
      // strip script/html tags
      str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
      str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
      element.innerHTML = str;
      str = element.textContent;
      element.textContent = '';
    }

    return str;
  }

  return decodeHTMLEntities;
})();

haha - 2025