//
//  Copyright - RealTime Fantasy Sports, Inc. 2009
//
var WatchDogTimer = 0;
var BigPlayTimer = 0;
var RefreshRate = 300000;
var FingerPrint = 'none';
var DataSrc = 0;
var isWorking = false;
var http = getHTTPObject(); 

var LastBigPlay = 0;
var QueuedBigPlay = '';
/*
var Flashing;
var FlashRate = 350;
var FlashStart = 0;
*/

function handleHttpResponse() {

	if (http.readyState == 4) {
		if (http.responseText.indexOf('invalid') == -1) {
		//try
		//{
			// Use the XML DOM 
			var xmlDocument = http.responseXML; 
			var next;
			var scoring;

//         Flashing = new Array();  // get ready to flash changed scores

			var print = xmlDocument.getElementsByTagName('sig').item(0);
			if (print)
			{
				if (print.firstChild.data != FingerPrint) document.RefreshForm.submit();
			}

			next = 0;

         var sideid = '';
         var sidecls = '';

			scoring = xmlDocument.getElementsByTagName('scoring').item(next);
			while (scoring)
			{
				var team = scoring.getAttribute('team-id');
				var side = scoring.getAttribute('side');
				var total = scoring.getAttribute('total');
				var remaining = scoring.getAttribute('remaining');
				var sb = '';
				var gb = '';
				var sd = '';
				var tb = '';
            var bp = '';
				var sbsig = '';
				var gbsig = '';
				var sdsig = '';
				var tbsig = '';
            var bpsig = '';

				if (side == 'red') {
					sideid = 'R';
					sidecls = 'scoringRedBold';
				} else {
					sideid = 'B';
					sidecls = 'scoringBlueBold';
				}
		
				if (total) {
					var tp_shown = document.getElementById('TP' + sideid + '_' + team);
					if (tp_shown)
					{
						//total = total + '&nbsp;';
						if (tp_shown.innerHTML != total) tp_shown.innerHTML = total;
					}
				}

            var mr_shown = document.getElementById('MR' + sideid + '_' + team);
            if (mr_shown) {
               if (remaining > 0) {
                  remaining = 'Minutes Remaining: ' + remaining;
               } else {
                  remaining = '&nbsp;';
               }
               if (mr_shown.innerHTML != remaining) mr_shown.innerHTML = remaining;
            }

				var i;
				for (i = 0; i < scoring.childNodes.length; i++)
				{
					var node = scoring.childNodes.item(i);
					if (node.nodeType == 1)
					{
						if (node.tagName == 'player')
						{
							var num = node.getAttribute('rtfs-id');

							var pts = node.getAttribute('points');// + '&nbsp;';
							var pts_shown = document.getElementById('PT' + sideid + '_' + num);
							if (pts_shown) {
								if (pts != pts_shown.innerHTML) {
                           pts_shown.innerHTML = pts;
                           $('#PT' + sideid + '_' + num).css('background-color','#00cc00');
                           $('#PT' + sideid + '_' + num).animate({ backgroundColor: "#ffffff" }, 15000, 
                              function() { 
                                 $('#PT' + sideid + '_' + num).css('background-color','transparent');
                              });
/*                           pts_shown.setAttribute("class", "sbWhiteFlash");*/
/*                           Flashing[Flashing.length] = pts_shown;*/
                        }
                     }

							if (node.firstChild)
							{
								var stats = node.firstChild.data;
								var stats_shown = document.getElementById('ST' + sideid + '_' + num);

								if (stats_shown) 
								{
								   stats = stats.replace(/\[BR\]/g,'<br>');
								   if (stats != stats_shown.innerHTML) stats_shown.innerHTML = stats; 
								} 
							}		
						}

						if (node.tagName == 'game')
						{
							var sig = node.getAttribute('sig');
							var num = node.getAttribute('rtfs-id');
							var gmst = node.getAttribute('status');
							var game = document.getElementById('GM' + sideid + '_' + num);
							if (game)
							{	
								if (sig != game.getAttribute('sig'))
								{
									game.setAttribute('sig',sig);
									//
									//  Game is scheduled
									//
									if (gmst == 'scheduled' && game) {
											if (node.firstChild.data != game.innerHTML) game.innerHTML = node.firstChild.data;
									}

									//
									//  Game is a final
									//
									if (gmst == 'final' && game) {
										var team;
										var score;
										var tab = '<table border=0 cellpadding=1 cellspacing=0>';
										team = node.getAttribute('away');
										score = node.getAttribute('away-score');
										tab = tab + '<tr class=sbWhite><td>' + team + '</td><td width=16 align=right>' + score + '</td><td width=44 rowspan=2 align=center><b>FINAL</b></td></tr>';
										team = node.getAttribute('home');
										score = node.getAttribute('home-score');
										tab = tab + '<tr class=sbWhite><td>' + team + '</td><td width=16 align=right>' + score + '</td></tr>';
										tab = tab + '</table>';
										if (tab != game.innerHTML) {
											game.innerHTML = tab;
										}
									}

									//
									//  Game is in progress
									//
									if (gmst == 'inprogress' && game) {
										var team;
										var score;
										var play;
										var poss;
                              var zone;
										var qtr;
                              var img;

										play = node.getAttribute('play');
										qtr = node.firstChild.data;
										poss = node.getAttribute('possession');
										zone = node.getAttribute('redzone');

										var tab = '<table border=0 cellpadding=1 cellspacing=0>';

										team = node.getAttribute('away');
										score = node.getAttribute('away-score');
                              if (poss == team) {
                                  if ("true" == zone) img = "redzone";
                                  else img = "possession" + (game.parentNode.getAttribute('class')=='sbGray' ? '-gray':'');
                              } else img = "spacer";
										tab = tab + '<tr class=sbWhite><td>' + team + '</td><td width=16 align=right>' + score + '</td>' +
												  	   '<td><img width=16 height=13 align=absmiddle src=http://www.realtime-fantasy-sports.com/img/' + img + '.gif></td>';

										tab = tab + '<td rowspan=2 align=center nowrap>' + qtr.replace(/left/,'left<br>') + '</td></tr>';

										team = node.getAttribute('home');
										score = node.getAttribute('home-score');
                              if (poss == team) {
                                  if ("true" == zone) img = "redzone";
                                  else img = "possession" + (game.parentNode.getAttribute('class')=='sbGray' ? '-gray':'');
                              } else img = "spacer";
										tab = tab + '<tr class=sbWhite><td>' + team + '</td><td width=16 align=right>' + score + '</td>' +
													'<td><img width=16 height=13 align=absmiddle src=http://www.realtime-fantasy-sports.com/img/' + img + '.gif></td></tr>';

										tab = tab + '<tr class=sbWhite><td colspan=4 align=center nowrap>' + play + '</td></tr>';

										tab = tab + '</table>';
										if (tab != game.innerHTML) {
											game.innerHTML = tab;
										}
									}
								}
							}
						}

					}
				}
				scoring = xmlDocument.getElementsByTagName('scoring').item(++next);
			}

         $(xmlDocument).find('scoring').each(function(){
             var team = $(this);
             sideid = ("red" == $(this).attr('side') ? 'R' : 'B');
             sidecls = ("red" == $(this).attr('side') ? 'scoringRedBold' : 'scoringBlueBold');

             function ShowList(datatag, label, target) {
                var list = '';
                team.find(datatag).each(function(){ list = list + '<li>' + $(this).text(); });
                $('#' + target + sideid + team.attr('team-id')).html('<span class=' + sidecls + '>' + label + ':</span><span class=scoringBulletItems>' + list + '</span>');
             }

             ShowList('score','SCORING','SB');
             ShowList('bonus','BONUSES','GB');
             ShowList('deduction','DEDUCTIONS','SD');
             ShowList('bench','BENCH','BP');
             ShowList('tiebreaker','TIE BREAKERS','TB');

             team.find('lineup').each(function(){
                $('#TP' + sideid + '_' + $(this).attr('team-id')).html($(this).attr('best-points'));   // set the team total to best lineup
                $(this).find('bench').each(function(){ $('#PT' + sideid + '_' + $(this).attr('rtfs-id')).removeClass('sbDraftMasterBig').addClass('sbWhiteBig'); });
                $(this).find('starter').each(function(){ $('#PT' + sideid + '_' + $(this).attr('rtfs-id')).removeClass('sbWhiteBig').addClass('sbDraftMasterBig'); });
             });
         });


         var node = xmlDocument.getElementsByTagName('bestpercent').item(0);
         if (node)
         {
            var best = '<br>' + node.firstChild.data + ' OF BEST POSSIBLE ROSTER';
            var bp =  document.getElementById('BestPercent');
            if (bp.innerHTML != best )
            {
               bp.innerHTML = best;
            }
         }

         next = 0;
			var node = xmlDocument.getElementsByTagName('team').item(next);
			while (node)
			{
            var i = 0;
            var teamnum = node.getAttribute('team-id');
            var total = node.getAttribute('total');
            var tag = document.getElementById('SC' + teamnum + 'V' + i);
            while (tag) {
               if (tag.innerHTML != total) tag.innerHTML = total;
               i = i + 1;
               tag = document.getElementById('SC' + teamnum + 'V' + i);
            }
				node = xmlDocument.getElementsByTagName('team').item(++next);
			}

         var big = xmlDocument.getElementsByTagName('big-plays').item(0);
         if (big) {
            LastBigPlay = big.getAttribute('last');
            var play = xmlDocument.getElementsByTagName('play');
            if (play) {
               if (play.item(0)) ShowBigPlay(play.item(0).firstChild.data);
               if (play.item(1)) 
                  QueuedBigPlay = play.item(1).firstChild.data;
               else
                  QueuedBigPlay = '';
            }
         }
         
         var topdate = $(xmlDocument).find("update");
         if (topdate.length > 0) $('#TopCurrDate').html(topdate.text());


/*
         if (Flashing.length > 0) {
            FlashStart = new Date();
            setTimeout("FlashScores()",FlashRate);
         }
*/
			isWorking = false;    

			timerID = setTimeout("UpdateScores()", RefreshRate + Math.floor(Math.random() * 5));

			clearTimeout(WatchDogTimer);
			WatchDogTimer = setTimeout("RefreshPage()", RefreshRate * 2);
//		}
//		catch (e)
//		{
//			RefreshPage();
//		}

		} else {
			//  invalid xml
			RefreshPage();
		}
	}
}

