var days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var player="http://mlb.mlb.com/team/player.jsp?player_id=";
var sortable="http://mlb.mlb.com/schedule/sortable.jsp?c_id=";
var standings="http://mlb.mlb.com/mlb/standings/?ymd=";

var bam_tix = {};

var east_of_gmc = (new Date()).getTimezoneOffset() < 0;
var twelve_hours = 12 * 60 * 60 * 1000;

function Game(arr) {
  this.gdate = new Date(arr[32]);
	this.isTBDdate = !!arr[32].match(/03:33/);
	this.y = this.gdate.getFullYear();
	this.m = this.gdate.getMonth()+1;
	this.d = this.gdate.getDate();
	this.ymd = this.y.toString() + ("0" + this.m).slice(-2) + ("0" + this.d).slice(-2);
	this.day = days[this.gdate.getDay()];
	var hour = this.gdate.getHours();
	var mins = ("0" + this.gdate.getMinutes()).slice(-2);
	
	var am_pm;
	if(hour >= 12) {
	  am_pm = "p";
	  if(hour > 12) {
	    hour -= 12;
	  } 
	} else {
	  am_pm = "a";
	}

	this.time = hour + ":" + mins + am_pm;
	this.today = new Date();
//	this.today.setUTCHours(11,0,0);
	this.gdateCompare = new Date(this.gdate.getTime());
//	this.gdate.setUTCHours(11,0,0);
	this.opponent = arr[5];
	this.result = arr[6]; 
	this.wrapup_link = arr[7];
	this.record = arr[8];
	this.wp = arr[9];
	this.wp_id = arr[10];
	this.lp = arr[11];
	this.lp_id = arr[12];
	this.broadcast = arr[13];
	this.probable_home = arr[14];
	this.probable_home_id = arr[15];
	this.probable_away = arr[16];
	this.probable_away_id = arr[17];
	this.home_away = arr[20];
	this.game_id = arr[21].replace(/[\/\-]/g, "_");
  this.tickets_link = bam_tix[this.game_id] && bam_tix[this.game_id].ticket_link.tlink;        // will be undefined until the tlinks load, which is ok
	this.preview_link = arr[18];
	this.oppDisplayCode = arr[4];
	this.win_loss = (this.result) ? this.result.toString().substring(0,1) : "";
	this.opp_display = (this.home_away=='away') ? "at " + this.opponent : this.opponent;
	this.oppDisplay = (this.home_away=='away') ? "@" + this.oppDisplayCode.toUpperCase() : "vs" + this.oppDisplayCode.toUpperCase();
	this.tagBgColor = (compareDate(this)<0) ? "past" : (compareDate(this)==0) ? "current" : (this["oppDisplayCode"]) ? this.home_away : "off";
	this.tbd = arr[22];
	this.status = arr[23];
	this.isTBD = (this.tbd=='1') ? true : false;
	this.isPPD = (this.result == '' && (compareDate(this)==-1)) ? true : false;
	this.isComplete = ((this.status == 'F' || this.status == 'GO' || this.status == 'FO' || this.status == 'C' || this.status == 'S' || this.status == 'PO')) ? true : false;
}

// compare date
function compareDate(currentGame) {
	if (currentGame.today.getTime() > currentGame.gdateCompare.getTime()) {return -1;}
	else if (currentGame.today.getTime() == currentGame.gdateCompare.getTime()) {return 0;}
	else if (currentGame.today.getTime() < currentGame.gdateCompare.getTime()) {return 1;}
}

// set filter variables
var filterMonth = "";
var filterDay = "";
var filterOpp = "";
var filterHomeAway = "";
var today = new Date();

