/**
  * load file dependencies
  */

bam.loadSync(bam.homePath + "bam.datagrid2.js");
bam.loadSync(bam.homePath + "bam.datetime.js");
bam.loadSync("/scripts/bam.promotion.js");


/**
  * contructor
  */
bam.TixGrid = function(team_id, cfg) {
  this.team_id = team_id;
  this.cfg = $.extend({}, bam.TixGrid.cfg, cfg);
  if(!cfg.cols) {
    throw new Error("missing 'cols' attribute from configuration");
  }
  this.init(cfg.cols);
};

// static storage for team lookup data, if necessary
bam.TixGrid.team_data = {};

/**
  * static variables
  */
// base configurations
bam.TixGrid.cfg = {
  table_id : "ticket_grid",
  table_class : "data_grid",
  empty_msg : "There are no tickets to display",
  empty_promo_html : "<em class='no_promo'>No promotions</em>",
  empty_tlink_html : "",
  hide_empty_promo_col : true,
  tlink_img : "",    // small tlink: "/images/schedule/icon_ticket.gif"
  tlink_text : ""
};

/** 
  * shared methods
  */
bam.TixGrid.prototype = {
  /*
   * Column definition objects
   *   @function value 
   *     @param game
   *     @returns columnValue
   *   @hash definition : used to define the column in datagrid
   */
  cols: {
    opponent_logo: {
      value: function(game) {
        return game[game.vs_at + "_name_full"] + "|" + game[game.vs_at + "_file_code"] + "|" + game[game.vs_at + "_sport_id"];
      },
      definition: {
        title:"Opponent", 
        sortable: false, 
        style: "opponent",
        decorator: function(cell_obj) {
          var parts = cell_obj.value.split("|");
          var team_name = parts[0];
          var club = parts[1];
          var sport_id = parts[2];

          var html = "";
          switch(sport_id) {
            case "51":
              html = "<img src='/wbc/2009/images/flags/34x21/" + club + ".jpg' alt='" + team_name + "' title='" + team_name + "' style='padding: 0 8.5px' />";
              break;
            default:
              html = "<img src='/mlb/images/team_logos/51x21/" + club + ".gif' alt='" + team_name + "' title='" + team_name + "' />";
          }
          return html;
        }
      }
    },
    
    opponent_name: {
      value: function(game) {
        return game[game.vs_at + "_name_full"];
      },
      definition: {
        title:"Opponent", 
        sortable: false, 
        style: "opponent_name"
      }
    },

    date: {
      value: function(game) {
        return game.game_datetime;                // ex: Fri, Jul 17
      },
      definition: {
        title:"Date", 
        type: bam.datagrid.DataType.DateTime, 
        sortable: false, 
        style: "game_date",
        dateFormat:"EEE, MMM d"
      }
    },

    time: {
      value: function(game) {
        return game.TBD || game.game_datetime.formatDate("h:mm a");       // ex: 7:05 pm
      },
      definition: {
        title:"Time", 
        sortable: false, 
        style: "game_time"
      }
    },

    promotions: {
      value: function(game) {
        return null;
      },
      definition: {
        title:"Promotion", 
        sortable: false, 
        style: "promotion", 
        decorator: function(cell_obj) {
          var that = this.parent._instance;
          var schedule_id = that.grid.rows(cell_obj.row).cell(0).value;
          var game = that.data[schedule_id];
          
          var out = [];

          if(game.promotion) {
            for (var i = 0, n = game.promotion.length; i < n; i++) {
             var promo = game.promotion[i];
             out.push("<a href='" + (promo.alt_page_url || '#') + "' rel='" + i + "'>" + 
               promo.offer_name + 
               (promo.image_url ? '<img src="/images/icons/photo.gif" />' : '') +
               "</a>");
            }
          }
          else {
            out = [ that.cfg.empty_promo_html ];
          }
          return out.join(", ");
        }
      }
    },

    tlink: {
      value: function(game) {
        return game.ticket_link ? game.ticket_link.tlink : null;
      },
      definition: {
        title:" ", 
        sortable: false, 
        style: "tlink",
        decorator: function(cell_obj) {
          var that = this.parent._instance;
          var out = "";
          if(cell_obj.value) {
            out = "<a href='" + cell_obj.value + "'>";
            if(!!that.cfg.tlink_img) {
              out += "<img src='" + that.cfg.tlink_img + "' alt='" + (that.cfg.tlink_text ? that.cfg.tlink_text : 'Buy Tickets') + "' /></a>";
            }
            else {
              out += (that.cfg.tlink_text ? that.cfg.tlink_text : 'Buy Tickets &rsaquo;') + "</a>";
              out = "<span class='button purchase'>" + out + "</span>";
            }
          }
          else {
            out = that.cfg.empty_tlink_html;
          }
          return out; 
        },
        onCellClick: function(evt) {
          $tlink = $("a", this);
          if($tlink[0]) {
            openTIXXWindow($tlink.attr("href"));
            return false;
          }
        }
      }
    },
    
    timezone: {
      value: function(game) {
        return game.time_zone_local;
      },
      definition: {
        title:" ", 
        sortable: false, 
        style: "timezone",
        visible: true
      }
    },
    
    venue: {
      value: function(game) {
        return game.venue_name;
      },
      definition: {
        title:"Venue", 
        sortable: false, 
        style: "venue"
      }
    }
  },
  init: function(colnames) {
    var that = this;
    var columns = [
      {title:"Schedule ID", sortable: false, visible: false}
    ];
    
    for(var i = 0, n = colnames.length; i < n; i++) {
      if(typeof that.cols[ colnames[i] ] !== "undefined") {
        columns.push(this.cols[ colnames[i] ].definition);
      }
    }
    
		this.grid = new bam.datagrid.DataGrid({
      showHeader: true,
      tableClass: this.cfg.table_class,
      noResultsMessage: this.cfg.empty_msg,
      columns: columns
    });
    
    this.grid._instance = this;

    $("td.promotion a").live("click", function(evt) {
      $this = $(this);
      var schedule_id = that.grid.rows(parseInt($this.parent().parent().attr("index"), 10)).cell(0).value;
      var game = that.data[schedule_id];
      var promo = game.promotion[$this.attr("rel")];
      if(promo.alt_page_url) {
        bam.promotion.openPromoWindow(promo.alt_page_url, promo.width, promo.height);        
      }
      else {
        bam.promotion.getInfo(game, evt, promo.width, promo.height);
        return false;
      }
    });

    
  },
  getFileCode: function(type, team_id) {
    var file_code = null;
    switch(type) {
      case "WBC":
        if(!bam.TixGrid.team_data.WBC) {
          $.ajax({
            type:"GET", 
            async:false, 
            cache:true, 
            url:'/scripts/wbc_club_properties.jsp?hashKey=team_id&p=team_id&p=team_code&alias=team_code:club&responseType=JSON', 
            dataType:"json",
            success: function(data) {
              bam.TixGrid.team_data.WBC = data;
            }
          });
        }
        file_code = bam.TixGrid.team_data.WBC[team_id].club;
        break;
    }
    return file_code;
  },
  // populate the grid instance with data
  populate: function(data) {
    this.data = data;

    this.grid.clearData();

    if(this.data) {
      var hide_promos = true;

      // promotion sorter for multiple promotions
      __promoSort = function(a, b) {
        a = parseInt(a, 10) || 99;        // ensure that a falsy value is not less than a real sort_key
        b = parseInt(b, 10) || 99;        // ensure that a falsy value is not less than a real sort_key
        if (a.sort_key === b.sort_key) {
          return 0;
        }
        else if (a.sort_key < b.sort_key) {
          return -1;
        }
        else {
          return 1;
        }
      };

      var row_num = 0;
      for(schedule_id in this.data) {
        if(data.hasOwnProperty(schedule_id)) {
          var game = data[schedule_id];
//          var promos_html = [];
          
          var dt = game.game_time_local_str;
//          dt.setTimeZone(-4, bam.datetime.isDST(dt));
          game.game_datetime = dt;

          var vs_at = (this.team_id == game.home_team_id ? "away" : "home");
          game.vs_at = vs_at;

          if(game.promotion) {
            if(game.promotion instanceof Array) {
               game.promotion.sort(__promoSort);
            }
            else {
              game.promotion = [ game.promotion ];
            }
          }

          switch(game[vs_at + "_sport_id"]) {
            case "51":
              game[vs_at + "_file_code"] = this.getFileCode("WBC", game[vs_at + "_team_id"]);
              break;
          }
          
          var row = [ schedule_id ];
          for(var i = 0, n = this.cfg.cols.length; i < n; i++) {
            if(typeof this.cols[ this.cfg.cols[i] ] !== "undefined") {
              row.push(this.cols[ this.cfg.cols[i] ].value(game));
            }
          }
          
          this.grid.insertRow(row);
          this.grid.rows(row_num++).game = game;

          hide_promos = hide_promos && !game.promotion;
        }
      }
//      if(this.cfg.hide_empty_promo_col && hide_promos) {
//        this.grid.columns(4).visible = false;
//      }
    }
    this.render();

    $("." + this.cfg.table_class + " thead tr", "#" + this.cfg.table_id).addClass("hdrTopBg");
  },
  render: function() {
		var cols = this.grid.columns();
    for(var i = 0, n = cols.length; i < n; i++) {
      if("Date" === cols[i].title) {
        break;
      }
    }
		
		if(i < n) {   // make sure that i is in bound
      this.grid.sortColumn(i);
		}
    this.grid.refresh(this.cfg.table_id);
  }
};
