//burndow.js

jQuery(document).ready(function($) {
  renderGraph("#reportgraph_0");
});

function renderGraph(id) {
  
	var idstr = jQuery(id).attr('id').split("_")[1];
	// console.log(idstr);
	
	// option handling
	var title = $("#reportgraphopt_" + idstr + " .title").text();
	
	var opt_per = $("#reportgraphopt_" + idstr + " .per").text()
	    .toLowerCase();
	var x_minTickSize = opt_per == "week" ? [ 7, "day" ] : [ 1, "day" ];
	
	var graphtype = $("#reportgraphopt_" + idstr + " .graph").text()
	    .toLowerCase();
	var dateFormatPattern = $("#reportgraphopt_" + idstr + " .dateFormat")
	    .text();
	var dateFormat = new DateFormat(dateFormatPattern);
	
	var cols = $("#reportgraphopt_" + idstr + " .cols").text().split(',');
	
	var isStackSeries = false;
	if($("#reportgraphopt_" + idstr + " .stack").text().toLowerCase() == 'true') {
	  isStackSeries = true;
	}
	
	var legendLoc =  $("#reportgraphopt_" + idstr + " .legendLoc").text();
	var legendXOffset =  $("#reportgraphopt_" + idstr + " .legendXOffset").text();
	var legendYOffset =  $("#reportgraphopt_" + idstr + " .legendYOffset").text();
	
	// collect label
	var table_headers = [];
	$("#reportgraphtable_" + idstr + " thead tr th").each( function(col_index) {
	  table_headers.push($(this).text());
	});
	
	var labels = []
	if (cols[0] == '') {
	  $.each(table_headers, function(table_headers_index, table_header) {
	    if (table_headers_index == 0) {
	      return true;
	    }
	    labels.push(table_header);
	  });
	} else {
	  // for selected column
	  $.each(table_headers, function(table_headers_index, table_header) {
	    $.each(cols, function(col_index, col) {
	      if (col == table_header) {
	        labels.push(table_header);
	      }
	    });
	  });
	}
	
	var xaxis_values = getXaxisValues(idstr, 0, dateFormat);
	
	var isDateAxis = false;
	var isNumAxis = false;
	switch (xaxis_values['type']) {
	  case 'date':
	    isDateAxis = true;
	  case 'num':
	    isNumAxis = true;
	}
	var datas = getTableValues(idstr, xaxis_values, table_headers, dateFormat);
	
	switch (graphtype) {
	case 'bars':
	  graph_opt = {
	    type : $.jqplot.BarRenderer,
	    opts : {
	    }
	  };
	  break;
	case 'lines':
	default:
	  graph_opt = {
	    type : $.jqplot.LineRenderer,
	    opts : {
	    }
	  };
	}
	
	var xaxis_opts = {}
	if (isDateAxis) {
	  xaxis_opts = {
	    renderer: $.jqplot.DateAxisRenderer
	  };
	} else if (isNumAxis) {
	   xaxis_opts = {
	    renderer: $.jqplot.CategoryAxisRenderer
	  };
	} else {
	  xaxis_opts = {
	    renderer: $.jqplot.CategoryAxisRenderer,
	    ticks: xaxis_values['values']
	  };
	}
	
	var series = [];
	$.each(labels, function(index, label) {
	  series.push({
	    label: label,
	    renderer: graph_opt['type']
	  })
	});
	
	isFill = false;
	if (isStackSeries && graphtype == 'lines') {
	  isFill = true;
	}
	plot1 = $.jqplot('placeholder_' + idstr, datas, {
	  legend: {
	    show: true,
	    location: legendLoc,
	    xoffset: Number(legendXOffset, 10),
	    yoffset: Number(legendYOffset, 10)
	  },
	  title: title,
	  stackSeries: isStackSeries,
	  series: series,
	  seriesDefaults: {
	    fill: isFill
	  },
	  axes: {
	    xaxis: xaxis_opts,
	    yaxis: {
	      min: 0
	    }
	  },
	  highlighter: {
	    sizeAdjust: 10
	  },
	  cursor: {show: true}
	});	
}

function convertData(str, dateFormat) {
  // try convert to date
  date = dateFormat.parse(str);
  if (date != null) {
    var strDate = new DateFormat("yyyy-MM-dd").format(date);
    return ['date', strDate];
  }

  // try convert to int
  num = Number(str, 10);
  if (!isNaN(num)) {
    return ['number', num];
  }

  // for string. create ticks.
  return ['str', str];
}

function getTableValues(tableId, xaxis_values, table_headers, dateFormat) {
  
  var tmp = {};
  
  $.each(table_headers, function(index, table_header) {
      tmp[table_header] = [];
    }
  );
    
  $("#reportgraphtable_" + tableId + " tbody tr").each(
    function(row_index) {
      $(this).children().each(function(col_index) { 
        
        // for xaxis column
        if(col_index == xaxis_values['colIndex']) {
          return true;
        }
        
        table_header = table_headers[col_index];
        
        value = Number($(this).text(), 10);
        
        if (xaxis_values['type'] == 'str') {
          tmp[table_header].push(value);
        } else {
          tmp[table_header].push([xaxis_values['values'][row_index], value]);
        }
      });
    });
    
  var datas = [];
  $.each(table_headers, function(index, table_header) {
      // for xaxis column
      if(index == xaxis_values['colIndex']) {
        return true;
      }
      datas.push(tmp[table_header]);
    }
  );
  
  return datas;
}

function getXaxisValues(tableId, index, dateFormat) {
  var values = []
  var type = 'str';

  $("#reportgraphtable_" + tableId + " tbody tr").each(
    function(row_index) {
      $(this).children().each( function(col_index) {
        if (col_index == index) {
          
          str = $(this).text();
          xaxis_value = convertData(str, dateFormat);
          
          type = xaxis_value[0];
          values.push(xaxis_value[1]);
        }
      });
    }
  );

  var xaxis_values = {
    colIndex: index,
    type: type,
    values: values
  };

  // console.log("xaxis_values=" + xaxis_values['values'])
  return xaxis_values;
}
