// new schedule object that can be initialized with an array of
// 'round' objects, describing the number of series in that round and
// the number of games for the series.
//
// ex. var schedule = new Schedule ( [ {series: 2, games: 3}, {series: 1, games: 5} ] );
//     Two rounds, two series in the first round, 3 game series.
//     one final series, 5 games.
//

function getParams() {

    var params = {};
    var query  = location.search.substring(1);
    var pairs  = query.split(",");

    for(var i=0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');
        if (pos == -1) { continue; }
        var paramName = pairs[i].substring(0,pos);
        var value     = pairs[i].substring(pos+1);
        params[paramName] = unescape(value);
    }

    return params;
}

function Schedule(scheduleFormat) {
    this.rounds = new Array(scheduleFormat.length);

    for (x=0; x<scheduleFormat.length; x++) {
        this.rounds[x] = { series: new Array(scheduleFormat[x].series) };
        for (y=0; y<scheduleFormat[x].series; y++) {
            this.rounds[x].series[y] = { games: new Array(scheduleFormat[x].games) };
            for (z=0; z<scheduleFormat[x].games; z++) {
                this.rounds[x].series[y].games[z] = new Object();
            }
        }
    }
}

// allows for the creation of more detailed game objects in the
// tbdschedules
function Game(gameInfo) {
    if (gameInfo[0] != "nogame") {
        this.id              = gameInfo[0];
        this.status          = gameInfo[1];
        this.teams = [{}, {}];
        this.teams[0].id     = gameInfo[2];
        this.teams[0].score  = gameInfo[3];
        this.teams[1].id     = gameInfo[4];
        this.teams[1].score  = gameInfo[5];
    } else {
        this.id = "nogame";
        this.status = "F";
    }
}

// the generated schedule only generates games if they were played.
// This goes back thru the schedule object and creates "nogame"
// objects for any missing games, or an empty series object if necessary.
function fillScheduleHoles(schedule, scheduleFormat) {
    for (x=0; x<scheduleFormat.length; x++) {
        for (y=0; y<scheduleFormat[x].series; y++) {

            // if the database gets games for one series, but not
            // another, we have a hole.  Need to fill that one too.
            var seriesMade = false;
            if (!schedule.rounds[x].series[y]) {
                schedule.rounds[x].series[y] = { matchup: "TBD vs TBD", games: [] };
                seriesMade = true;
            }

            for (z=0; z<scheduleFormat[x].games; z++) {

                // if the database is missing a game, we fill it.  if
                // the series is missing, we make empty games, if the
                // series existed, we create the games as 'unplayed'
                if (!schedule.rounds[x].series[y].games[z]) {
                    if (seriesMade) {
                        schedule.rounds[x].series[y].games[z] = new Game(["", "S", "t23", "", "t23", ""]);
                    } else {
                        schedule.rounds[x].series[y].games[z] = new Game(["nogame"]);
                    }
                }
            }
        }
    }
    return schedule;
}

// writes out the schedule as a series of rounds
function writeSchedule(schedule) {
    if (schedule) {
        for (var i=0; i<schedule.rounds.length; i++) {
           document.write( createRound(schedule.rounds[i], i+1) );
        }
    }
}

