var tsMatchGameIds;
var tsLeagueNames;

var tsAppState = {
  pageViewType       : undefined,
  collapsedLeagues   : [],
  userSelectedLeague : undefined,
  site               : undefined,
  lang               : undefined,
  todaysDate         : undefined,
  matchDate          : undefined,
  matchDateYesterday : undefined,
  matchDateTomorrow  : undefined,
  timeOffset         : undefined,
  autoRefreshOn      : true
}

var tsUrls = {
  liveScores        : "/nugget/FSITodaysScores_",
  futureFinalScores : "/nugget/FSITodaysScoresFutureFinal_"
}

var tsElementIds = {
  pageContainer         : "todaysScoresPageContainer",
  contentContainer      : "todaysScoresContentContainer",
  leagueContainer       : "todaysScoresLeagueContainer_",
  leagueScoresContainer : "todaysScoresLeagueScores_",
  leagueScoresToggle    : "todaysScoresToggleScores_",
  pageViewToggle        : "todaysScoresToggleView",
  boxScoreTable         : "todaysScoresBoxScore_",
  matchStatsTable       : "todaysScoresMatchStats_"
}

var tsText = {
  langEnglish            : "en",
  langSpanish            : "es",
  expandEnglish          : "expand +",
  expandSpanish          : "expandir +",
  closeEnglish           : "close -",
  closeSpanish           : "cerrar -",
  displayStatsEnglish    : "Display match stats",
  displayStatsSpanish    : "Desplegar estadisticas",
  displayBoxScoreEnglish : "Display box scores",
  displayBoxScoreSpanish : "Desplegar resultados",
  pageViewMatchStats     : "matchstats",
  pageViewBoxScore       : "boxscore",
  styleDisplayBlock      : "block",
  styleDisplayNone       : "none"
}


//===================================================
// NAME: displayElement(elementId)
// PARAM: an elements id
// RESULT: hidden element with given ID is displayed
//===================================================
function displayElement(elementId) {
  if (document.getElementById(elementId)) {
    document.getElementById(elementId).style.display = tsText.styleDisplayBlock;
  }
   return;
}

//===================================================
// NAME: hideElement(elementId)
// PARAM: an elements ID
// RESULT: element with that ID is hidden
//===================================================
function hideElement(elementId) {
  if (document.getElementById(elementId)) {
    document.getElementById(elementId).style.display = tsText.styleDisplayNone;
  }
  return;
}

//===================================================
// NAME: todaysScoresDisplayAllScores()
// PARAM: an elements id
// RESULT: hidden element with given ID is displayed
//===================================================
function todaysScoresDisplayAllScores() {
  // construct the element ID
  var leagueContainerId;
  var leagueScoresContainerId;
  var leagueScoresToggleId;
  for (var i=0; i<tsLeagueNames.length; i++) {
    leagueContainerId       = tsElementIds.leagueContainer        + tsLeagueNames[i];
    leagueScoresContainerId = tsElementIds.leagueScoresContainer  + tsLeagueNames[i];
    leagueScoresToggleId    = tsElementIds.leagueScoresToggle     + tsLeagueNames[i];
    // unhide DIV containing all data for a league
    displayElement(leagueContainerId);
    // unhide DIV containing the leagues box scores
    displayElement(leagueScoresContainerId);
    // expand DIV to ensure we display box scores
    todaysScoresToggleScoresOpen(tsLeagueNames[i]);
  }
  tsAppState.userSelectedLeague = undefined;
  return;
}

//===================================================
// todaysScoresDisplayLeague(league)
// PARAMS: league
// PURPOSE: displays the league selected by the user
//   and hides all other leagues
// OUTCOME: page will display ONLY the selected league
//===================================================
function todaysScoresDisplayLeague(league) {
  var leagueContainerId  = tsElementIds.leagueContainer + league;
  var otherLeagueSectionId;

  for (var i=0;i<tsLeagueNames.length;i++) {
    otherLeagueSectionId = tsElementIds.leagueContainer + tsLeagueNames[i];
    if (document.getElementById(otherLeagueSectionId)) {
      document.getElementById(otherLeagueSectionId).style.display = tsText.styleDisplayNone;
    }
  }
  if (document.getElementById(leagueContainerId)) {
    document.getElementById(leagueContainerId).style.display = tsText.styleDisplayBlock;
    todaysScoresToggleScoresOpen(league);
    tsAppState.userSelectedLeague = league;
  } else {
    todaysScoresDisplayAllScores();
  }
  return;
}