/*
function FlashScores()
{
   var now = new Date();
   var done = now.getTime() - 15000 > FlashStart.getTime();
   if (!done) setTimeout("FlashScores()",FlashRate);
   for (i = 0; i < Flashing.length; i++) {
      if (Flashing[i].getAttribute("class") == "sbWhiteFlash" || done) {
         Flashing[i].setAttribute("class", "sbWhiteBig");
      } else {
         Flashing[i].setAttribute("class", "sbWhiteFlash");
      }
   }
}
*/

function ShowBigPlay(play)
{
   var bigplaybox = document.getElementById('BigPlay');
   if (bigplaybox) {
      bigplaybox.setAttribute("class", "BigPlaySplash");
      bigplaybox.innerHTML = play;
      BigPlayTimer = setTimeout("ClearBigPlay()", 1000);
   }
}

function ClearBigPlay()
{
   var bigplaybox = document.getElementById('BigPlay');
   if (bigplaybox) {
      var cls = bigplaybox.getAttribute("class");
      if (cls == "BigPlaySplash") {
         bigplaybox.setAttribute("class", "BigPlayShow");
     	   BigPlayTimer = setTimeout("ClearBigPlay()", 13000);
      } else {
         bigplaybox.innerHTML = '';
         bigplaybox.setAttribute("class", "");
         if (QueuedBigPlay != '') {
            ShowBigPlay(QueuedBigPlay);
            QueuedBigPlay = '';
         }
      }
   }
}


