  
  // This function checks the values of the Edit Season form
  // and if there were any errors it displays an alert to the
  // user, otherwise the form is submitted.
  function submitSaveSeason() {

    var emptyMessage = " is a required field.\n";
    var errorMessages = ""
    var focusSet = false;
    
    var seasonName = document.getElementById("name");
    var startDate = document.getElementById("startDate");
    var endDate = document.getElementById("endDate");
    
    if (seasonName.value == "") {
      errorMessages += "Season name" + emptyMessage;
      seasonName.focus();
      focusSet = true;
    }
    if (startDate.value == "") {
      errorMessages += "Start Date" + emptyMessage;
      if (!focusSet) {
        startDate.focus();
        focusSet = true;
      }
    }
    if (endDate.value == "") {
      errorMessages += "End Date" + emptyMessage;
      if (!focusSet) {
        endDate.focus();
        focusSet = true;
      }
    }
    if (errorMessages == "") {
      document.getElementById("editSeasonForm").submit();
    } else {
      alert(errorMessages);
    }
    return;
  }
  
  
  // This function checks the values of the Edit Competition form
  // and if there were any errors it displays an alert to the
  // user, otherwise the form is submitted.
  function submitCompetition() {
  
    var emptyMessage = " is a required field.\n";
    var errorMessages = ""
    var focusSet = false;
  
    var countyId = document.getElementById("countyId");
    var seasonId = document.getElementById("seasonId"); 
    var competitionTypeId = document.getElementById("competitionTypeId"); 
    var modifierId = document.getElementById("modifierId");
    
    if (countyId.value == -1) {
      errorMessages += "County" + emptyMessage;
      countyId.focus();
      focusSet = true;
    }
    if (seasonId.value == -1) {
      errorMessages += "Season" + emptyMessage;
      if (!focusSet) {
        seasonId.focus();
        focusSet = true;
      }
    }
    if (competitionTypeId.value == -1) {
      errorMessages += "Competition type" + emptyMessage;
      if (!focusSet) {
        competitionTypeId.focus();
        focusSet = true;
      }  
    }
    if (modifierId.value == -1) {
      errorMessages += "Modifier" + emptyMessage;
      if (!focusSet) {
        modifierId.focus();
        focusSet = true;
      }
    }
    
    if (errorMessages == "") {
      document.getElementById("editCompetitionForm").submit();
    } else {
      alert(errorMessages);
    }
    return true;
  }


  // This function checks the values of the Edit Club form
  // and if there were any errors it displays an alert to the
  // user, otherwise the form is submitted.
  function submitSaveClub() {

    var emptyMessage = " is a required field.\n";
    var errorMessages = ""
    var focusSet = false;
    
    var name = document.getElementById("name");
    var numberOfCourts = document.getElementById("numberOfCourts");
    var telephoneNumber = document.getElementById("telephoneNumber");
    var addressLine1 = document.getElementById("addressLine1");
    var postCode = document.getElementById("postCode");
    var countyId = document.getElementById("countyId");
    var directions = document.getElementById("directions");
    
    if (name.value == "") {
      errorMessages += "Club Name" + emptyMessage;
      name.focus();
      focusSet = true;
    }
    if (numberOfCourts.value == "") {
      errorMessages += "Number Of Courts" + emptyMessage;
      if (!focusSet) {
        numberOfCourts.focus();
        focusSet = true;
      }
    }
    if (telephoneNumber.value == "") {
      errorMessages += "Telephone Number" + emptyMessage;
      if (!focusSet) {
        telephoneNumber.focus();
        focusSet = true;
      }
    }
    if (addressLine1.value == "") {
      errorMessages += "Address Line 1" + emptyMessage;
      if (!focusSet) {
        addressLine1.focus();
        focusSet = true;
      }
    }
    if (postCode.value == "") {
      errorMessages += "Post Code" + emptyMessage;
      if (!focusSet) {
        postCode.focus();
        focusSet = true;
      }
    }
    if (countyId.value == -1) {
      errorMessages += "County" + emptyMessage;
      if (!focusSet) {
        countyId.focus();
        focusSet = true;
      }
    }
    if (directions.value == "") {
      errorMessages += "Directions" + emptyMessage;
      if (!focusSet) {
        directions.focus();
        focusSet = true;
      }
    }
    
    if (errorMessages == "") {
      document.getElementById("editClubForm").submit();
    } else {
      alert(errorMessages);
    }
    return;
  }
  
  
  function submitSaveTeam() {

    var emptyMessage = " is a required field.\n";
    var errorMessages = ""
    var focusSet = false;
    
    var name = document.getElementById("name");
    var shortName = document.getElementById("shortName");
    var clubId = document.getElementById("clubId");

    if (name.value == "") {
      errorMessages += "Team Name" + emptyMessage;
      name.focus();
      focusSet = true;
    }
    if (shortName.value == "") {
      errorMessages += "Team Short Name" + emptyMessage;
      if (!focusSet) {
        shortName.focus();
        focusSet = true;
      }
    }
    if (clubId.value == -1) {
      errorMessages += "Club Id" + emptyMessage;
      if (!focusSet) {
        clubId.focus();
        focusSet = true;
      }
    }
    
    if (errorMessages == "") {
      document.getElementById("editTeamForm").submit();
    } else {
      alert(errorMessages);
    }
    return;
  }
  
  
  function submitSavePerson() {

    var nameRegExp = /[^a-zA-Z]+/;

    var emptyMessage = " is a required field.\n";
    var errorMessages = ""
    var focusSet = false;
    
    var firstName = document.getElementById("firstName");
    var lastName = document.getElementById("lastName");
    var teamId = document.getElementById("teamId");

    if (firstName.value == "") {
      errorMessages += "First Name" + emptyMessage;
      firstName.focus();
      focusSet = true;
    }
    if (firstName.value != "" && nameRegExp.test(firstName.value)) {
      errorMessages += "First Name must consist of only alphabetic characters\n";
      firstName.focus();
      focusSet = true;
    }
    if (lastName.value == "") {
      errorMessages += "Last Name" + emptyMessage;
      if (!focusSet) {
        lastName.focus();
        focusSet = true;
      }
    }
    if (lastName.value != "" && nameRegExp.exec(lastName.value)) {
      errorMessages += "Last Name must consist of only alphabetic characters\n";
      if (!focusSet) {
        lastName.focus();
        focusSet = true;
      }
    }
    if (teamId.value == -1) {
      errorMessages += "Team" + emptyMessage;
      if (!focusSet) {
        teamId.focus();
        focusSet = true;
      }
    }
    
    if (errorMessages == "") {
      document.getElementById("editPersonForm").submit();
    } else {
      alert(errorMessages);
    }
    return;
  }
  
  
  function assignAdminToPerson() {

    var emptyMessage = " is a required field.\n";
    var errorMessages = ""
    var focusSet = false;
    
    var adminLevel = document.getElementById("adminTypeId");
    var associatedPersonId = document.getElementById("personId");
    var teamId = document.getElementById("assignTeamId");

    if (adminLevel.value == -1) {
      errorMessages += "Admin Level" + emptyMessage;
      adminLevel.focus();
      focusSet = true;
    }
    if (associatedPersonId.value == -1) {
      errorMessages += "Associated Person" + emptyMessage;
      if (!focusSet) {
        associatedPersonId.focus();
        focusSet = true;
      }
    }
    if (teamId.value == -1) {
      errorMessages += "Associated Team" + emptyMessage;
      if (!focusSet) {
        teamId.focus();
        focusSet = true;
      }
    }
    if (errorMessages == "") {
      document.getElementById("assignRoleForm").submit();
    } else {
      alert(errorMessages);
    }
    return;
  }
  
  
  function removeAdminRights() {

    var emptyMessage = " is a required field.\n";
    var errorMessages = "";
    var focusSet = false;
  
    var personId = document.getElementById("removeAdminPersonId");

    if (personId.value == -1) {
      errorMessages += "Person" + emptyMessage;
      personId.focus();
      focusSet = true;
    }
    if (errorMessages == "") {
      document.getElementById("removeRoleForm").submit();
    } else {
      alert(errorMessages);
    }
    return;
  }
  
  
  function searchForPlayers() {

    var emptyMessage = " is a required field.\n";
    var errorMessages = "";
    var focusSet = false;
  
    var lastName = document.getElementById("searchLastName");

    if (lastName.value == "") {
      errorMessages += "Last name" + emptyMessage;
      lastName.focus();
    }
    if (errorMessages == "") {
      document.getElementById("updatePlayerForm").submit();
    } else {
      alert(errorMessages);
    }
    return;
  }
  
  
  function searchForPlayersToDelete() {

    var emptyMessage = " is a required field.\n";
    var errorMessages = "";
    var focusSet = false;

    var lastName = document.getElementById("searchDeleteLastName");

    if (lastName.value == "") {
      errorMessages += "Last name" + emptyMessage;
      lastName.focus();
    }
    if (errorMessages == "") {
      document.getElementById("deletePlayerForm").submit();
    } else {
      alert(errorMessages);
    }
    return;
  }
  
  
  function deletePlayer(playerId, replacementPlayerId) {

    var emptyMessage = " is a required field.\n";
    var errorMessages = "";
    var focusSet = false;
  
    var replacementName = document.getElementById("replacementPlayerFor-" + playerId);

    if (replacementName.value == -1) {
      errorMessages += "Replacement player" + emptyMessage;
      focusSet = true;
      replacementName.focus();
    }
    
    if (errorMessages == "") {
      var playerIdElement = document.getElementById("deletePlayerId");
      var replacementPlayerIdElement = document.getElementById("replacementPlayerId");
      playerIdElement.value = playerId;
      replacementPlayerIdElement.value = replacementName.value;
      document.getElementById("deletePlayerForm").submit();
    } else {
      alert(errorMessages);
    }
    return;
  }
  
  
  function updatePlayer(playerId) {

    var emptyMessage = " is a required field.\n";
    var errorMessages = "";
    var focusSet = false;
  
    var firstName = document.getElementById("resultFirstName-" + playerId);
    var lastName = document.getElementById("resultLastName-" + playerId);

    if (firstName.value == "") {
      errorMessages += "First name" + emptyMessage;
      focusSet = true;
      firstName.focus();
    }
    
    if (lastName.value == "") {
      errorMessages += "Last name" + emptyMessage;
      if (!focusSet) {
        lastName.focus();
      }
    }
    
    if (errorMessages == "") {
      var personId = document.getElementById("resultPersonId");
      personId.value = playerId;
      document.getElementById("updatePlayerForm").submit();
    } else {
      alert(errorMessages);
    }
    return;
  }
  
  
  function submitSaveNewPenalty() {

    var errorMessages = "";
    var emptyMessage = " is a required field.\n";
    var focusSet = false;
    var teamId = document.getElementById("teamId");
    var description = document.getElementById("description");
    var penaltyPoints = document.getElementById("penaltyPoints");
    
    
    if (teamId.value == -1) {
      errorMessages += "Please select a team.\n";
      focusSet = true;
      teamId.focus();
    }
    if (description.value == "") {
      errorMessages += "Description" + emptyMessage;
      if (!focusSet) {
        description.focus();
        focusSet = true;
      }
    }
    if (penaltyPoints.value == "") {
      errorMessages += "Penalty Points" + emptyMessage;
      if (!focusSet) {
        penaltyPoints.focus();
        focusSet = true;
      }
    }
    
    if (errorMessages == "") {
      document.getElementById("editPenaltyForm").submit();
    } else {
      alert(errorMessages);
    }
    return;
  }
  
  
  function submitDeletePenalty(penaltyId) {
    var id = document.getElementById("penaltyId");
    var formAction = document.getElementById("formAction");
    id.value = penaltyId;
    formAction.value = "deleteTeamPenalties";
    
    document.getElementById("editPenaltyForm").submit();
    return;
  }
  
  // Check the validation of the registration form.
  function submitLogin() {
    var loginUserNameRegExp = /[^a-zA-Z0-9\_\-]+/;
    var loginEmptyMessage = " is a required field.\n";
    var loginErrorMessages = "";
    var loginFocusSet = false;

    var loginUserName = document.getElementById("loginUserName");
    var loginPassword = document.getElementById("loginPassword");

    if (loginUserName.value == "") {
      loginErrorMessages += "Login user name" + loginEmptyMessage;
      if (!loginFocusSet) {
        loginUserName.focus();
        loginFocusSet = true;
      }
    } else if (loginUserNameRegExp.test(loginUserName.value)) {
      loginErrorMessages += "Login User name can only contain letters, numbers, '-', '_'\n";
      if (!loginFocusSet) {
        loginUserName.focus();
        loginFocusSet = true;
      }
    }
    if (loginPassword.value == "") {
      loginErrorMessages += "Password" + loginEmptyMessage;
      if (!loginFocusSet) {
        loginPassword.focus();
        loginFocusSet = true;
      }
    } else if (loginUserNameRegExp.test(loginPassword.value)) {
      loginErrorMessages += "Login password can only contain letters, numbers, '-', '_'\n";
      if (!loginFocusSet) {
        loginPassword.focus();
        loginFocusSet = true;
      }
    }
    if (loginErrorMessages == "") {
      document.getElementById("loginForm").submit();
    } else {
      alert(loginErrorMessages);
    }
    return;
  }
  
  
  // This method checks the validation of the registration form.
  function submitRegistration() {
    var nameRegExp = /[^a-zA-Z]+/;
    var userNameRegExp = /[^a-zA-Z0-9\_\-]+/;
    var emailRegExp = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

    var emptyMessage = " is a required field.\n";
    var regExpFailure = " must contain only alphabetic characters.\n";
    var errorMessages = "";
    var focusSet = false;

    var firstName = document.getElementById("firstName");
    var middleName = document.getElementById("middleName");
    var lastName = document.getElementById("lastName");
    var emailAddress = document.getElementById("emailAddress"); 
    var emailAddressConfirm = document.getElementById("emailAddressConfirm");
    var postCode = document.getElementById("postCode");
    var addressLine1 = document.getElementById("addressLine1");
    var addressLine2 = document.getElementById("addressLine2");
    var townOrCity = document.getElementById("townOrCity");
    var homeTelephoneNumber = document.getElementById("homeTelephoneNumber");
    var mobileTelephoneNumber = document.getElementById("mobileTelephoneNumber");
    var dobDay = document.getElementById("dobDay");
    var dobMonth = document.getElementById("dobMonth");
    var dobYear = document.getElementById("dobYear");
    var userName = document.getElementById("userName");
    var password = document.getElementById("password");
    var passwordConfirm = document.getElementById("passwordConfirm");
    var clubId = document.getElementById("clubId");
    var profile = document.getElementById("profile");
      
    if (firstName.value == "") {
      errorMessages += "First Name" + emptyMessage;
      firstName.focus();
      focusSet = true;
    } else if (nameRegExp.test(firstName.value)) {
      errorMessages += "First Name" + regExpFailure;
      firstName.focus();
      focusSet = true;
    }
    if (lastName.value == "") {
      errorMessages += "Last Name" + emptyMessage;
      if (!focusSet) {
        lastName.focus();
        focusSet = true;
      }
    } else if (nameRegExp.test(lastName.value)) {
      errorMessages += "Last Name" + regExpFailure;
      if (!focusSet) {
        lastName.focus();
        focusSet = true;
      }
    }
    if (middleName.value != "" && nameRegExp.test(middleName.value)) {
      errorMessages += "Middle Name" + regExpFailure;
      if (!focusSet) {
        middleName.focus();
        focusSet = true;
      }
    }
    if (emailAddress.value == "") {
      errorMessages += "Email Address " + emptyMessage;
      if (!focusSet) {
        emailAddress.focus();
        focusSet = true;
      }
    } else if (!emailRegExp.test(emailAddress.value)) {
      errorMessages += "Email must be valid email address.\n";
      if (!focusSet) {
        emailAddress.focus();
        focusSet = true;
      }
    }
    if (emailAddressConfirm.value == "") {
      errorMessages += "Email Address Confirm" + emptyMessage;
      if (!focusSet) {
        emailAddressConfirm.focus();
        focusSet = true;
      }
    } else if (!emailRegExp.test(emailAddressConfirm.value)) {
      errorMessages += "Email Address Confirm must be valid email address.\n";
      if (!focusSet) {
        emailAddressConfirm.focus();
        focusSet = true;
      }
    }
    if (homeTelephoneNumber.value == "" && mobileTelephoneNumber.value == "") {
      errorMessages += "Please provide at least one telephone number.\n";
      if (!focusSet) {
        homeTelephoneNumber.focus();
        focusSet = true;
      }
    }
    if (dobDay.value == '-1' || dobMonth == '-1' || dobYear == '-1') {
      errorMessages += "Please provide a valid date of birth.\n";
      if (!focusSet) {
        dobDay.focus();
        focusSet = true;
      }
    }
    if (userName.value == "") {
      errorMessages += "User name" + emptyMessage;
      if (!focusSet) {
        userName.focus();
        focusSet = true;
      }
    } else if (userNameRegExp.test(userName.value)) {
      errorMessages += "User name can only contain letters, numbers, '-', '_'\n";
      if (!focusSet) {
        userName.focus();
        focusSet = true;
      }
    }
    if (password.value == "") {
      errorMessages += "Password" + emptyMessage;
      if (!focusSet) {
        password.focus();
        focusSet = true;
      }
    } else if (userNameRegExp.test(password.value)) {
      errorMessages += "password can only contain letters, numbers, '-', '_'\n";
      if (!focusSet) {
        password.focus();
        focusSet = true;
      }
    } else if (password.value != passwordConfirm.value) {
      errorMessages += "Password must be the same as Password Confirm.\n";
    }
    if (passwordConfirm.value == "") {
      errorMessages += "Password confirm " + emptyMessage;
      if (!focusSet) {
        passwordConfirm.focus();
        focusSet = true;
      }
    } else if (userNameRegExp.test(passwordConfirm.value)) {
      errorMessages += "Password confirm can only contain letters, numbers, '-', '_'\n";
      if (!focusSet) {
        passwordConfirm.focus();
        focusSet = true;
      }
    }
    if (clubId.value == -1) {
      errorMessages += "Please select a club.\n";
    }
    if (errorMessages == "") {
      document.getElementById("registrationForm").submit();
    } else {
      alert(errorMessages);
    }
    return;
  } 


  // Causes the rankings table to have alternate colours per row.
  function alternateDivColours(tableName) {
    var table = document.getElementById(tableName);
    
    if (null != table) {
        var rowCollection = table.getElementsByTagName("tr");
        var classNames = ['mainContentBold', 'mainContentGreyBold'];
    
        if (null != rowCollection) {
        
            for (var ii = 0; ii < rowCollection.length; ii++) {
    	        var row = rowCollection[ii];
    	        row.className = classNames[ii % 2];
    	        var anchorCollection = row.getElementsByTagName("a");
    	        for (var jj = 0; jj < anchorCollection.length; jj++) {
        	        anchorCollection[jj].className = classNames[ii % 2];
    	        }
            }
        }
    }
    return;
  }
  
  
  // Edit Match Component Function.
  // This function works out whether the user wants to add a new player
  // or use one of the players available from the dropdown. If the former
  // then the user will have checked the 'add player' checkbox.
  // param - checkBox: checked if the user wants to add a new player, unchecked
  //                   if the player involved in the match already exists.
  function addExistingOrNewPlayer(checkBox) {
    
    if (checkBox.id == ("isHomePlayerExistPosition" + checkBox.value)) {
	    if (checkBox.checked) {
	      document.getElementById("addHomeNameDivPosition" + checkBox.value).style.display = "inline";
	      document.getElementById("selectHomeDivPosition" + checkBox.value).style.display = "none";
	    } else {
	      document.getElementById("addHomeNameDivPosition" + checkBox.value).style.display = "none";
	      document.getElementById("selectHomeDivPosition" + checkBox.value).style.display = "inline";
        document.getElementById("homePlayerFirstNamePosition" + checkBox.value).value = "first name";
        document.getElementById("homePlayerLastNamePosition" + checkBox.value).value = "last name";
	    }
    } else {
      if (checkBox.checked) {
        document.getElementById("addAwayNameDivPosition" + checkBox.value).style.display = "inline";
        document.getElementById("selectAwayDivPosition" + checkBox.value).style.display = "none";
      } else {
        document.getElementById("addAwayNameDivPosition" + checkBox.value).style.display = "none";
        document.getElementById("selectAwayDivPosition" + checkBox.value).style.display = "inline";
        document.getElementById("awayPlayerFirstNamePosition" + checkBox.value).value = "first name";
        document.getElementById("awayPlayerLastNamePosition" + checkBox.value).value = "last name";
      }
    }
    return;
  }
  
  
  // Function to clear the value of an input field when the focus is on that
  // particular field (this method will therefore be called on an onFocus event
  // for a specific element).
  function focusClearValues(inputField) {
    inputField.value = "";
    return;
  }
  
  
  // The main Edit Match Form!
  // This function is called when the user tries to submit the Edit Match form.
  // Its main function is to verify that all the fields have been filled in and that
  // they have been populated with valid information. For example, it will check
  // individual match scores to see that the score is valid (ie 3-1 instead of 2-2)
  // and will return false if any errors are found.
  function submitSaveMatch(isEnglishScoring) {
    // alert("Is english scoring: " + isEnglishScoring);
    var nameRegExp = /[^a-zA-Z]+/;
    var scoreRegExp = /\d{1,2}/;

    var emptyMessage = " is a required field.\n";
    var regExpFailure = " must contain only alphabetic characters.\n";
    var errorMessages = "";
    
    // Store the number of errors we find in the form.
    numberOfErrors = 0;
    
    // There are 5 matches that need to be validated on the page.
    for (var ii = 1; ii <= 5; ii++) {
      var homePlayerFirstName = document.getElementById("homePlayerFirstNamePosition" + ii);
      var homePlayerLastName = document.getElementById("homePlayerLastNamePosition" + ii);
      var homePlayerId = document.getElementById("homePlayerIdPosition" + ii);
      var homePlayerNotExist = document.getElementById("isHomePlayerExistPosition" + ii);
      var isHomeVictory = document.getElementById("isHomeVictoryPosition" + ii);
      var awayPlayerFirstName = document.getElementById("awayPlayerFirstNamePosition" + ii);
      var awayPlayerLastName = document.getElementById("awayPlayerLastNamePosition" + ii);
      var awayPlayerId = document.getElementById("awayPlayerIdPosition" + ii);
      var awayPlayerNotExist = document.getElementById("isAwayPlayerExistPosition" + ii);
      
      // Only bother doing any validation of teams if we are NOT processing a walkover.
      // If the tie was a walkover then we don't need to do anything.
      if (isHomeVictory.value != 3 && isHomeVictory.value != 4) {
      
	      // The first thing to consider is whether the 'home player' check box is checked
	      // or not. If it is, then we DO want to try and process the first and last name
	      // of the newly added player.
	      if (homePlayerNotExist.checked) {
	        if (homePlayerFirstName.value == "" || homePlayerFirstName.value == "first name") {
	          errorMessages += "No." + ii + " First Name" + emptyMessage;
	          numberOfErrors++;
	        } else if (nameRegExp.test(homePlayerFirstName.value)) {
	          errorMessages += "No." + ii + " First Name" + regExpFailure;
	          numberOfErrors++;
	        }
	        if (homePlayerLastName.value == "" || homePlayerLastName.value == "last name") {
	          errorMessages += "No." + ii + " Last Name" + emptyMessage;
	          numberOfErrors++;
	        } else if (nameRegExp.test(homePlayerLastName.value)) {
	          errorMessages += "No." + ii + " Last Name" + regExpFailure;
	          numberOfErrors++;
	        }
	      } else {
	        if (homePlayerId.value == -1) {
	          errorMessages += "Please select a home team player to play at No." + ii + ".\n";
	          numberOfErrors++;
	        }
	      }
	      if (isHomeVictory.value == -1) {
	        errorMessages += "Who won at position No." + ii + "? Please select.\n";
	        numberOfErrors++;
	      }
	      if (awayPlayerNotExist.checked) {
	        if (awayPlayerFirstName.value == "" || awayPlayerFirstName.value == "first name") {
	          errorMessages += "No." + ii + " First Name" + emptyMessage;
	          numberOfErrors++;
	        } else if (nameRegExp.test(awayPlayerFirstName.value)) {
	          errorMessages += "No." + ii + " First Name" + regExpFailure;
	          numberOfErrors++;
	        }
	        if (awayPlayerLastName.value == "" || awayPlayerLastName.value == "last name") {
	          errorMessages += "No." + ii + " Last Name" + emptyMessage;
	          numberOfErrors++;
	        } else if (nameRegExp.test(awayPlayerLastName.value)) {
	          errorMessages += "No." + ii + " Last Name" + regExpFailure;
	          numberOfErrors++;
	        }
	      } else {
	        if (awayPlayerId.value == -1) {
	          errorMessages += "Please select an away team player to play at No." + ii + ".\n";
	          numberOfErrors++;
	        }
	      }
	      
	      // Lets store the number of home games and away games each player has won,
	      // to help us detemine how to validate games 4 and 5.
	      var homeGamesWon = 0;
	      var awayGamesWon = 0;
	      var isInvalidGame = false;
	      
	      for (var jj = 1; jj <= 5; jj++) {
	      
	        homeScore = document.getElementById("homeScore" + jj + "Position" + ii).value;
	        awayScore = document.getElementById("awayScore" + jj + "Position" + ii).value;
	        
	        // Now we are using text fields rather than dropdown menu's it is possible for the user to
	        // enter invalid numbers.
	        var validHomeScore = scoreRegExp.test(homeScore) || homeScore == "";
	        if (!validHomeScore) {
	          errorMessages += "Home score for game " + jj + " for Position No." + ii + " contains invalid characters.\n";
	          numberOfErrors++;
	        }
	        var validAwayScore = scoreRegExp.test(awayScore) || awayScore == "";
	        if (!validHomeScore) {
	          errorMessages += "Away score for game " + jj + " for Position No." + ii + " contains invalid characters.\n";
	          numberOfErrors++;
	        }
	        
	        if (jj <= 3) {
		        if (validateScore(homeScore, awayScore, isEnglishScoring) && homeScore != '' && awayScore != '') {
		          var homeUKScoringWin = isEnglishScoring && ('10' == homeScore || ('9' == homeScore && homeScore > awayScore));
	              var homeUSScoringWin = !isEnglishScoring && homeScore > awayScore;
		          if (homeUKScoringWin || homeUSScoringWin) {
	                homeGamesWon++;
		          } else {
	                awayGamesWon++;
		          }
			    } else {
	              isInvalidGame = true;
	              errorMessages += "Game " + jj + " for Position No." + ii + " is incorrect.\n";
	              numberOfErrors++;
	            }
	        }
	        if ((jj == 4 || jj == 5) && !isInvalidGame) {
	          // We don't always want to process the 4th game. Only if someone hasn't
	          // already won in 3 games do we want to validate this game. Also, only if
	          // the first three games have been filled out correctly.
	          if (homeGamesWon != 3 && awayGamesWon != 3) {
	            var awayScoreMissing = homeScore != '' && awayScore == '';
	            var homeScoreMissing = awayScore != '' && homeScore == '';
	            // alert("match " + ii + ", game " + jj + " home score: " + homeScore + ", away score: " + awayScore);
	            if (validateScore(homeScore, awayScore, isEnglishScoring) && !awayScoreMissing && !homeScoreMissing) {
	              var homeUKScoringWin = isEnglishScoring && ('10' == homeScore || ('9' == homeScore && homeScore > awayScore));
	              var homeUSScoringWin = !isEnglishScoring && homeScore > awayScore;
	              if (homeUKScoringWin || homeUSScoringWin) {
	                homeGamesWon++;
	              } else {
	                awayGamesWon++;
	              }
	            } else {
	              isInvalidGame = true;
	              errorMessages += "Game " + jj + " for Position No." + ii + " is incorrect.\n";
	              numberOfErrors++;
	            }
	          } // else {
	            // if (validateScore(homeScore, awayScore, isEnglishScoring)) {
	            //   errorMessages += "You have entered too many games for match " + ii;
	            //   numberOfErrors++;
	            //   break;
	            // }
	          // }
	        }
	      }
	
	      // Don't bother to process the rest of the form if they have already
	      // clocked up a whole load of errors.
	      if (numberOfErrors > 5) {
	        break;
	      }
	  }
    }
    
    // If the user has really filled in the scores completely wrong, then don't
	// write a huge list of errors back to them, just write a simple error message.
	if (errorMessages == "") {
	  
	  // Then submit the form.
      document.getElementById("editMatchForm").submit();
	} else {
	  if (numberOfErrors > 5) {
	    alert("There are numerous mistakes. Fill the form out properly.");
	  } else {
	    alert(errorMessages);
	  }
	}
	
	// Important to set the number of errors back to zero.
	numberOfErrors == 0;
    return;
  }
  
  
  // Edit Match function.
  // When we load up the Edit Match page, we will have sent up to the score text fields a whole load
  // of -1's. I need to do this because we need to distinguish between a game that was won 11-0, for
  // example, and a game that hasn't been played at all. Once all the values have been loaded we then
  // want to clear all the -1's and leave all the 0's.
  function onloadRemoveNegativeScores() {
    
    // There are 5 matches that need to be validated on the page.  This will need to change when
    // we are catering for less than 5 matches. Fun.
    for (var ii = 1; ii <= 5; ii++) {
      
      // Each match is played to best of 5 games.
      for (var jj = 1; jj <= 5; jj++) {
       
        var homeScoreElement = document.getElementById("homeScore" + jj + "Position" + ii);
	    var awayScoreElement = document.getElementById("awayScore" + jj + "Position" + ii);
	    
	    // alert(
	    //   "homeScore" + jj + "Position" + ii + " value: " + homeScoreElement.value +
	    //   "\nawayScore" + jj + "Position" + ii + " value: " + awayScoreElement.value
	    // );
	    
	    if (homeScoreElement.value == '-1') {
	      homeScoreElement.value = "";
	    }
	    if (awayScoreElement.value == '-1') {
	      awayScoreElement.value = "";
	    }
      }
    }
    
  }
  
  
  
  // Edit Match function.
  // This function simply validates a game score. For example, a squash game score
  // can only be of a certain format like 9-0, 10-9, 10-8, 9-8 etc. This function
  // ensures that the user has filled the individual games scores in correctly.
  function validateScore(homeScore, awayScore, isEnglishScoring) {
    var returnValue = false;
    if (isEnglishScoring) {
      if (homeScore == 10 && (awayScore == 9 || awayScore == 8)) {
        returnValue = true; 
      } else if (awayScore == 10 && (homeScore == 9 || homeScore == 8)) {
        returnValue = true; 
      } else if (homeScore == 9 && (awayScore < 9 && awayScore != -1)) {
        returnValue = true;
      } else if (awayScore == 9 && (homeScore < 9 && homeScore != -1)) {
        returnValue = true;
      }
    } else {
    
      // We are doing American scoring to 11. As it is potentially possible to score any number
      // of points per game, the only validation we can do is ensure that the user hasn't entered
      // a negative number for the game.
      if (homeScore >= 11 || awayScore >= 0) {
        returnValue = true;
      }
    }
    // alert("home score is: " + homeScore + ", away score is: " + awayScore + ", is valid score: " + returnValue);
    return returnValue;
  }
  
  
  function addFixture() {
  
    var returnValue = false;
    var errorMessages = "";
    var emptyMessage = " is a required field.\n";
    var focusSet = false;
    var homeTeamId = document.getElementById("homeTeamId");
    var awayTeamId = document.getElementById("awayTeamId");
    var competitionId = document.getElementById("competitionId");
    var day = document.getElementById("fixtureDay");
    var month = document.getElementById("fixtureMonth");
    var year = document.getElementById("fixtureYear");
    
    if (homeTeamId.value == '-1') {
      errorMessages += "Home team" + emptyMessage;
      if (!focusSet) {
        homeTeamId.focus();
        focusSet = true;
      }
    }
    if (awayTeamId.value == '-1') {
      errorMessages += "Away team" + emptyMessage;
      if (!focusSet) {
        awayTeamId.focus();
        focusSet = true;
      }
    }
    if (competitionId.value == '-1') {
      errorMessages += "Competition" + emptyMessage;
      if (!focusSet) {
        competitionId.focus();
        focusSet = true;
      }
    }
    if (day.value == '-1') {
      errorMessages += "Day" + emptyMessage;
      if (!focusSet) {
        day.focus();
        focusSet = true;
      }
    }
    if (month.value == '-1') {
      errorMessages += "Month" + emptyMessage;
      if (!focusSet) {
        month.focus();
        focusSet = true;
      }
    }
    if (year.value == '-1') {
      errorMessages += "Year" + emptyMessage;
      if (!focusSet) {
        year.focus();
        focusSet = true;
      }
    }
    
    if (errorMessages != "") {
      alert(errorMessages);
    } else {
      returnValue = true;
    }
    return returnValue;
  }
  
  
  // Open and close a div, depending on what element names are
  // provided.
  function displayDiv(divName) {
    var helpDiv = document.getElementById(divName);
    if (helpDiv.style.display == "none") {
      helpDiv.style.display = "inline";
    } else {
      helpDiv.style.display = "none";
    }
    
    return;
  }
  
  // Used on the player profile page, used to point an image to the Chart Controller
  // which in turn generates the appropriate image depending on the parameters of
  // this method.
  function displayGameMatchesChart(contextPath, playerId, seasonId) {
    
    var image = document.getElementById("matchesWonChart");
    image.src = contextPath +
                "/servlet/chartController/matchesWon?playerId=" +
                playerId +
                "&seasonId=" +
                seasonId;
    
    // We also want to hide the textual data that this chart displays.
    for (var ii = 1; ii <= 3; ++ii) {
    	var dataRow = document.getElementById("matchStatsRow" + ii);
    	dataRow.style.display = "none";
    }
    return;
  }
  
  
  // Used on the player profile page, used to point an image to the Chart Controller
  // which in turn generates the appropriate image depending on the parameters of
  // this method.
  function displayWinsByPositionChart(contextPath, playerId, seasonId) {
    
    var image = document.getElementById("winsByPositionChart");
    image.src = contextPath +
                "/servlet/chartController/winsByPosition?playerId=" +
                playerId +
                "&seasonId=" +
                seasonId;
    
    // We also want to hide the textual data that this chart displays.
    for (var ii = 1; ii <= 5; ++ii) {
    	var dataRow = document.getElementById("winsByPositionRow" + ii);
    	dataRow.style.display = "none";
    }
    return;
  }
  
  
    
  
  // Used on the player profile page, used to point an image to the Chart Controller
  // which in turn generates the appropriate image depending on the parameters of
  // this method.
  function displayGamesWonChart(contextPath, playerId, seasonId) {
    
    var image = document.getElementById("gamesWonChart");
    image.src = contextPath +
                "/servlet/chartController/gamesWon?playerId=" +
                playerId +
                "&seasonId=" +
                seasonId;
    
    // We also want to hide the textual data that this chart displays.
    for (var ii = 1; ii <= 5; ++ii) {
    	var dataRow = document.getElementById("gamesWonRow" + ii);
    	dataRow.style.display = "none";
    }
    return;
  }
  
  // Performs the work of actually launching the pdf window.
  function launchPDF() {
     document.getElementById('pdfOptionsDiv').style.display = 'none';
     
     var clubPlayersOnlyCheckBox = document.getElementById("clubPlayersOnly");
     var highlightClubPlayersCheckBox = document.getElementById("highlightClubPlayers");
     var clubIdComboBox = document.getElementById("clubId");
     
     if (clubIdComboBox.value != -1) {
         
     }
     
     // var location = "http://localhost:8080/squash/servlet/PdfServlet/index.html";
     // var windowName = "PDF";
     // var attributes = "status=1,toolbar=1";
     // window.open(location,windowName,attributes);
     return;
  }
  
  