//===================================================
// todaysScoresToggleScores(league)
// PARAMS: league
// PURPOSE: collapses or expands scores for given league
// OUTCOME: league section and header will remain visible
//   to user. Scores for the league will display if
//   they are hidden; Score will be hidden for
//   league if they are visible
//===================================================
function todaysScoresToggleScores(league) {
  var leagueScoresContainerId = tsElementIds.leagueScoresContainer + league;
  var leagueScoresToggleId = tsElementIds.leagueScoresToggle + league;

  if (document.getElementById(leagueScoresContainerId)) {
    var element = document.getElementById(leagueScoresContainerId);
    if (element.style.display == tsText.styleDisplayNone) {
      element.style.display = tsText.styleDisplayBlock;
      if (tsAppState.lang == tsText.langSpanish)
           {document.getElementById(leagueScoresToggleId).innerHTML = tsText.closeSpanish;}
      else {document.getElementById(leagueScoresToggleId).innerHTML = tsText.closeEnglish;}
      for (var i=0; i < tsAppState.collapsedLeagues.length; i++) {
        if (tsAppState.collapsedLeagues[i] == league) {
          delete tsAppState.collapsedLeagues[i];
        }
      }
    }
    else if (element.style.display == tsText.styleDisplayBlock) {
      element.style.display = tsText.styleDisplayNone;
      if (tsAppState.lang == tsText.langSpanish)
           {document.getElementById(leagueScoresToggleId).innerHTML = tsText.expandSpanish;}
      else {document.getElementById(leagueScoresToggleId).innerHTML = tsText.expandEnglish;}
      tsAppState.collapsedLeagues.push(league);
    }
    else {
      element.style.display = tsText.styleDisplayBlock;
      if (tsAppState.lang == tsText.langSpanish)
           {document.getElementById(leagueScoresToggleId).innerHTML = tsText.closeSpanish;}
      else {document.getElementById(leagueScoresToggleId).innerHTML = tsText.closeEnglish;}
      for (var i=0; i < tsAppState.collapsedLeagues.length; i++) {
        if (tsAppState.collapsedLeagues[i] == league) {
          delete tsAppState.collapsedLeagues[i];
        }
      }
    }
  }
  return;
}

//===================================================
// todaysScoresToggleScoresOpen(league)
// PARAMS: league
// PURPOSE: expands scores for given league
// OUTCOME: Scores for the league will display
//===================================================
function todaysScoresToggleScoresOpen(league) {
  var elementId      = tsElementIds.leagueScoresToggle + league;
  var leagueScoresContainerId = tsElementIds.leagueScoresContainer + league;

  if (document.getElementById(leagueScoresContainerId)) {
    displayElement(leagueScoresContainerId);
    if (document.getElementById(elementId)) {
      var element = document.getElementById(elementId);
      if (tsAppState.lang == tsText.langSpanish)
           {element.innerHTML = tsText.closeSpanish;}
      else {element.innerHTML = tsText.closeEnglish;}
    }
  }
  return;
}


//===================================================
// todaysScoresToggleScoresClose(league)
// PARAMS: league
// PURPOSE: collapses scores for given league
// OUTCOME: Scores for the league will collapse
//===================================================
function todaysScoresToggleScoresClose(league) {
  var leagueScoresToggleId = tsElementIds.leagueScoresToggle + league;
  var leagueScoresContainerId = tsElementIds.leagueScoresContainer + league;

  if (document.getElementById(leagueScoresContainerId)) {
    hideElement(leagueScoresContainerId);
    if (document.getElementById(leagueScoresToggleId)) {
      var leagueScoresToggle = document.getElementById(leagueScoresToggleId);
      if (tsAppState.lang == tsText.langSpanish)
           {leagueScoresToggle.innerHTML = tsText.closeSpanish;}
      else {leagueScoresToggle.innerHTML = tsText.closeEnglish;}
    }
  }
  return;
}


