
function init_actions()
{
	var i, j, k, table, row, cell, child;
	
	// header links in table
	table = doc_elem("player_stats_table");
	for (i = 0; i < table.rows.length; ++i)
	{
		row = table.rows[i];
		if (!has_class(row, "MiniClassic")) continue;
		for (j = 0; j < row.cells.length; ++j)
		{
			cell = row.cells[j];
			for (k = 0; k < cell.childNodes.length; ++k)
			{
				child = cell.childNodes[k];
				if (child.tagName && child.tagName == "A")
				{
					child.onclick = header_click;
				}
			}
		}
	}
	// aggregation select
	doc_elem("aggregation").onchange = aggregation_change;
}

function aggregation_change()
{
	set_data_aggregation();
	sort_players();
	set_table_rows(g_players);
}

function set_data_aggregation()
{
	var aggregation, i, col, p, aggregation_func;
	
	aggregation = doc_elem("aggregation").value;
	switch (aggregation)
	{
		case ("per_game"): aggregation_func = per_game_calc; break;
		case ("per_30"):   aggregation_func = per_30_calc;   break;
		case ("totals"):   aggregation_func = totals_calc;   break;
	}
	
	for (i = 0; i < g_players.length; ++i)
	{
		p = g_players[i];
		for (col in g_cols)
		{
			if (col == "mins" && aggregation == "per_30") continue;
			if (!g_cols[col].is_agg) continue;
			p[col] = aggregation_func(g_player_totals[p.pid][col], g_player_totals[p.pid].gms, g_player_totals[p.pid].mins);
		}
	}
}

function per_game_calc(stat_total, games, mins)
{
	return safe_divide(stat_total, games);
}

function per_30_calc(stat_total, games, mins)
{
	return safe_divide(30, safe_divide(mins, games)) * safe_divide(stat_total, games);
}

function totals_calc(stat_total, games, mins)
{
	return stat_total;
}

function header_click(event)
{
	var link;
	
	link = get_event_src(event);
	link.blur();
	set_sort(link.innerHTML);
	sort_players();
	
	return false;
}

function sort_players(col)
{
	var sorter;
	
	sorter = new Sorter(g_players, ((g_sort_dir == "asc") ? player_cmp_asc : player_cmp_desc));
	
	set_table_rows(sorter.data);
}

function set_sort(col)
{
	var tmp;
	
	tmp = data_col_map(col);
	if (tmp == g_sort_col)
	{
		// "desc" position doesn't make any sense
		if (tmp == "pos") return;
		g_sort_dir = (g_sort_dir == "asc") ? "desc" : "asc";
	}
	else
	{
		if (tmp == "name" || tmp == "pos" || tmp == "to") g_sort_dir = "asc";
		else g_sort_dir = "desc";
	}
	g_sort_col = tmp;
}

function year_spacers(sorted_data)
{
	var i, player, cur_year, prev_year, with_spacers;
	
	with_spacers = [];
	prev_year = null;
	for (i = 0; i < sorted_data.length; ++i)
	{
		player = sorted_data[i];
		
		cur_year = player.year;
		if (prev_year != cur_year && prev_year != null)
			with_spacers.push(create_spacer_marker());
		
		prev_year = cur_year;
		
		with_spacers.push(player);
	}
	return with_spacers;
}

function pos_spacers(sorted_data)
{
	var i, player, pos, with_spacers;
	
	with_spacers = [];
	prev_year = null;
	for (i = 0; i < sorted_data.length; ++i)
	{
		player = sorted_data[i];
		pos = get_pos(player.pos);
		
		with_spacers.push(player);
		if (pos == "C" || pos == "bC") with_spacers.push(create_spacer_marker());
	}
	return with_spacers;
}
	
function check_ineligible(sorted_data)
{
	var ineligible_in_back, i, player, ineligible;
	
	ineligible_in_back = [];
	ineligible = [];
	for (i = 0; i < sorted_data.length; ++i)
	{
		player = sorted_data[i];
		if (g_ineligible[player.pid]) ineligible.push(player);
		else ineligible_in_back.push(player);
	}
	if (ineligible.length > 0)
	{
		ineligible_in_back.push(create_spacer_marker());
		for (i = 0; i < ineligible.length; ++i)
			ineligible_in_back.push(ineligible[i]);
	}
	
	return ineligible_in_back;
}

