//worktimegraph.js

function renderSummaryGraph(id, data) {
  plot = $.jqplot(id, [data], {
    seriesDefaults: {renderer: $.jqplot.PieRenderer},
    legend: {show: true}
  });
}

function renderGraph(id) {
  
	var idstr = jQuery(id).attr('id').split("_")[1];
	// console.log(idstr);
	
	// option handling
	var title = $("#worktimegraphopt_" + idstr + " .title").text();
	
	var graphtype = $("#worktimegraphopt_" + idstr + " .graph").text()
	    .toLowerCase();
	var dateFormatPattern = $("#worktimegraphopt_" + idstr + " .dateFormat")
	    .text();
	var dateFormat = new DateFormat(dateFormatPattern);
	
	var cols = $("#worktimegraphopt_" + idstr + " .cols").text().split(',');
	
	var isStackSeries = false;
	if($("#worktimegraphopt_" + idstr + " .stack").text().toLowerCase() == 'true') {
	  isStackSeries = true;
	}
	
	var legendLoc =  $("#worktimegraphopt_" + idstr + " .legendLoc").text();
	var legendXOffset =  $("#worktimegraphopt_" + idstr + " .legendXOffset").text();
	var legendYOffset =  $("#worktimegraphopt_" + idstr + " .legendYOffset").text();
	
	var xaxisMin = $("#worktimegraphopt_" + idstr + " .xaxisMin").text();
	var xaxisMax = $("#worktimegraphopt_" + idstr + " .xaxisMax").text();
	var yaxisMin = $("#worktimegraphopt_" + idstr + " .yaxisMin").text();
	var yaxisMax = $("#worktimegraphopt_" + idstr + " .yaxisMax").text();
	
	if(xaxisMin == 'null') {xaxisMin = null;}
	if(xaxisMax == 'null') {xaxisMax = null;}
	if(yaxisMin == 'null') {yaxisMin = null;}
	if(yaxisMax == 'null') {yaxisMax = null;}
	
	var xaxisFormatString = $("#worktimegraphopt_" + idstr + " .xaxisFormatString").text();
	var yaxisFormatString = $("#worktimegraphopt_" + idstr + " .yaxisFormatString").text();
	
	// collect label
	var table_headers = [];
	$("#worktimetable_" + 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 'number':
	    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,
	  	min: xaxisMin,
			max: xaxisMax
	  };
	} else if (isNumAxis) {
	  xaxis_opts = {
		  	min: toNum(xaxisMin, null),
				max: toNum(xaxisMax, null)
	  };
	} else {
	  xaxis_opts = {
	    renderer: $.jqplot.CategoryAxisRenderer,
		  min: xaxisMin,
		  max: xaxisMax,
	    ticks: xaxis_values['values']
	  };
	}
	xaxis_opts.tickOptions = {formatString: xaxisFormatString};
	
	var yaxis_opts = {
		tickOptions: {formatString: yaxisFormatString},
		min: toNum(yaxisMin, null),
		max: toNum(yaxisMax, null)
	};
	
	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('worktimeplaceholder_' + 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: yaxis_opts
	  },
	  highlighter: {
	    sizeAdjust: 10
	  },
	  cursor: {show: true}
	});	
}

function toNum(str, defaultValue) {
	if (str == null) {
		return defaultValue;
	}
  num = Number(str, 10);
  if (!isNaN(num)) {
    return num;
  } else {
  	return defaultValue;
  }
}

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] = [];
    }
  );
    
  $("#worktimetable_" + 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 = $(this).text();
        if (value == '') {
          return true;
        }
        value = Number(value, 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';

  $("#worktimetable_" + 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;
}