//===================================================
// todaysScoresToggleView()
// PURPOSE: toggles between displaying either boxscores for
//          all matches OR stats for all matches.
// OUTCOME: page will display the alternative view from
//          the one currently seen on the page
//===================================================
function todaysScoresToggleView() {
  var boxScoreTableElementId;
  var matchStatsTableElementId;
  if (tsAppState.pageViewType == tsText.pageViewBoxScore) {
    for (var i=0; i < tsMatchGameIds.length; i++) {
      boxScoreTableElementId   = tsElementIds.boxScoreTable   + tsMatchGameIds[i];
      matchStatsTableElementId = tsElementIds.matchStatsTable + tsMatchGameIds[i];
      if (document.getElementById(boxScoreTableElementId) && document.getElementById(matchStatsTableElementId)) {
        document.getElementById(boxScoreTableElementId).style.display   = tsText.styleDisplayNone;
        document.getElementById(matchStatsTableElementId).style.display = tsText.styleDisplayBlock;
      }
    }
    if (tsAppState.lang == tsText.langSpanish)
         {document.getElementById(tsElementIds.pageViewToggle).innerHTML = tsText.displayBoxScoreSpanish;}
    else {document.getElementById(tsElementIds.pageViewToggle).innerHTML = tsText.displayBoxScoreEnglish;}
    tsAppState.pageViewType = tsText.pageViewMatchStats;
  }
  else {
    for (i=0; i < tsMatchGameIds.length; i++) {
      boxScoreTableElementId   = tsElementIds.boxScoreTable   + tsMatchGameIds[i];
      matchStatsTableElementId = tsElementIds.matchStatsTable + tsMatchGameIds[i];
      if (document.getElementById(boxScoreTableElementId) && document.getElementById(matchStatsTableElementId)) {
        document.getElementById(boxScoreTableElementId).style.display   = tsText.styleDisplayBlock;
        document.getElementById(matchStatsTableElementId).style.display = tsText.styleDisplayNone;
      }
    }
    if (tsAppState.lang == tsText.langSpanish)
         {document.getElementById(tsElementIds.pageViewToggle).innerHTML = tsText.displayStatsSpanish;}
    else {document.getElementById(tsElementIds.pageViewToggle).innerHTML = tsText.displayStatsEnglish;}
    tsAppState.pageViewType = tsText.pageViewBoxScore;
  }
  return;
}

//===================================================
// todaysScoresGetScores(YYYYMMDD)
// PARAMS: (1) takes a date value in YYYYMMDD format
// RESULT: checks to see if the specified date is
//         is todays to choose what nugget to call
//===================================================
function todaysScoresGetScores(YYYYMMDD) {
  tsAppState.matchDate          = (YYYYMMDD || tsAppState.matchDate);
  tsAppState.matchDateYesterday = todaysScoresGetYesterdaysDate(YYYYMMDD);
  tsAppState.matchDateTomorrow  = todaysScoresGetTomorrowsDate(YYYYMMDD);
  //alert("YYYYMMDD: " + YYYYMMDD);
  //alert("tsAppState.matchDate: " + tsAppState.matchDate);
  // get todays scores
  if (YYYYMMDD == tsAppState.todaysDate) {
    _getRefreshedTodaysScores()
  } else {
    tsAppState.autoRefreshOn = false;
    _getFutureFinalScores()
  }
  return;
}


//===================================================
// todaysScoresGetTomorrowsDate(YYYYMMDD)
//===================================================
function todaysScoresGetTomorrowsDate(YYYYMMDD) {
  var tsDateObj = new Date(YYYYMMDD.substring(0,4), (YYYYMMDD.substring(4,6) - 1), YYYYMMDD.substring(6,8));
  return tsDateObj.clone().add(1).days().toString("yyyyMMdd");
}

