// copyright c 2003 by t. j. marlin
// All rights reserved. No part of this script may be reproduced or used in any
// form or by electronic or mechanical means, including information storage and retrieval // systems, without the permission in writing from the author, except in normal use of
// browsing the web page of which this is a part. 

version = "ver 2.3 13 oct 01";
numTeams = 0;
delete teams;
teams = new Array();
teamOrder = new Array();
var maxValue, minValue;
mulWon = 6;  // points for a win
mulDraw = 3;  // points for a draw
yellowBound = 2; //cautions above this cause a deduction 
mulYellow = 1; // points for a caution. 
mulRed = 3;  // points for a send off. 
maxGoalsScored = 3; // one point for each goal up to this value
shutoutVal = 1; // points for a shutout
moreInfoIndicator = "^"; // only valid as 1st or 2nd char of field.
                         // if both a change indicator and a more info indicator
						 // are on a field name,
                         // the change indicator must be first.
schedHeadComment = "";
schedDayComment = "";
schedTrailComment = "";
standComment = "";
function team( name, coach, mailName, mailDomain, phone, colors, ni, nat ){
  var args = name.split( "/" );
  this.name = args[0].trim();
  if( args.length > 1 ){
    this.region = args[1].trim();
  } else {
    this.region = "";
  }
  
  this.coach = coach.trim();
  if( arguments.length > 2 ){
    this.mailName = mailName.trim();
	this.mailDomain = mailDomain.trim();
  } else {
    this.mailName = "";
	this.mailDomain = "";""
  }
  if( arguments.length > 4 ){
    this.phone = phone.trim();
  } else {
    this.phone = "";
  }
  if( arguments.length > 5 ){
    this.colors = colors;
  } else {
    this.colors = "";
  }
  if( arguments.length > 6 ){
    this.notIncluded = ni;
  } else {
    this.notIncluded = false;
  }
  this.won = 0;
  this.lost = 0;
  this.draw = 0;
  this.yellow = 0;
  this.red = 0;
  this.goalsFor = 0;
  this.goalsAgainst = 0;
  this.goalDiff = 0;
  this.points = 0;
  this.pointsDeducted = 0;
  this.used = false;
  if( arguments.length <= 7 && !nat ){ // nat means not a team
    teams[numTeams++] = this;
  }
} // function team


team.prototype.computePoints = function( thisScore, otherScore, cautions, ejections ){
    this.points += Math.min( maxGoalsScored, thisScore );
    this.points += (otherScore == 0) ? shutoutVal : 0;
    if( cautions > yellowBound ){
      this.pointsDeducted += (cautions - yellowBound) * mulYellow;
    }
    this.pointsDeducted += ejections * mulRed;
}  //  team.prototype.computePoints(

team.prototype.toString = function(){
  with( this ){
    return name  + " points: " + points + " yellow: " + yellow + " red: " + red
           + " gf: " + goalsFor + " ga: " + goalsAgainst + " gd: " + goalDiff;
  }
}  //  team.prototype.toString

team.prototype.addCI = function(){ // add a change indicator to the beginning of the team name
  with( this ){
    if( name.substr( 0, 1 ) != changeIndicator ){
      name = changeIndicator + name;
    }
  }
}  //  team.prototype.addCI = function(){

team.prototype.removeCI = function(){ // removes a change indicator from the beginning of the team name
  with( this ){
    if( name.substr( 0, 1 ) == changeIndicator ){
      name = name.substr( 1, name.length );
    }
  }
}  //  team.prototype.removeCI = function(){

team.prototype.clearStats = function(){ // zeros all team statistics
   with( this ){ 
	won = 0;
  	lost = 0;
  	draw = 0;
  	yellow = 0;
  	red = 0;
  	goalsFor = 0;
  	goalsAgainst = 0;
  	points = 0;
  	pointsDeducted = 0;
   } // with
 }  //  team.prototype.clearStats = function()