// writes out the most first series thats current
function writeSingleSchedule(schedule) {
    if (schedule) {
        var html = "";
        var params = getParams();
        var leagueId = params.did.substring(1,4);

        // find current round, draw first series
        var current = findCurrentSeries(schedule);

        // if we have more than one series in this round, and a DOM
        // browser write out a select control to choose the others, if
        // no, draw the logos for the teams playing this series.

        if ((schedule.rounds[current.round].series.length > 1) && (document.getElementById)) {
            html += createSeriesSelect(schedule.rounds[current.round]);
        } 

        // now draw the schedule header image and the schedule 

        html += "<a href=\"/milb/events/playoffs/y2008/schedule.jsp?did=l" + leagueId + "\" title=\"View Full Schedule\">";
        html += "<img src=\"/milb/images/events/playoffs/y2008/headers/l" + leagueId + "_schedule.gif\" alt=\"Schedule\" border=\"0\" alt=\"View Full Schedule\" />";
        html += "</a>";

        if ((schedule.rounds[current.round].series.length <= 1) || !(document.getElementById)) {
            var game = schedule.rounds[current.round].series[current.series].games[0];
            if (game.teams && game.teams[0].id) {
                html += "<img src=\"/milb/images/events/playoffs/y2008/teamlogos/" + game.teams[0].id + "_schedlogo0.gif\" class=\"teamlogo\" style=\"margin-left: 50px;\" />";
            } else {
                html += "<img src=\"/milb/images/events/playoffs/y2008/teamlogos/l" + leagueId + "_schedlogo.gif\" class=\"teamlogo\" style=\"margin-left: 50px;\" />";
            } 
            if (game.teams && game.teams[1].id) {
                html += "<img src=\"/milb/images/events/playoffs/y2008/teamlogos/" + game.teams[1].id + "_schedlogo0.gif\" class=\"teamlogo\" style=\"margin-left: 10px;\" />";
            } else {
                html += "<img src=\"/milb/images/events/playoffs/y2008/teamlogos/l" + leagueId + "_schedlogo.gif\" class=\"teamlogo\" style=\"margin-left: 10px;\" />";
            } 
        }

        html += "<span id=\"singleSchedule\" style=\"color:#ffffff;\">";
        html += createSeries(schedule.rounds[current.round].series[current.series]);
        html += "</span>";
        document.write(html);
    }
}

// creates html for a select control dropdown to pick the series in
// the round requested
function createSeriesSelect(round) {
    var html = "";
    html += "<select style=\"float: right; width: 170px; color:#ffffff;\" onchange=\"selectSeries(this.selectedIndex);\">";
    for (var i=0; i<round.series.length; i++) {

        // matchups are long, shorten them for the select control
        var text = getMatchup(round.series[i]);
        text = text.replace(/1st\&nbsp\;Half/g, "1H");
        text = text.replace(/2nd\&nbsp\;Half/g, "2H");
        text = text.replace(/Wild\&nbsp;Card/g, "WC");
        text = text.replace(/Division/g, "");
        text = text.replace(/Winner/g, "");
        text = text.replace(/Champion/g, "");
        text = text.replace(/\&nbsp\;\&nbsp\;/g, "&nbsp;");

        html += "<option name=\"\" value=\"" + i + "\">";
        html += text;
        html += "</option>";
    }
    html += "</select>\n";
    return html;
}

// event handler for the select dropdown to display a different single schedule
function selectSeries(seriesNum) {
    if (document.getElementById) {
        var current = findCurrentSeries(schedule); // really should get schedule a better way than a global var
        var objContainer = document.getElementById("singleSchedule");
        objContainer.innerHTML = createSeries(schedule.rounds[current.round].series[seriesNum]);
    }
}

// utility function to find the most 'current' series, given a full schedule
function findCurrentSeries(schedule) {
    // loop thru looking for scheduled, but unfinished games
    for (var i=0; i<schedule.rounds.length; i++) {
        for (var k=0; k<schedule.rounds[i].series.length; k++) {
            for (var l=0; l<schedule.rounds[i].series[k].games.length; l++) {
                if (schedule.rounds[i].series[k].games[l].status != "F") { // final.  Does this account for other states?
                    return {round: i, series: k};
                }
            }
        }
    }

    return { round: (i-1), series: (k-1) };
}

