var RacingForm = {

  DEFAULT_FORM_ROWS : 5,

  track : undefined,
  raceId : undefined,

  meetingId : undefined,
  meetingName : "",

  raceNo : undefined,
  raceName : "",
  
  init : function() {
    this.meetings = $("meetings");
    this.races = $("races");
    this.races.disabled = true;
    this.parseLocation();

    DWREngine.beginBatch();

    this.populateMeetings();
    
    if( this.meetingId != undefined ) {

      this.populateRaces();

      if( this.raceNo != undefined ) {
        this.populateRace( true );
      }
    }

    DWREngine.endBatch();

  },

  parseLocation : function() {
    var hash = window.location.hash;
    if (hash.length > 1) {
      this.raceId = hash.substr(1);
      //this.parseRaceId();
    }
  },

  parseRaceId : function() {
    if( this.raceId == undefined ) {
      this.meetingId = undefined;
      this.raceNo = undefined;
    } else {
      var parts = this.raceId.split(".");
      this.meetingId = parts[0];
      if( parts.length > 1 ) {
        this.raceNo = parts[1];
      }
    }
  },

  updateLocation : function() {
    //window.location.hash = this.raceId == undefined ? "" : "#" + this.raceId;
  },

  onMeetingChange : function() {
    this.reset();
    var index = this.meetings.selectedIndex;
    if (index > 0) {
      this.track = this.meetings.options[index].value;
      this.meetingName = this.meetings.options[index].text;
      this.populateRaces();
    } else {
      this.races.selectedIndex = 0;
      this.races.disabled = true;
    }

    this.updateLocation();
  },

  onRaceChange : function() {
    this.reset(true);
    var index = this.races.selectedIndex;
    if (index > 0) {
      this.raceId = this.races.options[index].value;
      this.parseRaceId();
      this.raceName = this.races.options[index].text;
      this.populateRace();      
    }
    this.updateLocation();
  },

  populateMeetings : function() {
    RemotedRacingForm.listMeetings(FunctionUtil.scopedPointer(this, "doPopulateMeetings"));
  },

  doPopulateMeetings : function(entities) {

    var options = this.meetings.options;
    options.length = 1;
    var option;
    for (var i = 0; i < entities.length; i++) {
      var id = entities[i].id;
      var name = entities[i].name;


      if( option != undefined && option.text == name ) {

        option.value = option.value+","+id

      } else {

        option =  new Option( name, id );
        options[options.length] = option;
        
      }

      if( id == this.meetingId ) {
        this.meetingName = name;
        option.selected = true;
      }
    }

    if( this.track == undefined ) {
      this.track = options[1].value;
      this.meetingName = options[1].text;
      options[1].selected = true;
    }

    this.populateRaces();    
  },

  populateRaces : function() {
    RemotedRacingForm.listRaces( this.track, FunctionUtil.scopedPointer(this, "doPopulateRaces"));
    this.races.disabled = false;
  },

  doPopulateRaces : function(entities) {
    var options = this.races.options;
    options.length = 1;
    for (var i = 0; i < entities.length; i++) {
      var id = entities[i].id;
      var name = entities[i].name;

      var option = new Option( name, id );
      if( id == this.raceNo ) {
        this.raceName = name;
        option.selected = true;
      }
      options[options.length] = option;
    }


    if( this.raceId == undefined ) {
      this.raceId = options[1].value;
      this.raceName = options[1].text;
      options[1].selected = true;
      this.populateRace();
    }

  },

  populateRace : function( batched ) {
    
    if( !batched ) DWREngine.beginBatch();

    this.parseRaceId();

    RemotedRacingForm.getRaceSummary( this.meetingId, this.raceNo, FunctionUtil.scopedPointer(this, "doPopulateRaceSummary"));
    RemotedRacingForm.listRaceTraps( this.meetingId, this.raceNo, FunctionUtil.scopedPointer(this, "doPopulateRaceTraps"));

    if( !batched ) DWREngine.endBatch();
  },

  doPopulateRaceSummary: function(summary) {
    for (var v in summary) {
      $("summary" + StringUtil.upperCaseFirstChar(v)).innerHTML = summary[v];
    }
  },

  trackRace: function(value) {
    var tracker = new Image(1,1);
    tracker.src = "/tracking/"+value.replace(/ /g,"+");
  },

  doPopulateRaceTraps: function(traps) {
    var name = this.meetingName + " - " + this.raceName;
    
    $("raceTitle").innerHTML = name;
    this.trackRace( name );

    var leftColumn = $("leftColumn");
    var rightColumn = $("rightColumn");

    HtmlUtil.clearChildren(leftColumn);
    HtmlUtil.clearChildren(rightColumn);

    var table = HtmlUtil.createElement("table", leftColumn);
    var tbody = HtmlUtil.createElement("tbody", table);

    var validRunners = 0;

    for (var i = 1; i < traps.length; i++) {

      if( validRunners == 3 ) {
        table = HtmlUtil.createElement("table", rightColumn );
        tbody = HtmlUtil.createElement("tbody", table);        
      }

      var runner = traps[i];

      if( runner != null ) {
        validRunners++;

        var tr = HtmlUtil.createElement("tr", tbody);
        var runnerHeader = HtmlUtil.createElement( "th", "header dog" + i, tr );
        runnerHeader.colSpan = 11;

        if( runner.vacant ) {
        
          HtmlUtil.createTextElement("h4", "vacant", runnerHeader, runner.name);
          
          // Output blank rows so adjacent traps line up
          for (var l = 0; l < this.DEFAULT_FORM_ROWS; l++) {
            tr = HtmlUtil.createElement("tr", l % 2 == 1 ? "even" : "odd", tbody);
            this.populateBlankRunnerForm( tr );
          }
        
        } else {

          HtmlUtil.createTextElement("h4", runnerHeader, runner.name);
          var trainer = HtmlUtil.createElement("div", "trainer", runnerHeader);        
          HtmlUtil.createTextElement("strong", trainer, "Trainer: ");
	        HtmlUtil.createTextElement("span", trainer, runner.trainer);
	        HtmlUtil.createTextElement("div", "breeding", runnerHeader, runner.breeding.formatted);
	
	        for (var l = 0; l < runner.form.length; l++) {
	          tr = HtmlUtil.createElement("tr", l % 2 == 1 ? "even" : "odd", tbody);
	          this.populateRunnerForm( tr, runner.form[l] );
	        }
	        
	      } 
	       
        tr = HtmlUtil.createElement("tr", tbody );
        var spacer = HtmlUtil.createElement( "td", "spacer", tr );
        spacer.colSpan = 11;
      }
    }
  },

  reset : function(race) {

    this.raceId = undefined;
    this.raceNo = undefined;
    this.raceName = "";

    if (race) return;

    this.meetingId = undefined;
    this.meetingName = "";
  },

  populateRunnerForm: function( tr, form ) {

    var show = FunctionUtil.scopedPointer( HelpTooltip, "show" );
    var hide = FunctionUtil.scopedPointer( HelpTooltip, "hide" );

    this.addFormCell(tr, "formattedDate", form.formattedDate, show, hide);
    this.addFormCell(tr, "distance", form.distance, show, hide);
    this.addFormCell(tr, "trapNo", form.trapNo, show, hide);
    this.addFormCell(tr, "sectionalTime", StringUtil.fixed( form.sectionalTime, 2 ), show, hide);
    this.addFormCell(tr, "bendPosition", form.bendPosition, show, hide);
    this.addFormCell(tr, "position", StringUtil.formatPos(form.position), show, hide);
    this.addFormCell(tr, "comment", form.comment, show, hide);
    this.addFormCell(tr, "winningTime", StringUtil.fixed( form.winningTime, 2 ), show, hide);
    this.addFormCell(tr, "goingAllowance",
      form.goingAllowance == 0 ? "" : StringUtil.signValue(form.goingAllowance), show, hide);
    this.addFormCell(tr, "racingClass", form.racingClass, show, hide);
    this.addFormCell(tr, "adjustedTime", StringUtil.fixed( form.adjustedTime, 2 ), show, hide);

  },
  
  populateBlankRunnerForm: function( tr ) {

    // Used for vacant traps

    for( var i = 1; i <= 11; i++ ) {

      var nbsp = document.createTextNode( "\u00A0" );
      var td = document.createElement( "td" );
      td.appendChild( nbsp );
      tr.appendChild( td );

    }

  },

  addFormCell: function( tr, clazz, value, show, hide) {
    var td = HtmlUtil.createTextElement("td", clazz, tr, value );
    td.onmouseover = show;
    td.onmouseout = hide;
  },

  beginRequest: function() {

  }

};