function clearAllStats(){
  var i;
  for( i = 0; i < numTeams; i++ ){
    teams[ i ].clearStats();
  }  //  for
}  //  function clearAllStats(){

//  ________________________________________________________________________



function buildCoachList (){
  say( "<p><div align='center'><table border=0 cellpadding = 2>" );
  say( "<caption><b>Coaches</b></caption>" );
  var i;
  var midpt = Math.floor( (numTeams +1)/2 );
  j = midpt;

  for( i = 0; i < midpt; i++, j++ ){
    with( teams[ i ]){
      say( "<tr><td>" + name + "</td><td>" );
      if( mailName != "" ){ 
	    mailto ( mailName, mailDomain, coach );
      } else {
	    say( coach );
	  }
	  //if( colors != "" ){
	    //say( "<br>" + colors );
	  //}
	  say( "</td><td>" );
      say( phone );
	  say( "</td>" );
    }  //   with( teams[ i ]){
      if( j < numTeams ){
	    say( "<td width='15'></td>" ); // gutter
        with( teams[ j ]){
          say("<td>" + name + "</td><td>" );
          if( mailName != "" ){
		    mailto( mailName, mailDomain, coach );
          } else {
		    say( coach );
		  }
	      //if( colors != "" ){
	        //say( "<br>" + colors );
	      //}
		  say( "</td><td>" );
          say(  phone );
		  say( "</td>" );
        }  //   with( teams[ j ]){
      }  //   if( j < numTeams ){
	  say( "</tr>" );
	  say( "<tr><td>" + teams[i].region + "</td><td colspan='2'>" );
	  say( teams[ i ].colors );
	  say( "</td>" );
	  if( j < numTeams ){
	    say( "<td></td><td>" + teams[j].region + "</td></td><td colspan='2'>" );
		say( teams[ j ].colors );
		say( "</td>" );
	  } // if( j < numTeams ){
	  say( "</tr>" );
    }  //   for( i = 0; i < midpt; i++, j++ ){
    say( "</table></div>" );
}  //  buildCoachList
//  ____________________________________________________

/* open a link to field_info.html in a new window

inputs: field a string. 
        all blanks are changed to an underscore
        all letters are changed to lowercase.
outputs: none
returns: nothing
side effects: a new browser window showing field.html

*/
function moreInfo( field ){
  var url = field.replace( / /g, "_"); // replace blanks with underscores
  url = url.toLowerCase() + "_info.html";
	var moreInfoWin = window.open( url, "moreInfoWin", "scrollbars=yes,toolbar=yes");
	 moreInfoWin.focus();
} // function moreInfo( field ){
//  ____________________________________________________