// creates the html for each round in playoff schedule
function createRound(round, roundNum) {
    var html = "<div class=\"round\">";
    var params = getParams();
    var leagueId = params.did.substring(1,4);

    html += "<img src=\"/milb/images/events/playoffs/y2008/headers/l" + leagueId + "_round" + roundNum + ".gif\" />"; 

    // write images, insert defaults for unknown teams
    for (var i=0; i<round.series.length; i++) {

        html += "<span class=\"serieslogo\"";
        html += ">";

        if (round.series[i].games[0].teams) {
            if (round.series[i].games[0].teams[0].id) {
                html += "<img src=\"/milb/images/events/playoffs/y2008/teamlogos/";
                html += round.series[i].games[0].teams[0].id;
                html += "_schedlogo" + roundNum + ".gif\" class=\"teamlogo\"";
                html += "/>";
            }
            if (round.series[i].games[0].teams[1].id) {
                html += "<img src=\"/milb/images/events/playoffs/y2008/teamlogos/";
                html += round.series[i].games[0].teams[1].id;
                html += "_schedlogo" + roundNum + ".gif\" class=\"teamlogo\"/>";
            }
        } else {
            html += "<img src=\"/milb/images/events/playoffs/y2008/teamlogos/l" + leagueId;
            html += "_schedlogo.gif\" class=\"teamlogo\"";
            html += "/>";
            html += "<img src=\"/milb/images/events/playoffs/y2008/teamlogos/l" + leagueId;
            html += "_schedlogo.gif\" class=\"teamlogo\" />";
        }

        html += "</span>";
    }

    // write series tables
    html += "<table class=\"series\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
    for (var i=0; i<round.series.length; i++) {
        html += "<td><span style=\"color:#ffffff;\">";
        html += createSeries(round.series[i]);
        html += "</span></td>";
        if (i % 2) {
            html += "</tr><tr>";
        }
    }
    html += "</tr></table>";

    // write footer
    html += "<div class=\"summary\">" + round.summary + "&nbsp;</div>"; 

    html += "</div>\n";
    return html;
}

// creates the html for each series in playoff schedule
function createSeries(series) {
    var html = "";
    // write header row

    html += "<div class=\"matchup\">" + getMatchup(series) + "</div>";

    // write game rows
    html += "<table cellspacing=\"0\">";
    for(var i=0; i<series.games.length; i++) {
        html += createGame(series.games[i], i+1, series);
    }

    html += "</table>";
    return html;
}

// creates the 'matchup' text (team a vs team b) used at the top of each series
function getMatchup(series) {
    var text = "";

    // NOTE: need to deal with t23 - TBD
    //
    // unfortunatley we dont have a TBD team in the
    // general.properties, so we use this magic number for now.

    properties.clubs["t22"] = { display_name: "TBD" };
    properties.clubs["t23"] = { display_name: "TBD" };
    properties.clubs["t34"] = { display_name: "TBD" };

    try {
        text = properties.clubs[series.games[0].teams[0].id].display_name + " vs. " + properties.clubs[series.games[0].teams[1].id].display_name;
    } catch(e) {
        if (series.matchup) {
            text = series.matchup;
            text = text.replace(/ /g, "&nbsp;");
            text = text.replace(/\&nbsp\;vs\&nbsp\;/g, " vs ");
        }
    }
    return text;
}

function createTeamName(team) {
    var html = "";
    if (team.abbr != "TBD") {
        html += "<a href=\"/clubs/index.jsp?cid=" + team.id + "\">" + team.abbr + "</a>";
    } else {
        html += team.abbr;
    }
    return html;
}