// filters data from pulldown below
function filter(type, value) {
	window[type] = value;
}
function resetForm(type) {
	var clearForm = document.forms.filterData;
	clearForm.reset();
	if (filterMonth != "") filterMonth="";
	if (filterDay != "") filterDay="";
	if (filterOpp != "") filterOpp="";
	if (filterHomeAway != "") filterHomeAway="";
}
function sortable_schedule_populate(type) {
	var pastRowCount = 0;
	var futureRowCount = 0;
	var pastTbl = document.getElementById('past');
	var futureTbl = document.getElementById('future');
	var noResultsMsg = document.getElementById('noresults');
	//Added by good developers
	var rLen = raw.length-1;
	for (var j=0; j<=rLen; j++) {
		if (j <= rLen) {
			var currentRow = "";
			var currentGame = new Game(raw[j]);

			if ((filterMonth!='' && currentGame.m!=filterMonth)) continue;
			if ((filterDay!='' && currentGame.day!=filterDay)) continue;
			if ((filterHomeAway!='' && currentGame.home_away!=filterHomeAway)) continue;
			if ((filterOpp!='' && currentGame.oppDisplayCode!=filterOpp)) continue;

			if (currentGame.isComplete) {
			
				if (pastTbl == null) continue;
				currentRow = pastTbl.tBodies[0].rows[pastRowCount];
				pastRowCount++;
				
				// get column objects ( each row <td> )
				var dateObj = currentRow.cells[0];
				var oppObj = currentRow.cells[1];
				var resObj = currentRow.cells[2];
				var recObj = currentRow.cells[3];
				var wpObj = currentRow.cells[4];
				var lpObj = currentRow.cells[5];
				
				switch(currentGame.status) {
					case "F" : (currentGame.wrapup_link != "") ? resObj.innerHTML = '<a href="' + currentGame.wrapup_link + '" class="primaryVlink">' + currentGame.result + '</a>' : resObj.innerHTML = currentGame.result; break;
					case "GO" : (currentGame.wrapup_link != "") ? resObj.innerHTML = '<a href="' + currentGame.wrapup_link + '" class="primaryVlink">' + currentGame.result + '</a>' : resObj.innerHTML = currentGame.result; break;
					case "FO" : resObj.innerHTML = "Forfeit"; break;
					case "C" : resObj.innerHTML = "Cancelled"; break;
					case "S" : resObj.innerHTML = "Suspended"; break;
					case "PO" : resObj.innerHTML = "Postponed"; break;
				}
				
				dateObj.innerHTML = currentGame.day+", " +currentGame.m+"/"+currentGame.d;
				oppObj.innerHTML = '<a href="' + sortable + currentGame.oppDisplayCode + '" class="primaryVlink">' + currentGame.opp_display + '</a>';
				recObj.innerHTML = '<a href="' + standings + currentGame.ymd + '" class="primaryVlink">' + currentGame.record + '</a>';
				wpObj.innerHTML = (currentGame.wp != "") ? "<a href='" + player + currentGame.wp_id + "' class='primaryVlink'>" + currentGame.wp + "</a>" : "&nbsp;";
				lpObj.innerHTML = (currentGame.lp != "") ? "<a href='" + player + currentGame.lp_id + "' class='primaryVlink'>" + currentGame.lp + "</a>" : "&nbsp;";

			} else {
				// if future html table doesn't exist, continue
				if (futureTbl == null) continue;
				currentRow = futureTbl.tBodies[0].rows[futureRowCount];
				futureRowCount++;

				// get column objects ( each row <td> )
				var dateObj = currentRow.cells[0];
				var oppObj = currentRow.cells[1];
				var timeObj = currentRow.cells[2];
				var broadObj = currentRow.cells[3];
				var ppObj = currentRow.cells[4];
				var opObj = currentRow.cells[5];
				var tickObj = currentRow.cells[6];

				dateObj.innerHTML = currentGame.day + ", " + currentGame.m + "/" + currentGame.d;
				oppObj.innerHTML = '<a href="' + sortable + currentGame.oppDisplayCode + '" class="primaryVlink">' + currentGame.opp_display + '</a>';
				
				var clubidparam = "";
				if (club != "") { clubidparam = "&c_id="+club; }
				if (currentGame.broadcast == "") {
					broadObj.innerHTML = "<span class='txtBroadcast'>" + currentGame.broadcast + "<a href='http://mlb.mlb.com/mlb/subscriptions/index.jsp?affiliateId=sortschedule"+ clubidparam +"' class='primaryVlink'>MLB.TV</a></span>";
				} else {
					broadObj.innerHTML = "<span class='txtBroadcast'>" + currentGame.broadcast + ", <a href='http://mlb.mlb.com/mlb/subscriptions/index.jsp?affiliateId=sortschedule"+ clubidparam +"' class='primaryVlink'>MLB.TV</a></span>";
				}

				ppObj.innerHTML = (currentGame.probable_home != "") ? "<a href='" + player + currentGame.probable_home_id + "' class='primaryVlink'>" + currentGame.probable_home + "</a>" : "&nbsp;";
				opObj.innerHTML = (currentGame.probable_away != "") ? "<a href='" + player + currentGame.probable_away_id + "' class='primaryVlink'>" + currentGame.probable_away + "</a>" : "&nbsp;";

				// Check if TBD
				if (currentGame.isTBD && currentGame.time != "3:33am") currentGame.time = "TBD";
				// if preview exists, link it from the game time
				if (currentGame.preview_link != "") timeObj.innerHTML = '<a href="' + currentGame.preview_link + '" class="primaryVlink">' + currentGame.time + '</a>';
				// if preview DOESN'T exist, just show the game time
				else timeObj.innerHTML = currentGame.time;

        if (currentGame.tickets_link) {
          tickObj.innerHTML = "<a href='"+ currentGame.tickets_link +"' data-loc='" + currentGame.home_away + "' class='primaryVlink'>Buy<img src='/images/schedule/icon_ticket.gif' alt='Buy Tickets' width='13' height='13' border='0' align='absmiddle' hspace='4' /></a>";
				} else {
				  tickObj.innerHTML = "<a href='#' id='game" + currentGame.game_id + "' data-loc='" + currentGame.home_away + "' style='display:none;' class='primaryVlink'>Buy<img src='/images/schedule/icon_ticket.gif' alt='Buy Tickets' width='13' height='13' border='0' align='absmiddle' hspace='4' /></a>";
				}

				
				
			}
			// display row
			currentRow.style.display = "";
			// toggle between home/away bgcolors
			currentRow.className = currentGame.home_away;
		}
		else break;
	}
	if (pastRowCount<=rLen) for(var x=pastRowCount; x<=rLen; x++) hideRows(pastTbl, x);
	if (futureRowCount<=rLen) for(var x=futureRowCount; x<=rLen; x++) hideRows(futureTbl, x);

	if (pastRowCount<1 && futureRowCount<1) {
		if (pastTbl != null) pastTbl.style.display = "";
		if (futureTbl != null) futureTbl.style.display = "";
		noResultsMsg.style.display = "";
	} else if (pastRowCount<1 && futureRowCount>=1) {
		if (pastTbl != null) pastTbl.style.display = "none";
		futureTbl.style.display = "";
		noResultsMsg.style.display = "none";
	} else if (pastRowCount>=1 && futureRowCount<1) {
		if (futureTbl != null) futureTbl.style.display = "none";
		pastTbl.style.display = "";
		noResultsMsg.style.display = "none";
	} else {
		pastTbl.style.display = "";
		futureTbl.style.display = "";
		noResultsMsg.style.display = "none";
	}
}
function hideRows(tbl, count) {
	if (tbl == null) return;
	var row = tbl.tBodies[0].rows[count];
	row.style.display = "none";
}
// Create Empty Past Game Row w/display=none
function writePastGameRow(row) {
	var output="";
	output += "<tr valign='top' id='past_r" + row + "' style='display:none;'>";
	output += "<td id='past_r" + row + "c0' nowrap='nowrap'></td>"; // Date
	output += "<td id='past_r" + row + "c1' nowrap='nowrap'></td>"; // Opponent
	output += "<td id='past_r" + row + "c2' nowrap='nowrap'></td>"; // Result
	output += "<td id='past_r" + row + "c3' nowrap='nowrap'></td>"; // Record (commented out until fix is complete)
	output += "<td id='past_r" + row + "c4' nowrap='nowrap'></td>"; // Winning Pitcher
	output += "<td id='past_r" + row + "c5' nowrap='nowrap'></td>"; // Losing Pitcher
	output += "</tr>";
	document.write(output);
}
// Create Empty Future Game Row w/display=none
function writeFutureGameRow(row) {
	var output="";
	output += "<tr valign='top' id='future_r" + row + "' style='display:none;'>";
	output += "<td id='future_r" + row + "c0' nowrap='nowrap'></td>"; // Date
	output += "<td id='future_r" + row + "c1' nowrap='nowrap'></td>"; // Opponent
	output += "<td id='future_r" + row + "c2' nowrap='nowrap'></td>"; // Time
	output += "<td id='future_r" + row + "c3' nowrap='nowrap'></td>"; // Broadcast
	output += "<td id='future_r" + row + "c4' nowrap='nowrap'></td>"; // Probable Pit.
	output += "<td id='future_r" + row + "c5' nowrap='nowrap'></td>"; // Opposing Pit.
	output += "<td id='future_r" + row + "c6' nowrap='nowrap'></td>"; // Tickets
	output += "</tr>";
	document.write(output);
}

