// sp_stats.js
// CREATED: 10th March 2006
// Player stats etc.

// :: FUNCTIONS
// contains(Needle, Haystack, Delim)
// rtnOurTeam(Key)
// f_whoPlayed(SeasonID,OrderBy)

// Searches for Needle in Haystack, where the Haystack is a string of values delimited by Delim
// Returns true if found, false otherwise
function contains(Needle, Haystack, Delim) {
	var f = Haystack.split(Delim);
	var maxf = f.length;
	var i;
	var found = false;
	
	for (i=0; i<maxf; i++) {
		if (f[i] == Needle) {
			found = true;
			break;
		}
	}
	return found;
}

// Rtn array of our team (people IDs) from passed match key.
// Perfroms lookup to find whether team is home/away
// NB: Code from f_team() in sp_scores.js
function rtnOurTeam(Key) {
	var f, j, dbg;
  var home, rubbers;
  var offset;		
	var team = new Array();

  // GET FIXTURE...
  f = FixArr[FixArrLookup[Key]].split(',');
  home = (f[5] == 'H');
	
	// Get Results.. (Check)
	if (typeof(ResArr[Key]) == 'undefined') {
		return team;
	}
	f = ResArr[Key].split(',');
  rubbers = (f[1] == '_RUBBERS');	

  // SIX PLAYERS
  if (f[0].indexOf('6') > -1) {
    // FULL SCORESHEET OR RUBBERS ONLY?
    offset = (home || rubbers) ? 3 : 9;
    for (j=0;j<=5;j++) {team[j] = f[j+offset];}
  } 

  // FOUR PLAYERS
  else if (f[0].indexOf('4') > -1) {
    // FULL SCORESHEET OR RUBBERS ONLY?
    offset = (home || rubbers) ? 3 : 7;
    for (j=0;j<=3;j++) {team[j] = f[j+offset];}
  }

  // EIGHT PLAYERS (ie. Cup)
  else if (f[0].indexOf('8') > -1) {
    // FULL SCORESHEET OR RUBBERS ONLY?
    offset = (home || rubbers) ? 3 : 11;
    for (j=0;j<=7;j++) {team[j] = f[j+offset];}
  }
	
	// Debug...
/*	
	dbg = '';
	for(j=0; j<team.length; j++) {
		if (dbg > ' ') {dbg += ', ';}
		dbg += team[j];		
	}
	alert(Key + '\n\n' + ResArr[Key] + '\n\n' + '[' + dbg + ']');
*/	
	
	return team;
}