function buildSched ( a, ht, vt, hs, vs, hc, he, vc, ve ){
  var args = a.split( "," );
  var i;
  var numCols = 7;

  for( i = 0; i < args.length; i++ ){
    args[ i ] = args[ i ].trim();
  }

  if( args[0] == "first" ){
    say( "<p><p><div align='center'><b>"
          + "Home team is responsible"
		  + " to change in case of a color conflict." 
          + "<br>"
          + "|Changes shown in this color".ci()
          + "<br>"
          + schedHeadComment
		  + "</b></div>" );
    say( "<p><p><div align='center'><table border=0 cellpadding='4'>" );
    say( "<caption><b><font size=+1>" + args[1] + " Schedule</font></b></caption>" );
    return;
  }
    
  document.write( "<tr>" );
  if( args[0] == "last" ){
    say ("<td colspan='" + numCols + "' align='center'><img src='../images/colorful_stone_stripe.gif'>" );
    say ("</table></div>" );
    say( "<br><div align='right'><font size=-1>" + schedTrailComment + "</font></div>" );
    return;
  }

  if( args[0] != "" ){  // is there a day?
    say ("<td colspan='" + numCols + "' align='center'><img src='../images/colorful_stone_stripe.gif'>" );
    if( schedDayComment != "" ){
      say ("<tr><td colspan=" + numCols + " align='center'>" + schedDayComment );
    }
    say ( "<tr><th width='20'>Day</th><th width='40'>Date</th><th width='20'>Time</th><th align='left' width='20'>Home</th><th align='left' width='20'>Visitor</th><th width='100'>Field</th><th align='left' width='100'>Result</th></tr>" );
    say ( "<tr><td>" + args[0].ci() );
    say ( "</td><td>" + args[1].ci() + "</td><td");
  } else {
    say ( "<td colspan=3");
  }

  say ( " align='right'>" + args[2].ci() );
  say ( "</td><td>" + ht.name.ci() ); // home team
  say ( "</td><td>" + vt.name.ci() ); // visitors

  field = args[3];
  fieldChange = false;
  fieldMoreInfo = false;
  if( field.substr( 0, 1 ) == changeIndicator ){
    fieldChange = true;
    field = field.substr( 1, field.length);
  }
  if( field.substr( 0, 1 ) == moreInfoIndicator ){
    fieldMoreInfo = true;
    field = field.substr( 1, field.length);
  }
  
  say ( "</td><td align='center'>" );
  say( '<a ' );
  if( fieldChange ){
    say( "class=change " );
  }
  say( 'href=\"javascript: void mapIt(\'' );
  say( field );  // the field name
  say( '\')\">' + field + ' ' + args[4].ci() +'</a>' );
  if( fieldMoreInfo ){
    say( '<a href=\"javascript: void moreInfo(\'' );
    say( field );  // the field name
    say( '\')\"><img src="../images/more_info.gif" border="0" alt="more info"></a>' );
  }

  say(  "</td><td>" );

  if (hs != null) {

    say (  hs );
    say ( " - " + vs );
	if( !( ht.notIncluded || vt.notIncluded || (args[5] == "nostats"))){
	    ht.goalsFor += hs;
	    ht.goalsAgainst += vs;
	    vt.goalsFor += vs;
	    vt.goalsAgainst += hs;
	    if( hc == null ){
	      hc = 0;
	    }
		ht.yellow += hc;
	    if( he == null ){
	      he = 0;
	    }
	    ht.red += he;
	    if( vc == null ){
	      vc = 0;
	    }
	    vt.yellow += vc;
	    if( ve == null ){
	      ve = 0;
	    }
	    vt.red += ve;
	
	    if( hs > vs ){
	      ht.won++;
	      vt.lost++;
	    } else  if( vs > hs ){
	      vt.won++;
	      ht.lost++;
	    } else {
	      ht.draw++;
	      vt.draw++;
	    }
	    ht.computePoints( hs, vs, hc, he );
	    vt.computePoints( vs, hs, vc, ve );
	} //  if( ht.notIncluded ||
  }  //   if (hs != null) {
  say( "</td>" );
  if( args.length >= 7 ){
    say( "<td>" + args[6].ci() + "</td>" );  //  change indicator
  }
  say( "</tr>" );

} //  function buildSched ( a, hs, vs ){
//  ___________________________________________________________________________
//  ___________________________________________________________________________

// the standard functions for ordering the teams. The functions return true if this 
// team is higher in the standings than all others; false other wise.

function pointCompare( t ){
    if( t.points > maxValue ){
      maxValue = t.points;
      return true;
    }
    return false;
}  //  function pointCompare
//  ________________________________________________________________________


function goalDiffCompare( t ){
    if( t.goalDiff > maxValue ){
      maxValue = t.goalDiff;
      return true;
    }
    return false;
}  //  function goalDiffCompare
//  ________________________________________________________________________


function pointsDeductedCompare( t ){
    if( t.pointsDeducted < minValue ){
      minValue = t.pointsDeducted;
      return true;
    }
    return false;
}  //  function pointsDeductedCompare
//  ________________________________________________________________________


