// Tournament.js - tournament view javascript functions.
// 
// Copyright (c) Betfair 2007. All rights reserved.

// requires jQuery 1.1.2

var Tournament = {
  FadeSpeed: 500,
  
  initialize: function(initialRound) {
    Tournament.Rounds = $("div#tournament table.round");
    Tournament.showRound(initialRound || 0);
  },
  
  applyClasses: function(rounds) {
    $(rounds).removeClass("match_left").removeClass("match_right");
    
    $(rounds[0]).addClass("match_left");
    $(rounds[1]).addClass("match_right");
  },
  
  showNavigation: function(rounds) {
    $(rounds).find("a.previous_round, a.next_round").hide();
    $(rounds[0]).find("a.previous_round").show();
    $(rounds[1]).find("a.next_round").show();
  },
  
  nextRound: function() {
    var rounds        = Tournament.Rounds,
        visibleRounds = rounds.filter(":visible"),
        nextRoundIndex, nextRound, newRounds;
    
    nextRoundIndex = rounds.index(visibleRounds[1]) + 1;
    nextRound = rounds[nextRoundIndex];
    
    if (nextRound) {
      newRounds = [rounds[nextRoundIndex - 1], nextRound];
      Tournament.applyClasses( newRounds );
      Tournament.showNavigation( newRounds );
      visibleRounds.lt(1).hide();
      $(nextRound).show();

      recordStat('TTNNE');
    }
  },
  
  previousRound: function() {
    var rounds        = Tournament.Rounds,
        visibleRounds = rounds.filter(":visible"),
        prevRoundIndex, prevRound, newRounds;
    
    prevRoundIndex = rounds.index(visibleRounds[0]) - 1;
    if (prevRoundIndex >= 0) { prevRound = rounds[prevRoundIndex]; }
    
    if (prevRound) {
      newRounds = [prevRound, rounds[prevRoundIndex + 1]];
      Tournament.applyClasses( newRounds );
      Tournament.showNavigation( newRounds );
      visibleRounds.gt(0).hide();
      $(prevRound).show();

      recordStat('TTNPR');
    }
  },
  
  showRound : function(index) {
    var rounds = Tournament.Rounds,
        adjacentRound, visibleRounds;
    
    if (rounds[index]) {
      adjacentRound = rounds[index+1] || rounds[index-1];
      
      rounds.hide();
      $([rounds[index], adjacentRound]).show();
      
      visibleRounds = rounds.filter(":visible");
      Tournament.applyClasses( visibleRounds );
      Tournament.showNavigation( visibleRounds );
    }
  },
  
  timestamp: null,
  
  update: function(tnmtCompId, initialTimestamp) {
    setInterval(function() {
      $.getJSON(
        Config.AS_URL,
        {"action": "tnmt_update", "tnmt_comp_id": tnmtCompId, "after": Tournament.timestamp || initialTimestamp},
        function(json) {
          
          $(json.matches).each(function() {
            var match = this,
                matchTable = document.getElementById("tmatch_" + this.match_id);
            
            if (matchTable) { Tennis.matches.updateScores($(matchTable), match); }
          });
          
          $(json.markets).each(function() {
            var market = this;
            
            $(market.runners).each(function() {
              Tennis.matches.updatePrices(this, "tournament")
            });
          });
          
          // Update the timestamp:
          Tournament.timestamp = json.after;
        }
      );
    }, 30 * 1000);
  }
};

function recordStat(origin, mkt_id, seln_id) {
	var params = {
		'type'    : 'POST',
		'url'     : '/tennis',
		'dataType': 'json',
		'data'    : { 'action': 'record_stat', 'origin': origin }
	};

	if (mkt_id)  { params.data.mkt_id = mkt_id; }

	if (seln_id) { params.data.seln_id = seln_id; }

	$.ajax(params);
}

function fmt(msg, params) {
	if (params == null) { params = []; }
	
	for (var i = 0; i < params.length; i++)
		if (params[i]) {
			msg = msg.replace('%s', params[i], '');
		} else {
			msg = msg.replace('%s', '', '');
		}
	
	return msg;
}

function bf_link(origin, mkt_id, exch_id, seln_id) {
	var url = fmt("http://%s/Index.do?mi=%s&ex=%s&rfr=3925&suid=3925&bspi=3925",
	          [Config.BF_URL, mkt_id, exch_id]);

	recordStat(origin, mkt_id, seln_id);

	window.open(url, '_blank');
}