//===================================================
// todaysScoresGetYesterdaysDate(YYYYMMDD)
//===================================================
function todaysScoresGetYesterdaysDate(YYYYMMDD) {
  var tsDateObj = new Date(YYYYMMDD.substring(0,4), (YYYYMMDD.substring(4,6) - 1), YYYYMMDD.substring(6,8));
  return tsDateObj.clone().add(-1).days().toString("yyyyMMdd");
}


//------------------------------------------------------------
// todaysScoresInitialize()
// PURPOSE: sets required values when application is first loaded
//------------------------------------------------------------
function todaysScoresInitialize(tsiSite, tsiLang, tsiTimeOffset,tsiTodaysDate) {
  if (tsiSite == undefined || tsiLang == undefined || tsiTimeOffset == undefined) {
    // add some handling here
  }
  else {
    tsAppState.pageViewType = _todaysScoresInitializeViewType();
    tsAppState.pageViewType = tsText.pageViewBoxScore;
    tsAppState.site         = tsiSite;
    tsAppState.lang         = tsiLang;
    tsAppState.timeOffset   = tsiTimeOffset;
    tsAppState.todaysDate   = tsiTodaysDate;
    tsAppState.matchDate    = tsiTodaysDate;
    tsAppState.matchDateYesterday = todaysScoresGetYesterdaysDate(tsAppState.matchDate);
    tsAppState.matchDateTomorrow  = todaysScoresGetTomorrowsDate(tsAppState.matchDate);
    _todaysScoresAdjustDateText(tsAppState.matchDate,tsAppState.lang);
    _todaysScoresAutoRefresh();
  }
}


// ||||||||||| intialize, private, and reload functions ||||||||||||||||||||||||


//===================================================
// adjust date text when clicking either left/right arrow.
//===================================================
function _todaysScoresAdjustDateText(YYYYMMDD,tsLang) {
  var tsDateObj = new Date(YYYYMMDD.substring(0,4), (YYYYMMDD.substring(4,6) - 1), YYYYMMDD.substring(6,8));
  document.getElementById("todaysScoresTodaysDate").innerHTML     = _dateUtilsFormatDateTextHeader(YYYYMMDD,tsLang);
  //document.getElementById("todaysScoresYesterdaysDate").innerHTML = _dateUtilsFormatDateTextHeader(todaysScoresGetYesterdaysDate(YYYYMMDD),tsLang);
  //document.getElementById("todaysScoresTomorrowsDate").innerHTML  = _dateUtilsFormatDateTextHeader(todaysScoresGetTomorrowsDate(YYYYMMDD),tsLang);
  return;
}

//------------------------------------
// _getRefreshedTodaysScores()
// 10000 = 10secs
//------------------------------------
function _getRefreshedTodaysScores() {
  var xmlHttp = getXmlHttpObject();
  var params = tsAppState.site +"_"+ tsAppState.lang +"_"+ tsAppState.timeOffset;
  var url    = tsUrls.liveScores + params;

  xmlHttp.onreadystatechange=function(){
     if(xmlHttp.readyState==4){
      var xmlDocResult = xmlHttp.responseText;
      document.getElementById(tsElementIds.pageContainer).innerHTML = xmlDocResult;
      // temp auto turn on
      tsAppState.autoRefreshOn = true;
      if (tsAppState.autoRefreshOn) { _todaysScoresAutoRefresh(); }
      _todaysScoresAdjustDateText(tsAppState.matchDate,tsAppState.lang);
      _todaysScoresCheckState();
      _todaysScoresReloadMsnAd();
     }
    }
  xmlHttp.open("GET",url,true);
  xmlHttp.send(null);
}