function goalsAgainstCompare( t ){
    if( t.goalsAgainst < minValue ){
      minValue = t.goalsAgainst;
      return true;
    }
    return false;
}  //  function goalsAgainstCompare

//  ________________________________________________________________________


// change the contents of this array in the individual schedule to change sort options.
sortOrder = new Array(  pointCompare 
                       ,goalDiffCompare
                       ,pointsDeductedCompare
                       ,goalsAgainstCompare
             );
//  ________________________________________________________________________

function clearUsed(){
  var i;
  for( i = 0; i < numTeams; i++ ){
    teams[ i ].used = false; 
  }
}  //  function clearUsed(){

//  ________________________________________________________________________

function buildStandings() {
  var i;
  for( i = 0; i < numTeams; i++ ){
    with( teams[ i ] ){
      points += won * mulWon + draw * mulDraw - pointsDeducted; // misconduct computed in build schedule
      goalDiff = goalsFor - goalsAgainst;
    }
  } // for( i = 0; i < numTeams; i++ ){
  var breaks = new Array();
  for( i = 0; i < teams.length; i++ ){ // the initial team order is just the unsorted
    teamOrder[ i ] = i;                // order of making the teams.
  }
  breaks[ 0 ] = -1;              // the initial sort breaks is all the teams.
  breaks[ 1 ] = teams.length -1;

  var bix; // breaks index
  var soix; // sort order index
  var lowIdx, highIdx;
  var j, k;
  var selected;

  for( soix = 0; soix < sortOrder.length; soix++ ){
    delete nBreaks;
    var nBreaks = new Array();

    clearUsed();
    for( bix = 0; bix < breaks.length -1; bix++ ){
      lowIdx = breaks[ bix ] + 1;
      highIdx = breaks[ bix+1 ];
      //say( "bix: " + bix + "  lowIdx: " + lowIdx + "  highIdx: " + highIdx ); say();
      if( lowIdx != highIdx ){
        delete nOrder;
        nOrder = new Array();
        for( j = lowIdx; j <= highIdx; j++ ){
          maxValue = -Number.MAX_VALUE;
          minValue = Number.MAX_VALUE;
          for( k = lowIdx; k <= highIdx; k++ ){
            if( ( !teams[ teamOrder[ k ]].used )
                && sortOrder[ soix ](teams[ teamOrder[ k ]] )){
              //say( "selected: " + k ); say();
              selected = k;
            }  //  if( !teams[ 
          }  //  for( k = lowIdx; 
          //nOrder.push( teamOrder[ selected ]);  // doesn't work in ie below 5.5
          nOrder[ nOrder.length ] =  teamOrder[ selected ];
          teams[ teamOrder[ selected ]].used = true;
          //say( "end of k loop, norder: " + nOrder ); say();
        } //  for( j = lowIdx; 
        for( j = lowIdx, k = 0; j <= highIdx; j++, k++ ){
          //teamOrder[ j ] = nOrder.shift();  // doesn't work in ie below 5.5
          teamOrder[ j ] = nOrder[ k ];
        } //  for( j = lowIdx;
        //say( "final order: " + teamOrder ); say(); 
      }  //  if( lowIdx
      //  now recompute the breaks array
      maxValue = -Number.MAX_VALUE;
      minValue = Number.MAX_VALUE;
      delete intervalBreaks;
      intervalBreaks = new Array();
      for( j = highIdx; j >= lowIdx; j-- ){
	if( sortOrder[ soix ](teams[ teamOrder[ j ]] )){
	  //intervalBreaks.push( j );  // doesn't work in ie below 5.5
	  intervalBreaks[ intervalBreaks.length ] = j;  
	}  //  if( sortOrder[
      }  //  for( j = highIdx
	  
      //say( "intervalBreaks: " + intervalBreaks ); say();
      for( j = intervalBreaks.length-1; j >= 0; j-- ){
	//nBreaks.push( intervalBreaks[ j ] ); // doesn't work in ie below 5.5
	nBreaks[ nBreaks.length ] = intervalBreaks[ j ]; // doesn't work in ie below 5.5
      }
      //say( "nBreaks: " + nBreaks); say();
    }  //  for( bix = 0;
    delete breaks;
    var breaks = new Array();
    breaks[ 0 ] = -1;
    for( j = 0; j < nBreaks.length; j++ ){
      breaks[ j+1 ] = nBreaks [ j ];
    }
    //say( "new breaks: " + breaks ); say();
    //displayStandings( teamOrder );
  }  //  for( soix = 0;
} // function buildStandings
//  ________________________________________________________________________