function set_table_rows(data)
{
	var tbody, row, cell, d, i, col, col_info, content, aggregation;
	
	aggregation = doc_elem("aggregation").value;
	
	// add spacer between years
	if (g_sort_col == "year") data = year_spacers(data);
	
	// add spacer between start/bench and bench/na
	else if (g_sort_col == "pos") data = pos_spacers(data);
	
	// add spacer between eligible and ineligible
	else if (g_sort_col != "name" && g_sort_col != "ht") data = check_ineligible(data);
	
	tbody = doc_elem("player_stats_body");
	filicide(tbody);
	for (i = 0; i < data.length; ++i)
	{
		d = data[i];
		
		if (is_spacer_row(d))
		{
			row = d.create_spacer_func();
		}
		else
		{
			row = document.createElement("TR");
			row.onmouseover = tbody_row_over;
			row.onmouseout = tbody_row_out;
			for (col in g_cols)
			{
				col_info = g_cols[col];
				content = d[col];
				if (col_info.func && !(aggregation == 'totals' && col_info.is_agg)) content = col_info.func(content);
				
				cell = document.createElement("TD");
				cell.innerHTML = content;
				if (col_info.cls) add_class(cell, col_info.cls);
				if (col == g_sort_col) add_class(cell, "sort_cell");
				row.appendChild(cell);
			}
		}
		tbody.appendChild(row);
	}
}

function show_totals()
{
	show_totals_row(g_team_totals);
	show_totals_row(g_opp_totals);
}

function show_totals_row(totals)
{
	var tfoot, row, cell, col, col_info, content;
	
	tfoot = doc_elem("player_stats_foot");
	
	row = document.createElement("TR");
	row.onmouseover = tbody_row_over;
	row.onmouseout = tbody_row_out;
	add_class(row, "team_totals");
	for (col in g_cols)
	{
		col_info = g_cols[col];
		content = totals[col];
		if (col_info.func) content = col_info.func(content);
		
		cell = document.createElement("TD");
		cell.innerHTML = content;
		if (col_info.cls) add_class(cell, col_info.cls);
		if (col == g_sort_col) add_class(cell, "sort_cell");
		row.appendChild(cell);
	}
	tfoot.appendChild(row);
}

function tbody_row_over(event)
{
	var row, cell, i;
	return;
	row = get_event_src(event);
	for (i = 0; i < row.cells.length; ++i)
	{
		cell = row.cells[i];
		if (has_class(cell, "sort_cell"))
		{
			replace_class(cell, "sort_cell", "sort_cell_row_over");
			break;
		}
	}
}

function tbody_row_out(event)
{
	var row, cell, i;
	return;
	row = get_event_src(event);
	for (i = 0; i < row.cells.length; ++i)
	{
		cell = row.cells[i];
		if (has_class(cell, "sort_cell_row_over"))
		{
			replace_class(cell, "sort_cell_row_over", "sort_cell");
			break;
		}
	}
}

function is_spacer_row(data)
{
	return (data.is_spacer);
}

function create_spacer_marker()
{
	return {
		"is_spacer":1,
		"create_spacer_func":create_player_table_spacer
	};
}

function create_player_table_spacer()
{
	var row, cell;
	
	row = document.createElement("TR");
	
	cell = document.createElement("TD");
	add_class(cell, "player_table_spacer");
	cell.setAttribute("colspan", 100);
	
	row.appendChild(cell);
	return row;
}

function data_col_map(col)
{
	switch (col)
	{
		case ("FG%"): return "fgp";
		case ("FT%"): return "ftp";
		case ("3PM"): return "tpm";
		case ("3PA"): return "tpa";
		case ("3P%"): return "tpp";
		case ("TS%"): return "tsp";
		case ("GM"): return "gms";
		case ("YR"): return "year";
		case ("Player"): return "name";
		default: return col.toLowerCase();
	}
}

function player_cmp_asc(p1, p2)
{
	return (p1[g_sort_col] > p2[g_sort_col]);
}

function player_cmp_desc(p1, p2)
{
	return (p1[g_sort_col] < p2[g_sort_col]);
}

function init_team_totals_pre()
{
	var col;
	
	// aggregatable cols
	g_team_totals = {};
	for (col in g_cols)
	{
		if (g_cols[col].is_agg) g_team_totals[col] = 0;
	}
	set_totals_other_cols(g_team_totals, "Team");
}

function init_team_totals_post()
{
	var col, num_games;
	
	num_games = doc_elem("num_games").value;
	
	set_other_stats(g_team_totals);
	
	// minutes is aggregatable but doesn't matter for team, so do this after
	g_team_totals.mins = "0";
	for (col in g_cols)
	{
		if (g_cols[col].is_agg) g_team_totals[col] /= num_games;
	}
}

function init_opp_totals_post()
{
	var col, num_games, i, total_cols;
	
	num_games = doc_elem("num_games").value;
	
	// make sure everthing is a number
	for (col in g_opp_totals) g_opp_totals[col] = Number(g_opp_totals[col]);
	
	// set per game
	total_cols = ["fgm", "fga", "tpm", "tpa", "ftm", "fta", "stl", "to", "blk"];
	for (i = 0; col = total_cols[i]; ++i) g_opp_totals[col] /= num_games;
	
	// other cols
	g_opp_totals.mins = "0";
	set_totals_other_cols(g_opp_totals, "Opp");
	
	// set other stats
	set_other_stats(g_opp_totals);
}

