var MediaGrid = function (params) {

    this.type     = null; // 'audio' or 'video'
    this.period   = null; // 'day' or 'month' - determined if we show Date/Time or just Time
    this.target   = null; // id of tag to insert the grid into
    this.clubid   = null; // id of club this grid is for
    this.portal   = null; // '1' if this is the MiLB portal MM section 
    this.teamname = "full"; // format for team name 'full' (ex. Las Vegas 51s)
                            // or 'name' (ex. 51s)
                            // and (eventually 'short' - ex. Las Vegas) - not supported until put into generalproperties.js

    if (params.type)     { this.type     = params.type;     }
    if (params.period)   { this.period   = params.period;   }
    if (params.target)   { this.target   = params.target;   }
    if (params.clubid)   { this.clubid   = params.clubid;   }
    if (params.portal)     { this.portal     = params.portal;     }
    if (params.teamname) { this.teamname = params.teamname; }

    this.data    = null;
    this.dataUrl = null; // url source for new data to allow the obj to refresh itself

    // build a string of the table with all the rows of media items,
    // and then insert it into the element defined in the target param
    this.buildGrid = function() {

        // given a UTC seconds and tz offset value, return a formatted time and date.
        function getDateString (time, offset) { 
           
            var gameTime = new Date();
            var localDate = new Date();
            var localOffset = localDate.getTimezoneOffset() * 60 * 1000;          
            var formattedTime = "TBD";
            var formattedDate = "TBD";
            var isToday = false;
            var months = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]          
           
            if (offset) { 
                offset = offset * 60 * 60 * 1000;
            } else { offset = 0; } 
            time = time + offset + localOffset;
           
            gameTime.setTime(time);
           
            var hour = gameTime.getHours();
            var ampm = "";
            if (hour > 12) {
                hour = hour - 12;
                ampm = "p";
            } else if (hour == 12) {
                ampm = "p";
            } else { 
                ampm = "a";
            }
          
            var minute = gameTime.getMinutes();
            if (minute < 10) { minute = "0" + minute; }
          
            if ((hour == 3) && (minute == 33)) { 
                formattedTime = "Game&nbsp;2";
            } else { 
                formattedTime = hour + ":" + minute + ampm; 
            }

            formattedDate = months[gameTime.getMonth()] + " " + gameTime.getDate();

            if ((localDate.getFullYear() == gameTime.getFullYear()) 
                && (localDate.getMonth() == gameTime.getMonth()) 
                && (localDate.getDate() == gameTime.getDate())) {
                isToday = true;
            }

            return { 
              time: formattedTime, 
              date: formattedDate,
              isToday: isToday
            };
        }

        var html  = "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"mediaData\"><thead><tr>";


	if (this.portal != "1") {
	        if (this.period != "day") {
	            html += "<td class=\"firstCell\">Date</td>";
	            html += "<td style=\"width: 65px;\">Time&nbsp;ET</td>";
	        } else {
	            html += "<td class=\"firstCell\">Time&nbsp;ET</td>";
	        }

	        html += "<td>Game</td>";

	        if (this.type == "video") {
	            html += "<td class=\"lastCell\" style=\"text-align: center;\">Watch</td>";
	        } else if (this.type == "audio") {
	            html += "<td class=\"lastCell\" style=\"text-align: center;\">Away</td><td style=\"text-align: center;\">Home</td>";
	        }
	        html += "</tr></thead><tbody>";
	}
	else {
		html += "<td colspan=\"3\"><img src=\"/images/multimedia/y2009/game_details_bar.gif\" height=\"18\" width=\"615\" /></td></tr></thead>";
	}


        if ((this.data == null) || (this.data.length == 0)) { 
            html += "<tr><td colspan=\"3\"><div class=\"error\" style=''>"; 
		html += "No " + this.type + " available for this " + this.period + ".&nbsp; ";
		html += "&nbsp;Please select another " + this.period + ".  ";
//            html += "Please use the calendar navigation above to <br />find archived games from the 2008 season."; 
            html += "</div></td></tr>"; 
        } else { 

            var rowClass = "odd";
            var rows = this.data.length

            for (var i = 0; i<rows; i++) {

                var game = this.data[i];
				
				// new code for 2008
				if (game.game_info.game_status) {
					var status = game.game_info.game_status
					var status_group = status.substring(0,1);
				} else {
					var status = "";
					var status_group = "";
				}

                var gameTimeInfo = getDateString(parseInt(game.game_info.time,10), parseInt(game.game_info.offset.est,10));
                var formattedTime = gameTimeInfo.time;
                var formattedDate = gameTimeInfo.date;
                var isToday = gameTimeInfo.isToday;

                if (i % 2) { rowClass = "even" } else { rowClass = "odd"; }

                if ((isToday) &&  (this.period != "day")) {
                    rowClass += " today";
                } 
                html += "<tr class=\"" + rowClass + "\" >";

                if (this.period == "day") {
                    html += "<td class=\"firstCell time\" style=\"text-align: right; padding-right: 10px;\">";
						if (status_group==="D") {
							html += "PPD";
						} else if ((status_group==="U") || (status_group==="T")) {
							html += "SUSPD";
						} else if (status_group==="C") {
							html += "CNCL";
						} else {
							html += formattedTime;
						}
					html += "</td>";
                } else {
                    html += "<td class=\"firstCell date\">" + formattedDate + "</td>";
                    html += "<td style=\"text-align: right; padding-right: 10px;\">";
						if (status_group==="D") {
							html += "PPD";
						} else if ((status_group==="U") || (status_group==="T")) {
							html += "SUSPD";
						} else if (status_group==="C") {
							html += "CNCL";
						} else {
							html += formattedTime;
						}
					html += "</td>";
                }

                var teamAway = "Away Team";
                var teamHome = "Home Team";
                try {
                    if (this.teamname == "name") { 
                        teamAway = properties.clubs[game.game_info.teams.away.id].name;
                        teamHome = properties.clubs[game.game_info.teams.home.id].name;
                    } else { 
                        teamAway = properties.clubs[game.game_info.teams.away.id].display_name;
                        teamHome = properties.clubs[game.game_info.teams.home.id].display_name;
                    }
                } catch (e) {}

                html += "<td class=\"teams\">" + teamAway + " @ " + teamHome + "</td>";
				

                if (this.type == "video") {
					if ((status_group==="D") || (status_group==="U") || (status_group==="T") || (status_group==="C")) {
	                    html += "<td class=\"lastCell\" style=\"text-align: right;\">&nbsp;";
					} else {
	                    html += "<td class=\"lastCell\" style=\"text-align: right;\">&nbsp;";
	                    html += this.buildVideoGrid(game);			
					}
                } else if (this.type == "audio") {
					if ((status_group==="D") || (status_group==="U") || (status_group==="T") || (status_group==="C")) {
	                    html += "<td>&nbsp;</td><td class=\"lastCell\">&nbsp;";
					} else {
	                    html += "<td>&nbsp;";
	                    html += this.buildAudioGrid(game, "away");
	                    html += "</td><td class=\"lastCell\">&nbsp;";
	                    html += this.buildAudioGrid(game, "home");
					}
                } else {
//                  alert('invalid grid type');
                }

                html += "</td></tr>";
            }
        }

        html += "</tbody></table>";


        this.insertGrid(html);

    }

    // called by buildGrid with the game object, to build a html string
    // with the links to the video media items
    this.buildVideoGrid = function(game) {

        var html = "";
        try {
            var video = game.video;
            var state = video.state;
            var lang = "";
            if ((video.language) && (video.language.toLowerCase() != "en")) {
                if (video.language.toLowerCase() == "es" ) { 
                    lang = "<img src=\"/images/icons/media_lang_es.gif\" alt=\"En Espa&ntilde;ol\" height=\"10\" width=\"10\" style=\"margin-left: 2px;\" />";
                } else { 
                    lang = "[" + video.language.toUpperCase() + "]";
                }
            } 
            var icon = "";
            var active = false;
            switch (state) {
            case "video_on": 
                icon = "<img src=\"/images/icons/media_live.gif\" alt=\"Live\" height=\"10\" width=\"10\" />";
                active = true;
                break;
            case "video_archive": 
                icon = "<img src=\"/images/icons/media_archive.gif\" alt=\"Archive\" height=\"10\" width=\"10\" />";
                active = true;
                break;
            case "video_done": 
                icon = "<img src=\"/images/icons/media_soon.gif\" alt=\"Coming Soon\" height=\"10\" width=\"10\" />";
                active = false;
                break;
            default:
                icon = "<img src=\"/images/trans.gif\" height=\"10\" width=\"10\" class=\"trans\" />";
                active = false;
                break;
            }
              
            html += icon + lang;
              
            for (var u = 0; u<video.urls.length; u++) {
                var text = video.urls[u].speed + "K";
                var type = "v_sub";
                  
                if ((video.urls[u].url.login == "N") && (video.urls[u].url.authorization == "N")) {
                    html += "<img src=\"/images/icons/media_free.gif\" alt=\"Free\" height=\"10\" width=\"10\"  style=\"margin-left: 2px;\"  />";
                    type = "v_free";
                }
                  
                var object = "{ w:\'" + video.urls[u].url.w + "\', w_id:\'" + video.urls[u].url.w_id + "\', pid:\'" + video.urls[u].url.pid + "\', type: \'" + type + "\'} ";
                  
                if (active) { 
                    html += " <a href=\"javascript:mp.play(" + object + ");\">" + text + "</a> &nbsp; ";
                } else {
                    html += " " + text + " &nbsp; ";
                }
                  
            }

        } catch(e) {
            return "";
        }
        return html;
    }

    // called by buildGrid with the game object, to build a html string
    // with the links to the audio media items
    this.buildAudioGrid = function(game, location) {

        var audioTypes = ["away_audio", "alt_away_audio", "home_audio", "alt_home_audio"];
        var html = "";
        try { 
            for (var a = 0; a<audioTypes.length; a++) {
                  
                if (audioTypes[a].indexOf(location) == -1) { continue; } // only look for 'away' or 'alt_away' if location = 'away'
                if (!game[audioTypes[a]]) { continue; }                  // return if there is no content in the object

                var audio = game[audioTypes[a]];
                var state = audio.state;
                var lang = "";
                if ((audio.language) && (audio.language.toLowerCase() != "en")) {
                    if (audio.language.toLowerCase() == "es" ) { 
                        lang = "<img src=\"/images/icons/media_lang_es.gif\" alt=\"En Espa&ntilde;ol\" height=\"10\" width=\"10\" style=\"margin-left: 2px;\" />";
                    } else { 
                        lang = "[" + audio.language.toUpperCase() + "]";
                    }
                } 
                var icon = "";
                var active = false;
                switch (state) {
                case "audio_on": 
                    icon = "<img src=\"/images/icons/media_live.gif\" alt=\"Live\" height=\"10\" width=\"10\" />";
                    active = true;
                    break;
                case "audio_pregame": 
                    icon = "<img src=\"/images/trans.gif\" height=\"10\" width=\"10\" class=\"trans\" />";
                    active = true;
                    break;
                case "audio_archive": 
                    icon = "<img src=\"/images/icons/media_archive.gif\" alt=\"Archive\" height=\"10\" width=\"10\" />";
                    active = true;
                    break;
                case "audio_done": 
                    icon = "<img src=\"/images/icons/media_soon.gif\" alt=\"Coming Soon\" height=\"10\" width=\"10\" />";
                    active = false;
                    break;
                default:
                    icon = "<img src=\"/images/trans.gif\" height=\"10\" width=\"10\" class=\"trans\" />";
                    active = false;
                    break;
                }

                html += icon + lang;

                for (var u = 0; u<audio.urls.length; u++) {
                    var text = audio.text;
                    var type = "a_sub";

                    if ((audio.urls[u].url.login == "N") && (audio.urls[u].url.authorization == "N")) {
											html += "<img src=\"/images/icons/media_free.gif\" alt=\"Free\" height=\"10\" width=\"10\" style=\"margin-left: 2px;\"  />";
											type = "a_free";
                    } else if ((audio.urls[u].url.login == "Y") && (audio.urls[u].url.authorization == "N")) {
											html += "<img src=\"/images/icons/media_free.gif\" alt=\"Free\" height=\"10\" width=\"10\" style=\"margin-left: 2px;\"  />";
										}

                    var object = "{ w:\'" + audio.urls[u].url.w + "\', w_id:\'" + audio.urls[u].url.w_id + "\', pid:\'" + audio.urls[u].url.pid + "\', type: \'" + type + "\'} ";

                    if (active) { 
                        html += " <a href=\"javascript:mp.play(" + object + ");\">" + text + "</a>";
                    } else {
                        html += " " + text;
                    }

                }

            }
        } catch(e) { 
            return "";
        }
        return html;

    }

    // given the html string with all the media, insert it into the page target
    this.insertGrid = function(html) {
        var el = document.getElementById(this.target);
        if (el) {
            el.innerHTML = html;
        } else { 
            alert(this.target + " not found (" + el + ")"); 
        }
    }

    // TODO: will call the update routine to refresh its own data periodically, atleast for the current day
    this.fetchData = function() { 
//      alert('fetch new data via xmlhttprequest');
    }

};