// creates the html for each game in playoff schedule
// this should probably be broken up into smaller parts
function createGame(game, gameNum, series) {
    var html = "<tr class=\"game\">";
    try {
        // if we have schedule info, the game was played and we have team info
        if ((game.id) && (game.id != "nogame") && (game.teams)) { 
                    
            try {
                game.teams[0].abbr = teams[game.teams[0].id].abbr;
                game.teams[1].abbr = teams[game.teams[1].id].abbr;
            } catch (e) {
                game.teams[0].abbr = properties.clubs[game.teams[0].id].name;
                game.teams[1].abbr = properties.clubs[game.teams[1].id].name;
            }

            var homeTeam = (game.teams[0].ishome)?game.teams[0]:game.teams[1];
            var awayTeam = (game.teams[0].ishome)?game.teams[1]:game.teams[0];

            // show score and possible gameday/log/box/wrap links
            // for inprogress or finished games

            if ((game.status == "F") || (game.status == "O") || (game.status == "I")) { // scheduled

                if (homeTeam.score) { homeTeam.score = parseInt(homeTeam.score); }
                if (awayTeam.score) { awayTeam.score = parseInt(awayTeam.score); }

                html += "<td width=\"10%\" nowrap>";
                html += "Game " + gameNum + ": ";
                html += "<span class=\"teamnames\">";
                if (homeTeam.score > awayTeam.score) {
                    html += createTeamName(homeTeam) + " " + homeTeam.score + ", ";
                    html += createTeamName(awayTeam) + " " + awayTeam.score + " ";
                } else {
                    html += createTeamName(awayTeam) + " " + awayTeam.score + ", ";
                    html += createTeamName(homeTeam) + " " + homeTeam.score + " ";
                }
                html += "</span></td><td nowrap style=\"text-align: right; padding-right: 10px;\" class=\"gamelink\">";

                html += " <a href=\"/milb/stats/stats.jsp?sid=milb&t=g_log&gid=" + game.id + "\">Recap</a> ";
                if ((game.status == "F") || (game.status == "O")) { // final or over
                    html += " | <a href=\"/milb/stats/stats.jsp?sid=milb&t=g_box&gid=" + game.id + "\">Box</a>";

			  // GAME STORY LOGIC UPDATED 2008
			  // (and then disabled completely)

                    if (game.wrap) { 
//                        html += " | <a href=\"/milb/stats/stats.jsp?sid=milb&t=g_wra&gid=" + game.id + "\">Game Story</a> ";
                    }
                    else {
				if ((game.homeGameStoryLink !== null) || (game.awayGameStoryLink !== null)) {
//					html += "Game Story: ";
				}
				if (game.homeGameStoryLink !== null) { 
//					html += " | <a href=\"" + game.homeGameStoryLink + "\">" + createTeamName(homeTeam) + "</a> | ";
				}
				if (game.awayGameStoryLink !== null) { 
//					html += " | <a href=\"" + game.awayGameStoryLink + "\">" + createTeamName(awayTeam) + "</a>";
				}
                    }
                }

                // onclick="launchMILBGameday('2006_08_29_oakmlb_balmlb_1')"
                // launchMILBGameday is in global.js
                if (game.gameday) {
                    html += " | <a href=\"javascript:launchGameday('" + game.id + "')\"><img src=\"/images/scoreboard/icon_gameday.gif\" alt=\"Launch Gameday\" border=\"0\" height=\"12\" width=\"15\" style=\"margin-left:2px;\" align=\"absmiddle\"></a> ";
                }

                html += "</td>";
            
            // for upcoming games show team @ team info, with possible (ifnecessary)
    
            } else {

                html += "<td colspan=\"2\">Game " + gameNum + ": ";

                if (game.date) {
                    html +=  game.date + " ";
                } else {
                    html +=  "TBD ";
                }

                // game 2 of double headers have magic 3:33am time
                if (game.time == "03:33AM") { game.time = "TBD" }

                if (game.time) {
                    html += game.time + " ";
                } else {
                    html += "TBD ";
                }
                html += "<span class=\"teamnames\">";
                html += createTeamName(awayTeam) + " ";
                html += "@ ";
                html += createTeamName(homeTeam) + " ";
                html += "</span>";

                if (game.ifnecessary) {
                    html += " (If Necessary) ";
                }
                html += "</td>";
                
            }

        // if its a special "nogame" - a game that wasn't played
        // because the series finished in less than the max games,
        // write out text for that
            
        } else if (game.id == "nogame") {
            html += "<td colspan=\"2\">Game " + gameNum  + ": No Game</td>";

        // otherwise, get the TBD info from the editor maintained
        // files in tbdschedules/l###_tbschedule.js

        } else {
            html += "<td colspan=\"2\">Game " + gameNum  + ": " + game.tbd[0] + " " +  game.tbd[1] + "</td>";
        }

    // just in case, to make sure we get all the necessary table cells

    } catch (e) {
        html += "<td colspan=\"2\">&nbsp;<!-- error '" + e + "' caught --></td>";
    }
    html += "</tr>";

    return html;
}