function set_totals_other_cols(totals, type)
{
	// other cols
	totals.pid = "-";
	totals.pos = "-";
	totals.name = type+" Totals";
	totals.ht = "-";
	totals.year = "-";
	totals.gms = "-";
}

function init_player_data()
{
	var i, j, p, num_games;
	
	num_games = doc_elem("num_games").value;
	g_ineligible = {};
	g_player_totals = {};
	init_team_totals_pre();
	for (i = 0; i < g_players.length; ++i)
	{
		p = g_players[i];
		// make sure data that should be numerical really is
		for (j in p)
		{
			if (j == "name") continue;
			p[j] = Number(p[j]);
			
			// team totals (only need to total aggregatable columns
			if (g_cols[j].is_agg) g_team_totals[j] += p[j];
		}
		set_other_stats(p);
		
		// see if player has played enough games
		if ((p.gms / num_games) < .333) g_ineligible[p.pid] = 1;
		
		g_player_totals[p.pid] = obj_copy(p);
	}
	init_team_totals_post();
	init_opp_totals_post();
}

function set_other_stats(stats)
{
	// rebounds
	stats.dreb = stats.rebs - stats.oreb;
	
	// calculate scoring data
	stats.pts = (stats.fgm * 2) + stats.tpm + stats.ftm;
	stats.fgp = safe_divide(stats.fgm, stats.fga) * 100;
	stats.tpp = safe_divide(stats.tpm, stats.tpa) * 100;
	stats.ftp = safe_divide(stats.ftm, stats.fta) * 100;
	stats.tsp = safe_divide((stats.pts * 50), (stats.fga + (stats.fta * .44)));
}

function get_pos(pos_id)
{
	if (isNaN(pos_id)) return pos_id;
	return g_pos_map[pos_id];
}

function get_year(year_id)
{
	if (isNaN(year_id)) return year_id;
	return g_year_map[year_id];
}

function get_ht(inches)
{
	if (isNaN(inches)) return inches;
	return Math.floor(inches / 12)+"-"+(inches % 12);
}

var g_sort_col, g_sort_dir;

var g_cols, g_text_cols, g_col_content_formats, g_col_content_classes;

var g_team_totals;

// for players that don't meet min game requirement
var g_ineligible;

// keep an extra copy of totals data so we can convert between aggregation types
var g_player_totals;

var g_pos_map, g_year_map;

function init_globals()
{
	g_sort_col = null;
	g_sort_dir = null;
	
	g_cols = {
		"pid": {"func":""      ,"cls":"" ,"is_agg":0},
		"pos": {"func":get_pos ,"cls":"" ,"is_agg":0},
		"name":{"func":""      ,"cls":"b","is_agg":0},
		"ht":  {"func":get_ht  ,"cls":"" ,"is_agg":0},
		"year":{"func":get_year,"cls":"" ,"is_agg":0},
		"gms": {"func":""      ,"cls":"r","is_agg":0},
		"mins":{"func":n0      ,"cls":"r","is_agg":1},
		"pts": {"func":n1      ,"cls":"r","is_agg":1},
		"dreb":{"func":n1      ,"cls":"r","is_agg":1},
		"oreb":{"func":n1      ,"cls":"r","is_agg":1},
		"rebs":{"func":n1      ,"cls":"r","is_agg":1},
		"asts":{"func":n1      ,"cls":"r","is_agg":1},
		"fgm": {"func":n1      ,"cls":"r","is_agg":1},
		"fga": {"func":n1      ,"cls":"r","is_agg":1},
		"fgp": {"func":n1      ,"cls":"r","is_agg":0},
		"tpm": {"func":n1      ,"cls":"r","is_agg":1},
		"tpa": {"func":n1      ,"cls":"r","is_agg":1},
		"tpp": {"func":n1      ,"cls":"r","is_agg":0},
		"ftm": {"func":n1      ,"cls":"r","is_agg":1},
		"fta": {"func":n1      ,"cls":"r","is_agg":1},
		"ftp": {"func":n1      ,"cls":"r","is_agg":0},
		"tsp": {"func":n1      ,"cls":"r","is_agg":0},
		"stl": {"func":n1      ,"cls":"r","is_agg":1},
		"to":  {"func":n1      ,"cls":"r","is_agg":1},
		"blk": {"func":n1      ,"cls":"r","is_agg":1}
	};
	
	g_pos_map = ["PG","SG","SF","PF","C","bPG","bSG","bSF","bPF","bC","NA","NA"];
	g_year_map = ["Fr","So","Jr","Sr"];
}

function init()
{
	init_globals();
	init_actions();
	init_player_data();
	
	set_sort("pos");
	set_data_aggregation();
	sort_players();
	show_totals();
}

add_onload_func(init);