function buildRows(type) {
	var rLen = raw.length-1;
	switch(type) {
		case 'past' : for(var x=0;x<=rLen;x++) writePastGameRow(x); break;
		case 'future' : for(var x=0;x<=rLen;x++) writeFutureGameRow(x); break;
	}
}

function getTix() {
  var params = bam.url.parseQueryParameters();
  var today = new Date(),
    year = today.getFullYear(),
    today_str = year + ("0" + (today.getMonth() + 1)).slice(-2) + today.getDate();
  
  if(params.year == year) {
    $.ajax({
      url: "/ticketing-client/json/Game.tiksrv",
      data: {
        team_id               : sortable_schedule_team_id,  // externally defined
        begin_date            : today_str,
        year                  : year,
        sport_id              : 1,
        site_section          : "SCHEDULE"
      },
      dataType: "json",
      success: function(response) {
        if(response && response.events && response.events.game) {
          var games = bam_tix = $.rehash($.ensureArray(response.events.game), "game_id");
          
          var i, selector = [];
  
          for(i in games) {
            if(games.hasOwnProperty(i)) {
              var gm = games[i];
              delete games[i];
              i = i.replace(/[\/\-]/g, "_");
              games[i] = gm;
              selector.push("#game" + i);
            }
          }
          if(selector.length) {
            $(selector.join(", ")).each(function() {
              var $this = $(this);
              var schedule_id = $(this).attr("id").replace("game", "");
              $this.show().attr("href", games[schedule_id].ticket_link.tlink);
            });
          }
        }
      },
      error: function(xhr, status, error) {
        window.console && console.error(this.url.replace(/^.+\/(.+)\?.*$/, "$1"), "<" + status + ">:\n", error);
      }
    })
  }
}

function init(){
	var showBenchmark = document.location.search.indexOf("bm=true"); 
	if(showBenchmark>0) alert("Page Loaded!\n\nStart Populating");
	start = (new Date()).getTime();
	sortable_schedule_populate();
	stop = (new Date()).getTime();
	if(showBenchmark>0){
		benchmark = (stop - start) / 1000;
		alert("Start = " + start + "\nStop = " + stop + "\n\n" + raw.length + " Rows\n" + benchmark + " Seconds");
	}
}

$(document)
  .delegate("#future .primaryVlink", "click", function(e) {
    openTIXXWindow(this.href, $(this).attr("data-loc"));
    e.preventDefault();
  })