// Returns formatted table of all players who have played in the season
// For each player, the number of games played for each team and a total 
function f_whoPlayed(SeasonID,OrderBy) {
	var t, header, tmp, prop, val, i, maxi, j, f, c;
	var tid, maxt, tarr = new Array();
	var p = new Array();
	var order = new Array();
	var sfrom, sto, count, updated;
	var osh = ' style="background-color:#990000;"';	// OrderStyleHeader
	var osd = ' style="background-color:#FFE2CF;"';	// OrderStyleData	#ffcccc
	
  // DEFAULT : GET CURRENT SEASON ID
  if (typeof(SeasonID) == 'undefined') {
    SeasonID = f_getCurrentSeasonID();
  }
	if ((typeof(OrderBy) == 'undefined') || (OrderBy == '')) {
		OrderBy = _ALPHA;
	}	

  // LOOKUP SEASON
  f = SeasonArr[SeasonArrLookup[SeasonID]].split(',');
  sfrom = Number(f[2]);
  sto = Number(f[3]);
	
	// Construct simple Array of Team IDs (inc. _ALL)
	// Make header of table at same time;
	tmp = '<tr><td>&nbsp;</td>';
	if (OrderBy == _ALPHA) {
		tmp += '<th ' + osh + '>Club Member</th>';
	} else {
		tmp += '<th><a href="javascript:refreshWhoPlayed(\'' + SeasonID + '\');" title="Sort Alphabetically...">Club Member</a></th>';
	}	
	maxt = TeamArr.length;
	for(i=0; i<maxt; i++) {
		tarr[i] = f_rtnID(TeamArr[i]);
		if (i < (maxt - 1)) {
			tmp += '<th class="number"';
			if (OrderBy == tarr[i]) {
				tmp += osh + '>' + tarr[i];
			} else {			
				tmp += '><a href="javascript:refreshWhoPlayed(\'' + SeasonID + '\',\'' + tarr[i] + '\');" title="Sort By Team...">' + tarr[i] + '</a>';
			}
			tmp += '</th>';			
		}
	}
	tmp += '<th class="number"';
	if (OrderBy == _ALL) {
		tmp += osh + '>Total';
	} else {			
		tmp += '><a href="javascript:refreshWhoPlayed(\'' + SeasonID + '\',_ALL);" title="Sort By Totals...">Total</a>';
	}
	tmp += '</th></tr>';
	header = '<thead>' + tmp + '</thead><tfoot>' + tmp + '</tfoot>';
	
	// Construct array of people in club (inc. past members)
	// NB: Previously assumed all Silver Fox members occurred at top of PeopleArr[] !
	maxi = PeopleArr.length;
	c = 0;
	for(i=0; i<maxi; i++) {
		f = PeopleArr[i].split(',');
		if (contains(_HOME_CLUBID,f[4],'|')) {
			// Create entry in p[] for person and subarray for each team
			p[f[0]] = new Array();
			order[c++] = f[0];
			for(j=0; j<maxt; j++) {
				p[f[0]][tarr[j]] = 0;	// Init to zero
			}
		} else {
			//break;
			continue;
		}
	}
	
	// Step through fixtures...
  for (i=sfrom; i<=sto; i++) {
    // GET FIXTURE
    f = FixArr[i].split(',');
		tid = f[2];	// Team ID
		tmp = f_constructKey(f[1],tid);	// Match Key
		
		// If not results then continue...
		if (typeof(ResArr[tmp]) == 'undefined') {continue;}
				
		// Rtn array of our team (people IDs) from passed match key.
		f = rtnOurTeam(tmp);
		maxi = f.length;
		for (j=0; j<maxi; j++) {
			if ((f[j] != 'X') && (f[j] != '?')) {
				try { 
				  p[f[j]][tid]++;
				  p[f[j]][_ALL]++;
				} catch(myErr) {
					alert(myErr + '\n\nf[j] = "' + f[j] + '"');
				} finally {
					// Knowt
				}
			}
		}
	}
	
	// If OrderBy specified (ie. not default alphabetical)
	// Sort by specified team (or _ALL) - See bubble sort in f_playerLookup(), sp_people.js
	if (OrderBy != _ALPHA) {
		count = 0;
		maxi = order.length - 1;
    do {
      count++;	// JUST TO TEST (FAIL SAFE)
      updated = false;
      for (i=0; i<maxi; i++) {
				// Sort Descending
        if (p[order[i]][OrderBy] < p[order[i+1]][OrderBy]) {	// *** HERE ***
          updated = true;
          // SWAP VALUES
          tmp = order[i];
          order[i] = order[i+1];
          order[i+1] = tmp;
        }
      }
    } while ((updated) && (count < 200));
	}
	
	// Construct table to return
	t = '<table class="fixtures" cellpadding="0" cellspacing="0" border="0">';
	t += header + '<tbody>';
	
	// Display members...
	count = 0;
	maxi = order.length;
	for(i=0; i<maxi; i++) {
		// Only display row for member if total > 0
		if (p[order[i]][_ALL] == 0) {continue;}
	
		count++;
		t += '<tr';
		if ((count % 2) == 0) {t += ' class="highlight"';}
		t += '><td style="text-align:right;padding-right:10px;color:#999999;">' + count + '.</td><td';
		if (OrderBy == _ALPHA) {t += osd;}
		t += '>' + f_linkPerson(order[i]) + '</td>';
		
		// Team totals and grand total
		for(prop in p[order[i]]) {
			val = p[order[i]][prop];
			if (val == 0) {
				val = '<span class="faint">----</span>';
			}
			t += '<td class="number"';
			if (OrderBy == prop) {t += osd;}			
			t += '>' + val + '</td>';		
		}
		
		t += '</tr>';
	}
	 
	t += '</tbody></table>';
	
	t += '<p>' + count + ' members listed.</p>';

	return t;
}