//------------------------------------
// _getFutureFinalScores()
// /nugget/FSITodaysScoresFutureFinal_<site>_<lang>_<offset>_yyyymmdd
// /nugget/FSITodaysScoresFutureFinal_foxsoccer_en_0_20090605
//------------------------------------
function _getFutureFinalScores() {
  var xmlHttp = getXmlHttpObject();
  var params  = tsAppState.site +"_"+ tsAppState.lang +"_"+ tsAppState.timeOffset +"_"+ tsAppState.matchDate;
  var url     = tsUrls.futureFinalScores + params;
  xmlHttp.onreadystatechange=function(){
     if(xmlHttp.readyState==4){
      var xmlDocResult = xmlHttp.responseText;
      _todaysScoresCancelAutoRefresh();
      document.getElementById(tsElementIds.pageContainer).innerHTML = xmlDocResult;
      _todaysScoresAdjustDateText(tsAppState.matchDate,tsAppState.lang);
      tsAppState.autoRefreshOn = false;
      //_todaysScoresCheckState();
      _todaysScoresReloadMsnAd();
     }
    }
  xmlHttp.open("GET",url,true);
  xmlHttp.send(null);
}

//------------------------------------
// _todaysScoresAutoRefresh()
// 10000 = 10secs
//------------------------------------
var tsScoresRefreshTimer;
function _todaysScoresAutoRefresh() {
  tsScoresRefreshTimer = setTimeout("_getRefreshedTodaysScores()",60000);
}

//------------------------------------
// _todaysScoresCancelAutoRefresh()
//------------------------------------
function _todaysScoresCancelAutoRefresh() {
  clearTimeout(tsScoresRefreshTimer);
}


//------------------------------------------------------------
// _todaysScoresReloadAd()
//------------------------------------------------------------
function _todaysScoresReloadMsnAd() {
  dapMgr.trackEvent(eventType.click);
}

var tsReloadMsnAds = window.setInterval('_todaysScoresReloadMsnAd()', 60000);

//------------------------------------------------------------
// _todaysScoresInitializeViewType()
// creates a closure ensuring the Todays Scores tsPageViewType is
// 1) allows set and 2) only set to one of the predefined types
//------------------------------------------------------------
function _todaysScoresInitializeViewType() {
  var allowedTypes=new Array();
  allowedTypes['boxscore']   = 1;
  allowedTypes['matchstats'] = 2;
  var viewType="boxscore";
  return function(vtype) {
    viewType = allowedTypes[vtype] ? vtype : viewType;
    return viewType;
  };
}

//===================================================
// _todaysScoresRestoreState()
// PURPOSE: checks tsCollapsedLeagues and tsUserSelectedLeague
//  for defined values. If defined we assume application is in use.
//  If not defined we assume application first load and do nothing.
// RESULT: if first load application will be intialized.
//  if application is in use the state prior to page reload
//  will be restored
//===================================================
function _todaysScoresRestoreState() {
  // check page view type
  if (tsAppState.pageViewType == undefined) {
    // we should never get here!!
    tsAppState.pageViewType = tsInitializeViewType();
    tsAppState.pageViewType = tsText.pageViewBoxScore;
  }
  else {
    if (tsAppState.pageViewType == tsText.pageViewBoxScore)
         {tsAppState.pageViewType = tsText.pageViewMatchStats;}
    else {tsAppState.pageViewType = tsText.pageViewBoxScore;}
    todaysScoresToggleView();
  }
  // check for display of a single league
  if (tsAppState.userSelectedLeague == undefined)
       {todaysScoresDisplayAllScores();}
  else {todaysScoresDisplayLeague(tsAppState.userSelectedLeague);}
  // check for collapsed league scores
  if (tsAppState.collapsedLeagues.length == 0)
       {tsAppState.collapsedLeagues = [];}
  else {
    for (var i=0; i < tsAppState.collapsedLeagues.length; i++) {
      todaysScoresToggleScoresClose(tsAppState.collapsedLeagues[i]);
    }
  }
}

//------------------------------------------------------------
// _todaysScoresCheckState()
// checks tsCollapsedLeagues and tsUserSelectedLeague for defined
// values. If defined we assume application is in use. If not
// defined we assume a first load for the application thought
// it mat be the user hasn't made any selections
//------------------------------------------------------------
function _todaysScoresCheckState() {
  if (tsAppState.collapsedLeagues.length == 0 && tsAppState.userSelectedLeague == undefined)
       {return;}
  else {_todaysScoresRestoreState();}
}

