;(function (window, document, $, bam) {
  
  
  /**
   * ScheduleSeries
   * If called without the new keyword, use a singleton instance.
   */
  var reAwayHome = /^(away|home)_(.*)$/,
      reGameTime = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}:\d{2}:\d{2})$/,
      instance;

  function makeJavaScriptUrl (code) {
    return 'javascript:void(' + escape(code) + ');';
  }
        
  function WorldSeriesSchedule () {
    if (!(this instanceof WorldSeriesSchedule)) {
      if (!instance) {
        instance = new WorldSeriesSchedule();
      }
      return instance;
    }
  }
    
  // Add $.loadable behavior to ScheduleSeries
  $.loadable(WorldSeriesSchedule, {
    dataType: 'text',
    url:      '/lookup/json/named.schedule_series.bam',
    cache:    !bam.env.host.isDev, // bust cache on dev
    data: {
      // season:     2010,
      sport_code: '\'mlb\'',
      game_type:  '\'W\''
    },
    dataFilter: function (json) {

      var data  = $.parseJSON(json) || {},
          games = $.ensureArray($.deep(data, 'schedule_series.queryResults.row'));

      return $.map(games, function (game) {

        var prop, match;
        
        // Convert to a usable JavaScript date string
        game.date = game.game_time_et.replace(reGameTime, '$2/$3/$1 $4');
        
        // Convenience lookup for teams
        game.away = {};
        game.home = {};
        
        for (prop in game) {
          match = reAwayHome.exec(prop);
          if (match) {
            game[match[1]][match[2]] = game[prop];
            // delete game[prop];
          }
        }        

        // Determine winning/losing teams
        // var runsAway = game.away.score,
        //     runsHome = game.home.score;
        // 
        // if (runsAway > runsHome) {
        //   game.winning_team = game.away;
        //   game.losing_team  = game.home;
        // } else if (runsHome > runsAway) {
        //   game.winning_team = game.home;
        //   game.losing_team  = game.away;
        // }
        
        // Create game links from available data
        game.links = {
          boxscore: makeJavaScriptUrl('launchGameday({gid:"' + game.gd_game_id + '",mode:"box"})'),
          wrap: makeJavaScriptUrl('launchGameday({gid:"' + game.gd_game_id + '",mode:"wrap"})')
        };
        
        return game;
      });
    }
  });
  
  
  WorldSeriesSchedule.prototype.load = (function (load) {
    return function (season) {      
      return load.call(this, { data: { season: season } });
    };
  })(WorldSeriesSchedule.prototype.load);
  
  
  // Add ScheduleSeries to bam.services namespace
  bam.namespace('services').WorldSeriesSchedule = WorldSeriesSchedule;

})(this, this.document, this.jQuery, this.bam);

