/**
  * load file dependencies
  */

bam.loadSync(bam.homePath + "bam.datagrid.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);
    this.init();
};

// 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_promo_col : false,
    hide_empty_promo_col : true,
    tlink_img : "/mlb/images/buttons/green/bu_buyticketsnow.gif"        // small tlink: "/images/schedule/icon_ticket.gif"
};

/** 
  * shared methods
  */
bam.TixGrid.prototype = {
    // shared portion of the contructor
    init: function() {
        var that = this;
        this.grid = new bam.datagrid.DataGrid({
            showHeader: true,
            tableClass: this.cfg.table_class,
            noResultsMessage: this.cfg.empty_msg,
            columns: [
                {title:"Schedule ID", sortable: false, visible: false},
                {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 + "_standings_logo.gif' alt='" + team_name + "' title='" + team_name + "' />";
                    }
                    return html;
                 }},
                {title:"Date", type: bam.datagrid.DataType.DateTime, sortable: false, style: "game_date"},
                {title:"Time", sortable: false, style: "game_time"},
                {title:"Promotion", sortable: false, style: "promotion", visible: !that.cfg.hide_promo_col,
                 decorator: function(cell_obj) {
                     var schedule_id = that.grid.rows(cell_obj.row).cell(0).value;
                     var game = that.data[schedule_id];
//                     console.log(cell_obj.cell, schedule_id);                     
                     var out = "";
                     if(game.promotion) {
                         out = cell_obj.value;
                         if(game.promotion[0].image_url) {
                             out += " <img src='/images/icons/photo.gif' alt='Click to view photo' />";
                         }
                         $(cell_obj.cell).css("cursor", "pointer");
                     }
                     else {
                        out = that.cfg.empty_promo_html;
                     }
                     return out;
                 },
                 onCellClick: function(evt) {
                     var schedule_id = that.grid.rows(parseInt($(this).parent().attr("index"), 10)).cell(0).value;
                     var game = that.data[schedule_id];
                     if(game.promotion) {
                         var width = game.promotion[0].pop_up_width || 320
                         var height = game.promotion[0].pop_up_height || 300;
                         bam.promotion.getInfo(game, evt, width, height);
                     }
                 }},
                {title:" ", sortable: false, style: "tlink",
                 decorator: function(cell_obj) {
                    return cell_obj.value ? "<a href='" + cell_obj.value + "'><img src='" + that.cfg.tlink_img + "' alt='Buy Tickets' /></a>" : that.cfg.empty_tlink_html;
                 },
                 onCellClick: function(evt) {
                     $tlink = $("a", this);
                     if($tlink[0]) {
                         openTIXXWindow($tlink.attr("href"));
                         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;
                }
            };

            for(schedule_id in this.data) {
                if(data.hasOwnProperty(schedule_id)) {
                    var game = data[schedule_id];
                    var promo = {};
                    
                    var dt = bam.datetime.parseXMLDate(game.game_time_local);
                    dt.setTimeZone(-4, bam.datetime.isDST(dt));
                    game.game_datetime = dt;

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

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

                    switch(game[vs_at + "_sport_id"]) {
                        case "51":
                            game[vs_at + "_file_code"] = this.getFileCode("WBC", game[vs_at + "_team_id"]);
                            break;
                    }
                    
                    this.grid.insertRow([
                        schedule_id,                                                // back reference to the data set
                        game[vs_at + "_name_full"] + "|" + game[vs_at + "_file_code"] + "|" + game[vs_at + "_sport_id"],                          // club and team name
                        dt.formatDate("EEE, MMM d"),                                // ex: Fri, Jul 17
                        dt.formatDate("h:mm a"),                                    // ex: 7:05 pm
                        (promo.offer_name ? promo.offer_name : null),
                        (game.ticket_link ? game.ticket_link.tlink : null)
                    ]);

                    hide_promos = hide_promos && !promo.offer_name;
                }
            }
            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() {
        this.grid.refresh(this.cfg.table_id);
    }
};