function UpdateScores() 
{
	if (!isWorking && http) {
      var params = "XML=1&LID=" + $('input[name=LID]').val() + "&UID=" + $('input[name=UID]').val() + "&TM1=" + $('input[name=TM1]').val() + "&FFL=" + $('input[name=FFL]').val()
		if (DataSrc == 1) {
			http.open("GET", "/cgi-bin/scorecast?" + params + "&BP=" + LastBigPlay + "&X=" + Math.floor(Math.random() * 99999), true);
		} else if (DataSrc == 2) {
			http.open("GET", "/cgi-bin/gamecast?" + params + "&TM2=" + $('input[name=TM2]').val() + "&BP=" + LastBigPlay + "&X=" + Math.floor(Math.random() * 99999), true);
		} else if (DataSrc == 3) {
			http.open("GET", "/cgi-bin/display_actual_vs_best?" + params + "&X=" + Math.floor(Math.random() * 99999), true);
		}
		http.onreadystatechange = handleHttpResponse;
		isWorking = true;
	   http.send(null);
	}
}

function RefreshPage()
{
	document.RefreshForm.submit();
}

//function SetGame(LN,TM1,TM2,Week,FPrint,DSrc,Refresh)
function SetGame(FPrint,DSrc,Refresh)
{
	DataSrc = DSrc;
	FingerPrint = FPrint;
	if (RefreshRate < 60000)
		RefreshRate = 60000; // be safe
	else 
		RefreshRate = Refresh;

	if (http) {
	   //  set the refresh timer and an emergency timer
	   RefreshTimer = setTimeout("UpdateScores()", RefreshRate);
	   WatchDogTimer = setTimeout("RefreshPage()", RefreshRate * 2);
	} else {
	   //  apparently does not support XMLHTTPRequest
	   ReloadTimer = setTimeout("RefreshPage()", RefreshRate);
	}
}



