var BetfairScorecard = {
  Config: {
    scoreUrl: "/betfair/update_scorecard",
    scoreRefresh: 20,
    pricesUrl: "/betfair_prices/update",
    pricesRefresh: 30
  },

  Templates:  {},
  MarketId:   null,
  ExchangeId: null,
  InningId:   null,

  initialize: function(inningId) {
    this.InningId = inningId;

    this.parseTemplates();
    this.addPriceEventHandlers();
    this.enablePriceUpdates();
    this.enableScoreUpdates();
  },

  addPriceEventHandlers: function() {
    var select = $("select#betfair_market_select");

    select.change(function() {
      var values = this.value.split("~"),
          marketId, exchangeId;

      BetfairScorecard.currentMarketId   = values[0];
      BetfairScorecard.currentExchangeId = values[1];

      BetfairScorecard.updatePricesRequest();
    });

    select.change();
  },

  enableScoreUpdates: function() {
    setInterval(BetfairScorecard.scoreCallback, BetfairScorecard.Config.scoreRefresh * 1000);
  },

  scoreCallback: function(url) {
    var url = BetfairScorecard.Config.scoreUrl + "/" +
              BetfairScorecard.InningId + ".js?" + Math.random();

    $.ajax({ type: "GET", url: url, dataType: "script",
             success: BetfairScorecard.googleAnalytics("/betfair/" + BetfairScorecard.InningId) });
  },

  enablePriceUpdates: function() {
    setInterval(BetfairScorecard.updatePricesRequest, BetfairScorecard.Config.pricesRefresh * 1000);
  },

  updatePricesRequest: function() {
    $.getJSON(
      BetfairScorecard.Config.pricesUrl,
      {market_id: BetfairScorecard.currentMarketId, exchange_id: BetfairScorecard.currentExchangeId},
      BetfairScorecard.pricesCallback
    );
  },

  pricesCallback: function(json) {
    BetfairScorecard.renderTemplate("prices_template", "div#market_prices_container", "market", json);
  },

  parseTemplates: function() {
    var templateObj;

    $("div#templates textarea").each(function() {
      templateObj = TrimPath.parseDOMTemplate(this.id);
      BetfairScorecard.Templates[this.id] = templateObj;
    });
  },

  renderTemplate: function(templateName, targetElement, contextName, json) {
    var context = {},
        renderedTemplate;

    context[contextName] = json;
    renderedTemplate     = BetfairScorecard.Templates[templateName].process(context);
    $(targetElement).empty().append(renderedTemplate);
  },

  togglePlayerMarkets: function(id, scope) {
    BetfairScorecard.toggleFunction(id, scope, "player_markets");
  },

  togglePlayerBattingStats: function(id, scope) {
    BetfairScorecard.toggleFunction(id, scope, "player_batting_stats");
  },

  togglePlayerBowlingStats: function(id, scope) {
    BetfairScorecard.toggleFunction(id, scope, "player_bowling_stats");
  },

  toggleFunction: function(id, scope, type) {
    var div = $("div#" + scope + "_" + type + "_" + id);

    if (div.is(":visible")) {
      div.fadeOut(200);
    } else {
      $("div.player_markets, div.player_stats").hide();
      div.fadeIn(200);
    }
  },

  betfairMarketLink: function(marketId, exchangeId) {
    var url = "http://www.betfair.com/?sid=152&mi=" + marketId + "&ex=" +
              (exchangeId || 1) + "&rfr=2534";

    window.open(url);
  },

  googleAnalytics: function(location) {
    if (urchinTracker) { urchinTracker(location); }
  }
};

// Open the given URL in a new window.
function linkToMainWindow(url) {
  var w = window.open(url);
  w.focus();
}