function displayStandings( order ){
  say( "<p><p><div align='center'><table border=0 cellpadding=4>" );
  say(  "<caption><b><font size=+1>Team Standings "
      + "</font></b><br>" 
	  + standComment
	  + "</caption>" );
  say( "<tr><th>Team</th><th>Won</th><th>Lost</th><th>Draw</th><th>Cautions</th>"
      + "<th>Send-offs</th><th>Points<br>Deducted</th><th>Points</th><th>Goals<br>For</th>"
      + "<th>Goals<br>Against</th><th>Goal<br>Diff</th></tr>" );
  for( i = 0; i < numTeams; i++ ){
    if( !teams[ order[ i ]].notIncluded ){
	    say(  "<tr><td>" + teams [ order[ i ]].name
	        + "</td><td align='center'>" + teams [order[ i ]].won
	        + "</td><td align='center'>" + teams [order[ i ]].lost
	        + "</td><td align='center'>" + teams [order[ i ]].draw
	        + "</td><td align='center'>" + teams [order[ i ]].yellow
	        + "</td><td align='center'>" + teams [order[ i ]].red
	        + "</td><td align='center'>" + teams [order[ i ]].pointsDeducted
	        + "</td><td align='center'>" + teams [order[ i ]].points
	        + "</td><td align='center'>" + teams [order[ i ]].goalsFor
	        + "</td><td align='center'>" + teams [order[ i ]].goalsAgainst
	        + "</td><td align='center'>" + teams [order[ i ]].goalDiff
	        + "</td></tr>"
	      );
	} //  if( !teams[ order ...
  } // for( i = 0; i < numTeams; i++ ){

  say( "</table></div>" );
}  //  function displayStandings(
//  ________________________________________________________________________


function buildPools( numPools ){ // build table of pool assignments, r117a, r55, r144, r143, r56, r117b );
  say( "<p><p><div align='center'><table border='0' cellpadding='4'>" ); // 
  say(  "<caption><b><font size=+1>Playoff Pools</font></b></caption>" );
  var i, j, k;
  var poolLetters = "ABCDEFGHIJ";   // max 10 pools
  say( "<tr>" );
  for( i = 0; i < numPools; i++ ){
    say( "<th" );
    if( i != 0 ){
      say( " width = '20'></th><th" );
    }
    say( ">Pool " + poolLetters.charAt( i ) + "</th>" );
  }  //  for( i = 0;
  say( "</tr>" );
  
  say( "<tr>" );
  var numTeams = arguments.length -1;
  var numTeamsInPool;
  k = 1;
  for( i = 0; i < numPools; i ++ ){
    numTeamsInPool = Math.ceil( numTeams / ( numPools - i ) );
    say( "<td" );
    if( i != 0 ){
      say( "></td><td" );
    }
    say( " valign='top'>" );
    for( j = 0; j < numTeamsInPool; j++ ){
      if( j != 0 ){
        say( "<br>" );
      } 
      say( arguments[ j + k ].name ); 
    }  //  for( j = 0;
    say( "</td>" );
    numTeams -= numTeamsInPool;
    k += numTeamsInPool;
  }  //  for( i = 0;
  say( "</tr>" );
  say( "</table></div>" );
}  //  function buildPools( numPools ){