function scoringLogSelected(theForm,useLeaderBoard)
{
	var URL, team_number;

	if (theForm.scoringLogSelect.selectedIndex == 0) {

      if (useLeaderBoard)
      {
         // The first item in the games list was selected, which is just "All Scores"
         URL = "/cgi-bin/leaderboard?LID=" + theForm.LID.value + "&UID=" +
              theForm.UID.value + "&TN=" + theForm.TN.value + "&Week=" +
              theForm.FFL.value + "&X=" + Math.round(Math.random() * 32768);
      } else {
         // The first item in the games list was selected, which is just "All Scores"
         URL = "/cgi-bin/scoreboard?LID=" + theForm.LID.value + "&UID=" +
              theForm.UID.value + "&TN=" + theForm.TN.value + "&Week=" +
              theForm.FFL.value + "&X=" + Math.round(Math.random() * 32768);
      }
	} else {
		team_number = theForm.scoringLogSelect.options[theForm.scoringLogSelect.selectedIndex].value;
		
		URL = "/cgi-bin/scorecast?LID=" + theForm.LID.value + "&UID=" +
			  theForm.UID.value + "&TN=" + theForm.TN.value + "&FFL=" +
			  theForm.FFL.value + "&TM1=" + team_number + "&X=" + Math.round(Math.random() * 32768);
	}
	
	window.open(URL, '_self');
}

//------------------------------------------------------------------------------------

function GoBox(away,home)
{
   URL = "/php/nfl-content.php?ITEM=6&LN=" + escape(document.RefreshForm.LID.value) + "&UID=" +
         escape(document.RefreshForm.UID.value) + "&NFL_WEEK=" + escape(document.RefreshForm.NFL.value) + 
         "&AWAY=" + escape(away) + "&HOME=" + escape(home) + 
         "&X=" + Math.round(Math.random() * 32768);
   window.location.href = URL;
}


var FirstGame = 0;
function DisplayGames(first,count)
{
   var curr = 0;
   var gamediv = document.getElementById('GAME' + curr);
   while (gamediv) {
      if (curr < first) gamediv.style.display = "none";
      else if (curr < first + count) gamediv.style.display = "block";
      else gamediv.style.display = "none";
      curr = curr + 1;
      gamediv = document.getElementById('GAME' + curr);
   }
}

function ScrollLeft(count)
{
   if (FirstGame > 0) {
      FirstGame = FirstGame - 1;
      DisplayGames(FirstGame,count);
   }
}

function ScrollRight(last,count)
{
   if (FirstGame < (last - count) + 1){
      FirstGame = FirstGame + 1;
      DisplayGames(FirstGame,count);
   }
}
