//=================================================================================================
// mainUI.js
// (c) 2012 Robot Entertainment
//=================================================================================================

var cLayoutSmall = 0;
var cLayoutMedium = 1;
var cLayoutLarge = 2;
var cNumLeaderboardSlots = 20;

//=================================================================================================
function updateGameEntry(entryID, lastMoveText, creationTimeText, unreadChats, homeColor, colorIndex, opponentAvatarColor)
{
   var entrySelect = '#' + entryID;
   // [6/21/12 Xemu] for these time based strings, update them to their new values
   $(entrySelect + '-LastMoveText').html(lastMoveText);
   $(entrySelect + '-CreationTimeText').html(creationTimeText);

   // [6/21/12 Xemu] chat badge is a little trickier since we might need to reveal or hide existing
   var unreadChatVal = unreadChats;
   if (unreadChatVal > 9)
      unreadChatVal = '9+';
   $(entrySelect + '-ChatBadge').html(unreadChatVal);
   if (unreadChats == 0)
   {
      $(entrySelect + '-ChatBadge').hide();
      // [6/21/12 Xemu] also repaint the HTML5 canvas that we overlap, because the world is filled with pain & disappointment
   }
   else
   {
      //alert(entrySelect + " unread " + unreadChats);
      $(entrySelect + '-ChatBadge').show();
   }

   var colorize = cef.uiapp.getAvatarColorize();
   if (colorize)
      colorizeAvatar(homeColor, colorIndex, 'BaseAvatar' + entryID, 'ColorAvatar' + entryID, opponentAvatarColor);
}

//=================================================================================================
function removeById(id) {
  var element = document.getElementById(id);

  // A bit of robustness helps...
  if (element && element.parentNode) {
    element.parentNode.removeChild(element);
  }
}

//=================================================================================================
function purgeEntry(entryName)
{
   // @TODO - modularize this out
   if ($('#'+ entryName).length)
   {
      //alert('purge waiting ' + gameID);
      removeById(entryName);
   }
}

//=================================================================================================
function purgeGamesList()
{
   $('#YourTurnText').html(cef.uiapp.locString('YOUR TURN'));
   $('#GameListActive').empty();
   $('#GameListWaiting').empty();
   $('#GameListCompleted').empty();
}

//=================================================================================================
function purgeGameFromAll(gameID)
{
   // [7/20/12 xemu] there's a webkit bug where if you shrink a scrollable list while scrolled, it crashes.  :(
   $('#gameslist').scrollTop(0);

   purgeEntry('ActiveEntry' + gameID);
   purgeEntry('WaitingEntry' + gameID);
   purgeEntry('CompletedEntry' + gameID);
}

//=================================================================================================
function checkGameEntryStatus(gameID, entryRoot)
{
   entryID = '#' + entryRoot + gameID;
   if ($(entryID).length)
      return true;

   return false;   
}

//=================================================================================================
function selectGameIfNotActive(gameID)
{
   if (checkGameEntryStatus(gameID, 'WaitingEntry') || checkGameEntryStatus(gameID, 'CompletedEntry'))
   {
      gameRefresh(gameID);
   }
}

//=================================================================================================
function addGameEntry(gameID, opponentName, opponentAvatar, opponentAvatarColor, statusCode, lastMoveText, creationTimeText, teamIcon1, teamIcon2, lastEntry, homeColor, colorIndex, unreadChats)
{
   var layout = cef.uiapp.getLayoutMode();

   var extraClass = '';
   var statusClass = '';
   var entrySelect = '';
   var entryID = '';

   var upArt = 'GameList-Up_Lge.png';
   var downArt = 'GameList-Dn_Lge.png';

   if(layout == cLayoutMedium)
   {
      upArt = 'GameList-Up_Med.png';
      downArt = 'GameList-Dn_Med.png';
   }

   if (statusCode == 1)
   {
      // See if we already have an entry for this game in this category
      entryID = 'ActiveEntry' + gameID;
      entrySelect = '#' + entryID;
      purgeEntry('WaitingEntry' + gameID);
      if ($(entrySelect).length)
      {
         // we should still update the time text, etc
         updateGameEntry(entryID, lastMoveText, creationTimeText, unreadChats, homeColor, colorIndex, opponentAvatarColor );
         return;
      }

      statusClass = ' activeEntry';
      var count = $("#GameListActive div").length;
      if (count == 0)
      {
         extraClass = ' topEntry';
      }
   }
   else if (statusCode == 2)
   {
      entryID = 'WaitingEntry' + gameID;
      entrySelect = '#' + entryID;
      purgeEntry('ActiveEntry' + gameID);
      if ($(entrySelect).length)
      {
         // we should still update the time text, etc
         updateGameEntry(entryID, lastMoveText, creationTimeText, unreadChats, homeColor, colorIndex, opponentAvatarColor);
         return;
      }

      statusClass = ' waitingEntry';
      var count = $("#GameListWaiting div").length;
      if (count == 0)
      {
         extraClass = ' topEntry';
      }
   }
   // resigned / unknown
   else if ((statusCode == 3) || (statusCode == 4))
   {
      entryID = 'CompletedEntry' + gameID;
      entrySelect = '#' + entryID;
      purgeEntry('WaitingEntry' + gameID);
      purgeEntry('ActiveEntry' + gameID);
      if ($(entrySelect).length)
      {
         // we should still update the time text, etc
         updateGameEntry(entryID, lastMoveText, creationTimeText, unreadChats, homeColor, colorIndex, opponentAvatarColor);
         return;
      }
   }

   if (lastEntry)
   {
      extraClass += ' bottomEntry';
   }

   var emblemSize = 39;
   var emblemOffsetX = 12;
   var emblemOffsetY = 12;
   var emblemRightOffset = 53;
   var vsPosX = 54;
   var vsPosY = 0;
   var namePosX = 89;
   var namePosY = -6;
   var lastMoveX = 8;
   var lastMoveY = 40;
   layout = cef.uiapp.getLayoutMode();
   if (layout == cLayoutMedium)
   {
      emblemSize = 32;
      emblemOffsetX = 7;
      emblemOffsetY = 5;
      emblemRightOffset = 0;
      vsPosX = 41;
      vsPosY = -12;
      namePosX = 76;
      namePosY = -17;
      lastMoveX = 107;
      lastMoveY = 17;
   }

   var colorize = cef.uiapp.getAvatarColorize();

   //alert("EID " + entryID);
   var startDiv = '<div class=\"gameEntry' + statusClass + extraClass + '\" id=\"' + entryID + '\">';
   var leftIconSrc = '<img src=\"heroacademy://data/' + teamIcon1 + '\" style=\"position:absolute; left:' + emblemOffsetX.toString() + 'px; top:' + emblemOffsetY.toString()+'px; width:'+ emblemSize.toString() + 'px;height:' + emblemSize.toString() + 'px;z-index:1\">';
   //var vsBanner = '<img src=\"vsBanner.png\" style=\"position:relative; left:4; bottom:8; z-index:0;\">';
   var vsBanner = '<p style=\"z-index:2; position:absolute; top:' + vsPosY.toString() + 'px; left:' + vsPosX.toString() + 'px;\" class=\"gameTextMedium\">' + cef.uiapp.locString('vs') + '</p>';
   var rightIconSrc = '<img src=\"heroacademy://data/' + teamIcon2 + '\" style=\"position:absolute; right:' + (emblemOffsetX + emblemRightOffset).toString() + 'px; top:' + emblemOffsetY.toString() + 'px; width:' + emblemSize.toString() + 'px;height:' + emblemSize.toString() + 'px; z-index:1;\">';
   var avatarSrc = '<img id=\"BaseAvatar' + entryID + '\" src=\"heroacademy://data/' + opponentAvatar + '\" style=\"position:absolute; top:9px; right:10px; width:53; height:53; z-index:1; -webkit-transform: scale(-1, 1);\">';
   var avatarColorSrc = '';
   if (colorize)
      avatarColorSrc = "<canvas id='ColorAvatar" + entryID + "' style=\"position:absolute; border-style:none; top:9px; right:10px; z-index:1; -webkit-transform: scale(-1, 1);\" width=\"53\" height=\"53\" ></canvas>";
   var nameDiv = '<div><p style=\"z-index:2; position:absolute; left:' + namePosX.toString() + 'px; top:' + namePosY.toString() + 'px;\" class=\"gameTextName\" id=\"' + entryID + '-Text\" >' + opponentName + '</p></div>';
   var fontText = '';
   if (cef.uiapp.getSmallGameDetailText())
      fontText = 'font-size:11px;';
   var lastMoveSrc = '<p style=\"z-index:2; position:absolute;' + fontText + 'top:' + lastMoveY.toString() + 'px; left:' + lastMoveX.toString() + 'px;\" class=\"gameTextSmall\" id=\"' + entryID + '-LastMoveText\" >' + lastMoveText + '</p>';
   var creationTimeSrc = '<p style=\"z-index:2; position:absolute;' + fontText + 'top:40; left:80; width:186; text-align:right;\" class=\"gameTextSmall\" id=\"' + entryID + '-CreationTimeText\">' + creationTimeText + '</p>';
   var unreadChatVal = unreadChats;
   if (unreadChatVal > 9)
      unreadChatVal = '9+';
   var unreadChatMarker = '<p style=\"z-index:2; position:absolute; right:4px; bottom:4px; width:18px; height:18px; text-align:center; background:url(\'heroacademy://data/NewChatsBadge-hd.png\') transparent no-repeat; background-size:100%\" class=\"unreadChatBadgeText\" id=\"' + entryID + '-ChatBadge\">' + unreadChatVal + '</p>';
   var endDiv = '</div>';

   if (layout == cLayoutMedium)
   {
      creationTimeSrc = "";
      avatarSrc = "";
      avatarColorSrc = "";
   }

   //alert("game" + gameID + " " + entryID);
   if (statusCode == 1)
   {
      $(GameListActive).append(startDiv + leftIconSrc + vsBanner + rightIconSrc + avatarSrc + avatarColorSrc + nameDiv + lastMoveSrc + creationTimeSrc + unreadChatMarker +  endDiv);
   }
   else if (statusCode == 2)
   {
      $(GameListWaiting).prepend(startDiv + leftIconSrc + vsBanner + rightIconSrc + avatarSrc + avatarColorSrc + nameDiv + lastMoveSrc + creationTimeSrc + unreadChatMarker + endDiv);
   }
   else if ((statusCode == 3) || (statusCode == 4))
   {
      $(GameListCompleted).prepend(startDiv + leftIconSrc + vsBanner + rightIconSrc + avatarSrc + avatarColorSrc + nameDiv + lastMoveSrc + creationTimeSrc + unreadChatMarker + endDiv);
   }
   if (colorize)
      colorizeAvatar(homeColor, colorIndex, 'BaseAvatar' + entryID, 'ColorAvatar' + entryID, opponentAvatarColor);

   // [6/21/12] Xemu - if we have no chats, hide the badge element
   if (unreadChats == 0)
      $(entrySelect + '-ChatBadge').hide();

   if (gameID == cef.uiapp.getCurrentGame())
   {
      showCurrentGameEntry(entryID);
   }

   if(layout == cLayoutMedium)
   {
      fixupButtonSubtext(entryID, entryID + '-Text', -25, -20, 30, 25, downArt, upArt, function ()
      {
         gameClick(gameID.toString(), true);
         showCurrentGameEntry(entryID);
      });
   }
   else if(layout == cLayoutLarge)
   {
      fixupButtonSubtext(entryID, entryID + '-Text', -18, -6, 35, 25, downArt, upArt, function ()
      {
         gameClick(gameID.toString(), true);
         showCurrentGameEntry(entryID);
      });
   }

}

//=================================================================================================
function addCreateEntry()
{
   if ($('#EntryCreate').length)
      return;

   var buttonID = "EntryCreate";
   var buttonClass = "createGameEntry";
   var displayText = cef.uiapp.locString("Start a Game!");
   buttonText1 = "<div id=\"" + buttonID + "\"  class=\"" + buttonClass + "\"  >";
   //buttonText2 = "<p style=\"width:265px; position:absolute;left:64px;top:8px;line-height:55px;\" id=\"EntryCreate-Text\" class=\"createGameEntryText\">" + displayText + "</p>";
   //buttonText2 = "<p style=\"\" id=\"EntryCreate-Text\" class=\"createGameEntryText\">" + displayText + "</p>";
   buttonText2 = "<span class=\"createGameEntryText\">" + displayText + "</span>";
   //buttonText2 = displayText;
   buttonText3 = "</div>";

/*
   layout = cef.uiapp.getLayoutMode();
   if (layout == 1)
      nameDiv = '<div style=\"\"><p style=\"z-index:2; position:absolute; left:0px; top:0px;\" class=\"navMenuText\">' + opponentName + '</p></div>';
   else
      nameDiv = '<div style=\"\"><p style=\"z-index:2; position:absolute; left:91; top:-6;text-align:left;width:300;\" class=\"gameTextFixed\">' + opponentName + '</p></div>';
*/
   //var avatarSrc = '<img src=\"heroacademy://data/' + opponentAvatar + '\" style=\"position:absolute; top:8;right:12;width:54; height:54;; z-index:1;\">';
   //var endDiv = '</div>';
   $(GameListActive).append(buttonText1 + buttonText2 + buttonText3); // startDiv + nameDiv + endDiv);

   if(layout == cLayoutMedium)
   {
      var downArt = "GameList-Top-Dn_Med.png";
      var upArt = "GameList-Top-Up_Med.png";
      //fixupButtonSubtext('EntryCreate', 'EntryCreate-Text', '60px', '45px', downArt, upArt, function ()
      fixupButton('EntryCreate',  40, 35, downArt, upArt, function ()
      {
         navigateTo('GamesList_CreateGame');
      }, 228, 220);
   }
   else if(layout == cLayoutLarge)
   {
      var downArt = "GameList-Top-Dn_Lge.png";
      var upArt = "GameList-Top-Up_Lge.png";
      //fixupButtonSubtext('EntryCreate', 'EntryCreate-Text', '60px', '45px', downArt, upArt, function ()
      fixupButton('EntryCreate',  60, 45, downArt, upArt, function ()
      {
         navigateTo('GamesList_CreateGame');
      }, 288, 280);
   }
   
   overrideStyleByLayoutType();
}

//=================================================================================================
function gameRefresh(gameID)
{
   cef.uiapp.reloadGame(gameID);
}

//=================================================================================================
function gameClick(gameID, showLoadingOverlay)
{
   //alert("game ID " + gameID);
   cef.uiapp.selectGame(gameID, showLoadingOverlay);

   $('#GameBoard').show();
   cef.uiapp.showGameView();

}

//=================================================================================================
function showCurrentGameEntryByGameID(gameID)
{
   showGameEntryIfVisible('ActiveEntry' + gameID);
   showGameEntryIfVisible('WaitingEntry' + gameID);
   showGameEntryIfVisible('CompletedEntry' + gameID);
}

//=================================================================================================
function showGameEntryIfVisible(entryID)
{
   if ($('#' + entryID).is(":visible"))
   {
      showCurrentGameEntry(entryID);
   }
}

//=================================================================================================
function showCurrentGameEntry(entryID)
{
   //alert("CURRENT " + entryID);
   // remove any existing game entry
   removeById('CurrentGameOverlay');

   layout = cef.uiapp.getLayoutMode();

   var width = 336;
   var height = 68;
   if (layout == cLayoutMedium)
   {
      width = 280;
      height = 45;
   }

   var overlay = '<img src=\"heroacademy://data/UI/BarButtonSelect.png\" style=\"position:absolute; top:0px; left:0px; z-index:3; width:' + width.toString() + 'px; height:' + height.toString() + 'px;\" id=\"CurrentGameOverlay\">';
   $('#' + entryID).append(overlay);
}

//=================================================================================================
function showCurrentPuzzleEntry(entryID) {
   // remove any existing game entry
   removeById('CurrentPuzzleOverlay');

   layout = cef.uiapp.getLayoutMode();

   var width = 338;
   var height = 64;
   if (layout == cLayoutMedium) {
      width = 278;
      height = 55;
   }

   // get the parent and force a coordinate system on it by making its position relative (can't inherit xform of static)
   $('#' + entryID).css("position", "relative");
   var overlay = '<img src=\"heroacademy://data/UI/BarButtonSelect.png\" style=\"position:absolute; top:0px; left:0px; z-index:3; width:' + width.toString() + 'px; height:' + height.toString() + 'px;\" id=\"CurrentPuzzleOverlay\">';
   $('#' + entryID).append(overlay);
}

//=================================================================================================
function hideBoardElements()
{
   // need a better system here...
   // [8/6/12 xemu] indeed we do.  refactored this out so we can call it in a lighter form when changing between games
   hideBoardOverlays();
   $(ChatForm).hide();

   removeById('CurrentGameOverlay');
   removeById('CurrentPuzzleOverlay');

   hideAllLoginUI();
   cef.uiapp.hideGameView();
   cef.uiapp.enableGamesList(false);
}

//=================================================================================================
function hideBoardOverlays()
{
   $('#TeamSelect').hide();
   $('#GameBoard').hide();
   $('#HomeScreen').hide();
   $('#NewsPage').hide();
   $('#FramePage').hide();
   $('#Customize').hide();
   $('#Training').hide();
   $('#TeamDetails').hide();
   $('#GamesListScreen').hide();
   $('#CustomizeColors').hide();
   $('#CustomizeAvatars').hide();
   $('#Challenges').hide();
   $('#Leaderboards').hide();
}

//=================================================================================================
function clearGameEntries()
{
   //alert("CGE");
   $(GameListActive).empty();
   $(GameListWaiting).empty();
}

//=================================================================================================
function retrieveText(id)
{
   var txtbox = document.getElementById(id);
   var value = txtbox.value;
   return value;
}

//=================================================================================================
function showTeamSelect(gameID, opponent, matchmake)
{
   rematch = false;
   if (gameID == '0')
   {
      if (opponent == '')
      {
         opponent = $('#CreateGameOpponentName').val(); //Should be the fetched username not the email address you might enter
      }
      else
      {
         rematch = true;
      }
      //alert("bind decline");
      bindButton("TeamSelectDeclineGame", "clearNavEntries(); assembleBreadcrumbs('GamesList'); navigateToGamesList(); ");
      $("#TeamSelectCreateGame").html(cef.uiapp.locString("Create!"));
      $("#TeamSelectDeclineGame").html(cef.uiapp.locString("Cancel"));
      $("#CreateGameTitleBarText").html(cef.uiapp.locString("Create Game"));
   }
   else
   {
      // [5/17/12 xemu] note fullwise that if we have a gameID set, that means we are accepting someone else's invite
      //   which has a few different functionality implications.
      var bindCmd = "cef.uiapp.declineGame('" + gameID + "'); navigateToGamesList();";

      $("#TeamSelectCreateGame").html(cef.uiapp.locString("Accept!"));
      $("#TeamSelectDeclineGame").html(cef.uiapp.locString("Decline"));
      $("#CreateGameTitleBarText").html(cef.uiapp.locString("Accept Game"));
      //alert(bindCmd);
      bindButton("TeamSelectDeclineGame", bindCmd);
   }

   // [5/18/12 xemu] disable the create button, it gets re-enabled by team selection
   $('#TeamSelectCreateGame').css("background", "url('heroacademy://UI/AccountGreenButton-Dn.png') transparent no-repeat");
   clearButton('TeamSelectCreateGame');
   //alert("disable?");


   hideBoardElements();
   clearChat();

   // [4/20/12] @TODO - handle bad username better
   cef.uiapp.populateTeamSelect(opponent, gameID, matchmake, rematch);

   //alert("Teamselect vs " + opponent);

   currentLoginUI = '#TeamSelect';
   $('#TeamSelect').show();
}

//=================================================================================================
function teamSelectTeamClicked(teamName, teamInvID, teamPickButton)
{
   onPurchase = "$('#" + teamName + "BuyStar').hide();";
   if(cef.uiapp.doesOwnTeam(teamName) || (teamName == "random"))
   {
      eval(onPurchase);
      setRosterSelection(teamName);
   }
   else
   {
      upsellDLC(teamInvID, onPurchase);
   }
}

//=================================================================================================
function addToTeamSelectRoster(owned, teamName, teamInvID, teamDisplay, teamEmblem, gridX, gridY)
{
   //alert(owned + " , " + teamName);
   var layout = cef.uiapp.getLayoutMode();
   if(layout == cLayoutMedium)
   {
      rosterWidth = 222;
      rosterHeight = 156;
   }
   else if(layout == cLayoutLarge)
   {
      rosterWidth = 222;
      rosterHeight = 172;
   }
   leftPos = gridX * rosterWidth;
   topPos = gridY * rosterHeight;
   startDiv = "<div style=\"position:absolute; border-width:1px; border-style:solid; border-color:red; left:" + leftPos + "px; top:" + topPos + "px; width:" + rosterWidth + "px; height:" + rosterHeight + "px;  border-style:none;\">";
   teamLabel = "<label class=\"teamName\" style=\"position:absolute; top:0px; left:0px; width:192px; height:32px; padding:0px; border-style:none; text-align:center; vertical-align:top;\">" + teamDisplay + "</label>";

   var teamPickButton = "TeamSelect_" + teamName;
   clickCmd = "teamSelectTeamClicked('" + teamName + "', '" + teamInvID + "', '" + teamPickButton + "');";

   teamSelectImage = "<img src=\"heroacademy://UI/SelectTeamGlow.png\" style=\"background:transparent no-repeat; width:202px; height:202px; position:absolute; top:-14px; left:0px;background-size:100%;display:none;\" " +
      "class=\"teamSelectImage\" id=\"teamSelect" + teamName + "\" />";
   teamImage = "<div style=\"background:url('" + teamEmblem + "') transparent no-repeat; background-size:100%; width:102px; height:102px; position:absolute; top:36px; left:50px;cursor:pointer;\" onclick=\"" + clickCmd + "\" id=\"" + teamPickButton + "\" />";
   teamTooltipButton = "";
   var helpButtonID = "HelpButton_" + teamName;
   if (teamName != "random")
   {
      helpClickCmd = "showTeamDetails('" + teamName + "'); addTeamHelpBackButton('TeamSelect', false);";
      teamTooltipButton = "<img id=\"" + helpButtonID + "\" src=\"heroacademy://data/UI_Tooltip.png\" style=\"background-repeat:no-repeat; width:29px; height:33px; position:absolute; right:70px; bottom:30px;cursor:pointer;\" onclick=\"" + helpClickCmd + "\"/>";
   }

   upsellButton = "";
   if (owned == 0)
   {
      //upsellClickCmd = "upsellTeam('" + teamName + "');";
      //upsellButton = "<button class=\"button186\" style=\"position:absolute; width:86px; background-size:100%; background-repeat:no-repeat; left:68px; bottom:5px\" onclick=\"" + upsellClickCmd + "\">" + cef.uiapp.locString('Buy!') + "</button>";
      var buyText = cef.uiapp.locString("Buy!");
      upsellButton = "<div id=\"" + teamName + "BuyStar\" style=\"background:url('heroacademy://data/UI/BigStarburst.png') no-repeat transparent; pointer-events:none; width:76px; height:76px; position:absolute; left:22px;bottom:13px;background-size:100%;\" class=\"buyText\"><p style=\"position:relative;left:-2px;top:-2px\">" + buyText + "<p></div>";
   }
   endDiv = "</div>";
   $('#TeamSelectRoster').append(startDiv + teamLabel + teamSelectImage + teamImage + teamTooltipButton + upsellButton + endDiv);

   $('#' + teamPickButton).hover(
      function ()
      {
         //$('#' + buttonID).css("font-size", bigSize);
         $('#' + teamPickButton).css("width", "142px")
         .css("height", "142px")
         .css("left", "30px")
         .css("top", "16px");
      },
      function ()
      {
         //$('#' + buttonID).css("font-size", normalSize);
         $('#' + teamPickButton).css("width", "102px")
         .css("height", "102px")
         .css("left", "50px")
         .css("top", "36px");
      }
   );

   $('#' + helpButtonID).hover(
      function ()
      {
         //$('#' + buttonID).css("font-size", bigSize);
         $('#' + helpButtonID).css("width", "43px")
         .css("height", "49px")
         .css("right", "64px")
         .css("bottom", "26px");
      },
      function ()
      {
         //$('#' + buttonID).css("font-size", normalSize);
         $('#' + helpButtonID).css("width", "29px")
         .css("height", "33px")
         .css("right", "70px")
         .css("bottom", "30px");
      }
   );

}

//=================================================================================================
function setRosterSelection(teamName)
{
   $(".teamSelectImage").hide();
   $('#teamSelect' + teamName).show();
   cef.uiapp.teamRosterSelection(teamName);

}

//=================================================================================================
function clearButton(buttonID)
{
   $("#" + buttonID)
   .off("click")
   .off("hover")
   .off("mouseup")
   .off("mousedown");
}

//=================================================================================================
function bindButton(buttonID, cmd)
{
   //alert(buttonID + ":" + cmd);
   $("#" + buttonID)
  .off("click")
  .on("click", function (e)
  {
     eval(cmd);
  });
}

//=================================================================================================
function clearTeamSelectRoster()
{
   $('#TeamSelectRoster').empty();
}

//=================================================================================================
function setTeamSelectAvatars(name1, name2, color1, color2, avatar1, avatar2, avatarColor1, avatarColor2, flipAvatar2)
{
   $('#TeamSelectName1').html(name1);
   $('#TeamSelectAvatar1').attr("src", avatar1);
   colorizeAvatar(true, color1, 'TeamSelectAvatar1', 'TeamSelectColorAvatar1', avatarColor1);

   $('#TeamSelectName2').html(name2);
   $('#TeamSelectAvatar2').attr("src", avatar2);
   colorizeAvatar(false, color2, 'TeamSelectAvatar2', 'TeamSelectColorAvatar2', avatarColor2);

   if(flipAvatar2)
   {
      $('#TeamSelectAvatar2')[0].style.webkitTransform = "scale(-1, 1)";
      $('#TeamSelectColorAvatar2')[0].style.webkitTransform = "scale(-1, 1)";
   }
   else
   {
      $('#TeamSelectAvatar2')[0].style.webkitTransform = "scale(1, 1)";
      $('#TeamSelectColorAvatar2')[0].style.webkitTransform = "scale(1, 1)";
   }
}

//=================================================================================================
function setTeamSelectTitle(titleText)
{
   // [5/9/12 xemu] - note that this expects localized text in.

   $('#teamSelectTitle').html(titleText); // "ADFKADFAODKFAF"); //  titleText;
}

//=================================================================================================
function requestGame(gameID, opponent, useTeam, fromMatchmaker)
{
   if (fromMatchmaker)
   {
      cef.uiapp.matchmake(useTeam);
      navigateToGamesList();
      return;
   }
   else if (gameID == '0')
   {
      if (!cef.uiapp.createGame(opponent, useTeam))
         return;
   }
   else
   {
      cef.uiapp.acceptGame(useTeam, gameID);
   }

   hideBoardElements();
   $('#GameBoard').show();
   cef.uiapp.showGameView();

}

//=================================================================================================
function createLeaderBoardSlots(numSlots)
{
   $('#LeaderboardsContainer').empty();
   for (i=0; i<numSlots-1; i++)
   {
      $('#LeaderboardsContainer').append("<div id='leaderboardentry" + i + "' class='leaderboardEntry' style='height:58px;'><div id='leaderboardentrytext" + i + "'></div></div>");
   }
   $('#LeaderboardsContainer').append("<div id='leaderboardentry" + i + "' class='leaderboardEntry' style='height:60px;'><div id='leaderboardentrytext" + i + "'></div></div>");
}

//=================================================================================================
function fillLeaderboardSlot(slot, rank, name, score, highlight)
{
   if ((slot < 0) || (cNumLeaderboardSlots < slot))
      return;

   var report = "Slot " + slot + ": " + name + ", rank " + rank + ", score " + score + ".";
   var entry = rank + ") " + name + " : " + score;
   //$("#leaderboardentry" + slot).html(entry);

   var rankHTML = '<div class="leaderboardEntryRank" style="position:absolute; left:0px; text-align: center; width:102px;">' + rank + '</div>';
   var nameHTML = '<div class="leaderboardEntryText" style="position:absolute; left:102px; text-align: left; width:660px; padding-left:90px;">' + name + '</div>';
   var scoreHTML = '<div class="leaderboardEntryRank" style="position:absolute; right:0px; text-align: center; width:92px;">' + score + '</div>';
   var entryHTML = rankHTML + nameHTML + scoreHTML;
   $("#leaderboardentrytext" + slot).html(entryHTML);
   
   if(highlight)
      $("#leaderboardentry" + slot).css("background-image", "url('heroacademy://UI/LeaderboardsBar_Highlight.png')");
      
}

//=================================================================================================
function runTest()
{
   var gameID = '1917';
   var entryID = '#ActiveEntry' + gameID;
   if ($(entryID).length)
   {
      alert("exist " + entryID);
   }
   else
   {
      alert("NOT exist " + entryID + ' ' + $(entryID) + $(entryID).length);
   }
}

//=================================================================================================
function modalPopup(fullpath)
{
   //var result = window.showModalDialog("http://www.google.com", { msg: "Hi from parent" });
   var result = window.showModalDialog(fullpath, { });
}

//=================================================================================================
function prepChat(name1, avatar1, colorFile1, color1, name2, avatar2, colorFile2, color2, colorizeOnly)
{
   if (!colorizeOnly)
   {
      $('#ChatBlank').hide();
      $('#ChatMOTD').hide();

      var layout = cef.uiapp.getLayoutMode();
      if (layout == cLayoutMedium)
      {
         $('#BackgroundFrame').attr("src", "heroacademy://UI/GameScreen_Med.png");
      }

      $(ChatForm).show();
   }

   $('#ChatName1').html(name1);
   $('#ChatAvatar1').attr("src", avatar1);
   colorizeAvatar(true, color1, 'ChatAvatar1', 'ChatColorAvatar1', colorFile1);

   $('#ChatName2').html(name2);
   $('#ChatAvatar2').attr("src", avatar2);
   colorizeAvatar(false, color2, 'ChatAvatar2', 'ChatColorAvatar2', colorFile2);

   if (!colorizeOnly)
   {
      $('#ChatHolder').show();
      $('#ChatText').empty();
      $('#ChatInput').focus();
      $('#ChatForm').ajaxForm(function ()
      {
         chatText = $('#ChatInput').val();
         chatTyped(chatText);
      });
   }

}

//=================================================================================================
function clearChat()
{
   $('#ChatName1').html("");
   $('#ChatAvatar1').attr("src", "");
   $('#ChatName2').html("");
   $('#ChatAvatar2').attr("src", "");

   $('#ChatHolder').hide();
   $('#ChatText').empty();

   $('#ChatMOTD').hide();

   var layout = cef.uiapp.getLayoutMode();
   if(layout == cLayoutLarge)
   {
      $('#ChatBlank').show();
   }
}

//=================================================================================================
function chatTyped(chatText)
{
   //alert(chatText);
   cef.uiapp.chatTyped(chatText);
   $('#ChatInput').val('');
}

//=================================================================================================
function showChat(leftSide, chatText)
{
   layout = cef.uiapp.getLayoutMode();

   //alert(fromLocal + " : " + chatText);
   if (leftSide == 1)
   {
      gradient = "background-image: -webkit-linear-gradient(left , #64739D 2%, #536083 50%, #64739D 98%)"
      //styleAlign = "style='text-align:left; background-image: -webkit-linear-gradient(#B4B8C3,#C2C6D1);'";
      padding = '';
      if (layout == cLayoutLarge)
         padding = 'margin-top:3px; padding:4 6 2 6;';

      styleAlign = "style='text-align:left; color:white;" + padding + gradient + ";'";

   }
   else
   {
      padding = '';
      if (layout == cLayoutLarge)
         padding = 'margin-top:3px; padding:4 6 2 6;';
      styleAlign = "style='text-align:right; color:white;" + padding + "; '";
   }

   chatTextLine = '<p class=\"chatDisplayText\" ' + styleAlign + ' >' + chatText + '</p>';

   $('#ChatText').append(chatTextLine);

   // [5/8/2012 xemu] annoyingly this restyling has to happen after the <p> is appended
   layout = cef.uiapp.getLayoutMode();
   if (layout == cLayoutMedium)
   {
      $(".chatDisplayText")
         .css('font-size', '18px')
         .css('color', 'white');
   }

}

//=================================================================================================
function positionElement(elemName, x, y, width, height)
{
   $('#' + elemName)
   .css('left', x.toString() + 'px')
   .css('top', y.toString() + 'px')
   .css('width', width.toString() + 'px')
   .css('height', height.toString() + 'px');
}

//=================================================================================================
function setBoardSize(width, height)
{
   $(".boardElement")
   .css('width', width.toString() + 'px')
   .css('height', height.toString() + 'px');

   $(".boardImage")
   .css('width', width.toString() + 'px')
   .css('height', height.toString() + 'px')
}

//=================================================================================================
function overrideStyleByLayoutTypeOnStartup()
{
   // This function only needs to be called once.
   layout = cef.uiapp.getLayoutMode();
   if (layout == cLayoutMedium)
   {
      $("#breadcrumbs")
      .css('left','6px');

      $("#refreshGamesButton")
      .css('left', '251px');

      $("#PreloginUI_Div1")
      .css('left', '277px')
      .css('top', '424px');

      $("#PreloginUI_Div2")
      .css('left', '618px')
      .css('top', '424px');

      $("#AccountCreateUI_Div1")
      .css('left', '375px')
      .css('top', '418px');

      $("#LoginUI_Div1")
      .css('left', '409px')
      .css('top', '430px');

      $("#PasswordResetUI_Div1")
      .css('left', '409px')
      .css('top', '430px');

      $("#SetPasswordUI_Div1")
      .css('left', '409px')
      .css('top', '430px');

      $("#FirstTimeSplashScreen")
      .css('width', '1280px')
      .css('height', '680px');

      $("#FirstTimeSplashScreen_Img1")
      .attr('src', 'heroacademy://UI/FirstTimeSplashScreen_Med.png');

      $("#FirstTimeSplashScreen_Div1")
      .css('left', '387px')
      .css('top', '495px');

      $("#FirstTimeSplashScreen_Div2")
      .css('left', '673px')
      .css('top', '495px');

      $("#CustomizeColors_Img1")
      .attr('src', 'heroacademy://UI/ColorsPageBG_Med.jpg');

      $("#CustomizeAvatarsImg1")
      .attr('src', 'heroacademy://UI/CreateGameBg_Med.png');

      $("#CustomColorBaseAvatar")
      .css('top', '82px');
      $("#CustomColorColorAvatar")
      .css('top', '82px');

      $("#CustomizeColorsText")
      .css('top', '98px');

      if (cef.uiapp.getUseWideColorText())
      {
         $("#CustomizeColorsText")
            .css('width', '500px')
            .css('left', '232px');
      }
      else
      {
         $("#CustomizeColorsText")
            .css('left', '282px');
      }

      $("#ColorHomePicker")
      .css('width', '748px');
      $("#ColorAwayPicker")
      .css('width', '748px');

      $("#ColorAreaHome")
      .css('height', '185px')
      .css('top', '233px');
      $("#ColorAreaAway")
      .css('height', '185px')
      .css('top', '435px');

      $("#TeamDetailContainer")
      .css('height', '636px');
      $("#TeamDetailBackground")
      .attr('src', 'heroacademy://UI/TeamsPageBG_Med.jpg');

      $("#TeamDetailEmblem")
      .css('left', '133px');

      $("#TeamDetailEntries2")
      .css('top', '544px')
      .css('left', '258px')
      .css('width', '436px');

      $("#TeamDetailEntries0")
      .css('left', '28px')
      .css('width', '436px');

      $("#TeamDetailEntries1")
      .css('left', '496px')
      .css('width', '436px');

      $("#AvatarContainer")
      .css('width', '900px')
      .css('height', '492px');

      $("#TeamSelect_Img1")
      .attr('src', 'heroacademy://UI/CreateGameBg_Med.png');

      $("#teamSelectTitleContainer")
      .css('top', '133px');

      $("#TeamSelectAvatar1Container")
      .css('top', '76px')
      .css('left', '53px');
      $("#TeamSelectName1")
      .css('left', '-14px');

      $("#TeamSelectAvatar2Container")
      .css('top', '76px')
      .css('right', '179px');
      $("#TeamSelectName2")
      .css('left', '-14px');

      $("#SelectATeamText")
      .css('top', '173px');
      $("#TeamSelectRoster_Container")
      .css('top', '245px');
      $("#TeamSelect_ImgBackdrop")
      .css('height', '322px')
      .attr('src', 'heroacademy://UI/SelectTeam-Backdrop_Med.png');
      $("#TeamSelectRoster")
      .css('left', '158px');

      $("#TeamSelectButtonsContainer")
      .css('bottom', '16px');
      $("#TeamSelectDeclineGame")
      .css('right', '24px');

      $("#LeaderboardsImg1")
      .attr('src', 'heroacademy://UI/LeaderboardsBG_Med.png');

      $("#LeaderboardsScroll")
      .css('height', '636px');
      $("#LeaderboardsContainer")
      .css('margin-bottom', '185px');

      $("#GameListActiveSection")
      .css('padding', '5px 0px 0px 0px');
      $("#GameListCompletedSection")
      .css('padding', '0px 0px 5px 0px');

      for (i=1; i<=5; i++)
      {
         $("#MainMenugBG" + i)
         .attr('src', 'heroacademy://UI/MainMenuBG_Med.jpg');
      }
      
      $("#ChallengeBG")
      .attr('src', 'heroacademy://UI/ChallengePage_Med.jpg');
      
      $("#CustomizeBG")
      .attr('src', 'heroacademy://UI/CustomizePageBG_Med.jpg');
      
      $("#TrainingBG")
      .attr('src', 'heroacademy://UI/TrainingPageBG_Med.jpg');
      
      $("#PlayBG")
      .attr('src', 'heroacademy://UI/PlayPage_Med.jpg');
   }
}

//=================================================================================================
function overrideStyleByLayoutType()
{
   layout = cef.uiapp.getLayoutMode();
   if (layout == cLayoutMedium)
   {
      $("#navmenu")
      .css('padding-top', '2px');

      $(".navMenuButtonBig")
      .css("background", "url('heroacademy://UI/PlayButton-Up_Med.png') transparent no-repeat")
      .css('width', '286px')
      .css('height', '102px')
      .css('margin-left', '7px')
      .css('margin-top', '3px')
      .css('line-height', '100px');

      $(".navMenuButton")
      .css("background", "url('heroacademy://UI/MenuNav-Up_Med.png') transparent no-repeat")
      .css('width', '278px')
      .css('height', '55px')
      .css('margin-left', 'auto')
      .css('margin-right', 'auto')
      .css('margin-top', '6px')
      .css('line-height', '52px');

      $(".navMenuButtonLeftAlign")
      .css('width', '210px')
      .css('height', '55px')
      .css('margin-left', '5px')
      .css('margin-top', '6px')
      .css('line-height', '52px');

      $(".gamesListSection")
      .css('margin', '0px 4px 0px 4px');

      $(".gameListHeader")
      .css("background", "url('heroacademy://UI/GamesList-Heading_Med.png') transparent no-repeat")
      .css('width', '279px')
      .css('height', '31px');

      $(".createGameEntry")
      .css("background", "url('heroacademy://UI/GameList-Top-Up_Med.png') transparent no-repeat")
      .css('width', '279px')
      .css('height', '44px')
      .css('line-height', '45px')
      .css('font-size', '30px');

      $(".createGameEntryText")
      .css('top', '0px')
      .css('padding', '0px 0px 0px 10px');

      $(".gameEntry")
      .css("background-image", "url('heroacademy://UI/GameList-Up_Med.png')")
      .css('width', '279px')
      .css('height', '44px')
      .css('padding', '0px');

      $(".gameTextFixed")
      .css('width', '302px')
      .css('height', '45x');

      $(".gameTextName")
      .css('width', '150px')
      .css('height', '20x');

      $("#ChatAvatar1")
      .css('left', '9px')
      .css('top', '10px')
      .css('width', '53px')
      .css('height', '53px');
      $("#ChatColorAvatar1")
      .css('left', '9px')
      .css('top', '10px')
      .attr('width', '53')
      .attr('height', '53');

      $("#ChatAvatar2")
      .css('right', '9px')
      .css('top', '10px')
      .css('width', '53px')
      .css('height', '53px');
      $("#ChatColorAvatar2")
      .css('right', '9px')
      .css('top', '10px')
      .attr('width', '53')
      .attr('height', '53');

      $("#ChatName1")
      .css('left', '67px')
      .css('width', '166px')
      .css('top', '12px')
      .css('text-align', 'left');
      $("#ChatName2")
      .css('left', '67px')
      .css('width', '166px')
      .css('top', '38px')
      .css('text-align', 'right');

      $(".chatDisplayText")
      .css('font-size', '18px')
      .css('color', 'white');

      $(".gameTextInput")
      .css('color', 'white')
      .css('background-color', 'black');

      $("#ChatText")
      .css('width', '296px')
      .css('height', '183px')
      .css('top', '74px')
      .css('left', '2px');

      $("#ChatInput")
      .css('width', '290px')
      .css('height', '23px')
      .css('left', '5px')
      .css('bottom', '4px');

      $('#HomeArt').attr("src", "heroacademy://UI/TF2_Home_Med.png");

   }
   else if (layout == cLayoutLarge)
   {
      $("#gameslist")
      .css('width', '370px');

      $('#HomeArt').attr("src", "heroacademy://UI/TF2_Home_Lge.png");
   }
}

//=================================================================================================
function prepLocText()
{
   $('#PreloginHeadingText').html(cef.uiapp.locString('WELCOME!'));
   $('#AccountCreateHeadingText').html(cef.uiapp.locString('CREATE ACCOUNT'));
   $('#LoginHeadingText').html(cef.uiapp.locString('LOGIN'));
   $('#PasswordResetHeadingText').html(cef.uiapp.locString('PASSWORD RESET'));
   $('#SetPasswordHeadingText').html(cef.uiapp.locString('SET PASSWORD'));

   $('#YourTurnText').html(cef.uiapp.locString('YOUR TURN'));
   $('#WaitingForText').html(cef.uiapp.locString('WAITING FOR...'));
   $('#CompletedGamesText').html(cef.uiapp.locString('COMPLETED'));
   $('#TeamSelectCreateGame').html(cef.uiapp.locString('Create!'));
   $('#TeamSelectDeclineGame').html(cef.uiapp.locString('Cancel'));
   $('#NewAccount').html(cef.uiapp.locString('NEW ACCOUNT'));
   $('#ExistingAccount').html(cef.uiapp.locString('EXISTING ACCOUNT'));

   $('#email_create_text').html(cef.uiapp.locString('Email:'));
   $('#account_create_text').html(cef.uiapp.locString('Username:'));
   $('#password_create_text').html(cef.uiapp.locString('Password:'));
   $('#repassword_create_text').html(cef.uiapp.locString('Retype Password:'));
   $('#CancelCreateAccount').html(cef.uiapp.locString('CANCEL'));
   $('#CreateAccount').html(cef.uiapp.locString('CREATE'));

   $('#login_account_text').html(cef.uiapp.locString('Email:'));
   $('#login_password_text').html(cef.uiapp.locString('Password:'));
   $('#LoginSubmit').html(cef.uiapp.locString('LOG IN!'));
   $('#CancelLogin').html(cef.uiapp.locString('CANCEL'));
   $('#ForgotPassword').html(cef.uiapp.locString('Forgot Password?'));

   $('#reset_email_text').html(cef.uiapp.locString('Email:'));
   $('#PasswordReset').html(cef.uiapp.locString('SEND'));
   $('#CancelPasswordReset').html(cef.uiapp.locString('CANCEL'));

   $('#email_setpw_text').html(cef.uiapp.locString('Email:'));
   $('#password_setpw_text').html(cef.uiapp.locString('New Password:'));
   $('#repassword_setpw_text').html(cef.uiapp.locString('Retype Password:'));
   $('#CancelSetPassword').html(cef.uiapp.locString('CANCEL'));
   $('#SetPasswordConfirm').html(cef.uiapp.locString('ACCEPT'));

   $('#SelectATeamText').html(cef.uiapp.locString('Select a Team!'));

   $('#CustomizeColorsTitle').html(cef.uiapp.locString('Custom Color'));
   $('#CustomizeColorsText').html(cef.uiapp.locString('CustomizeColor_Text'));
   $('#ColorHomeText').html(cef.uiapp.locString('Home Color'));
   $('#ColorAwayText').html(cef.uiapp.locString('Away Color'));
   $('#AvatarTitleBarText').html(cef.uiapp.locString('Avatars'));
   
   $('#HowToPlay').html(cef.uiapp.locString('How to Play!'));
   $('#SkipTutorial').html(cef.uiapp.locString('Skip Tutorial'));
   
   $('#ExistingAccountExplanation').html("<p>" + cef.uiapp.locString('ExistingAccountExplanation') + "</p>");
   $('#NewAccountExplanation').html("<p>" + cef.uiapp.locString('NewAccountExplanation') + "</p>");
   $('#ForgotPasswordExplanation').html("<p>" + cef.uiapp.locString('ForgotPasswordExplanation') + "</p>");

   // [5/16/12 xemu] not technically loc text, but still one-time startup mojo
   fixupButtonWithHeight("TeamSelectDeclineGame", 45, 25, "AccountRedButton-Dn.png", "AccountRedButton-Up.png", null, 210, 210, 39);
   fixupButton("HowToPlay", 45, 35, "FirstTimeSplashButton-Dn.png", "FirstTimeSplashButton-Up.png", null, 242, 242);
   fixupButton("SkipTutorial", 45, 35, "FirstTimeSplashButton-Dn.png", "FirstTimeSplashButton-Up.png", null, 242, 242);
   
   fixupButtonSmall("ExistingAccount", "AccountButton-Dn.png", "AccountButton-Up.png");
   fixupButtonSmall("NewAccount", "AccountButton-Dn.png", "AccountButton-Up.png");
   fixupButtonSmall("CreateAccount", "SubmitButton-Dn.png", "SubmitButton-Up.png");
   fixupButtonSmall("CancelCreateAccount", "SubmitButton-Dn.png", "SubmitButton-Up.png");
   fixupButtonSmall("LoginSubmit", "SubmitButton-Dn.png", "SubmitButton-Up.png");
   fixupButtonSmall("CancelLogin", "SubmitButton-Dn.png", "SubmitButton-Up.png");
   fixupButtonSmall("ForgotPassword", "ForgotPasswordButton-Dn.png", "ForgotPasswordButton-Up.png");
   fixupButtonSmall("PasswordReset", "SubmitButton-Dn.png", "SubmitButton-Up.png");
   fixupButtonSmall("CancelPasswordReset", "SubmitButton-Dn.png", "SubmitButton-Up.png");
   fixupButtonSmall("SetPasswordConfirm", "SubmitButton-Dn.png", "SubmitButton-Up.png");
   fixupButtonSmall("CancelSetPassword", "SubmitButton-Dn.png", "SubmitButton-Up.png");

   fixupButtonNoText("refreshGamesButton", "GameRefreshButton-Dn.png", "GameRefreshButton.png", "GameRefreshButtonHighlight.png", true, function ()
   {
      cef.uiapp.manualRequestGamesList();
   });


   if (cef.uiapp.getUseSmallMOTD())
   {
      $('#MOTDText').css('font-size', '45px');
   }
   if (cef.uiapp.getUseSmallTeamDetails())
   {
      $('#TeamDetailDescription').css('font-size', '25px');
      $('#TeamDetailLongDesc').css('font-size', '18px');
   }
   if (cef.uiapp.getUseSmallLoginForm())
   {
      $('.loginFormText').css('font-size', '12px');
   }
   overrideStyleByLayoutTypeOnStartup();
   createLeaderBoardSlots(cNumLeaderboardSlots);

   /*
   $('#gameslist-slider').slider({
      orientation: "vertical",
      min: 0,
      max: 100,
      value: 60,
      stop: function (event, ui)
      {
         //alert(ui.value);
         $('#gameslist').scrollTop(ui.value * 10);
      }
   });
   */
}

//=================================================================================================
function locAlert(unLocText)
{
   cef.uiapp.displayError(unLocText);
}

//=================================================================================================
function showMOTD()
{
   clearChat();
   $('#ChatMOTD').show();
   //  [5/18/12 xemu] - at some point we should pull this from the server or just update the contents?
   $('#MOTDText').html(cef.uiapp.locString("MOTD_DefaultText"));
}

//=================================================================================================
function doTwitterButton() 
{
   //modalTest("heroacademy://twitterFrame.html");
   //modalTest("https://twitter.com/intent/tweet?button_hashtag=TwitterStories");
   var twitterText = cef.uiapp.getTwitterText();
   var twitterURL = "https://twitter.com/share?text=" + encodeURIComponent(twitterText);
   modalPopup(twitterURL);
}


//=================================================================================================
/*
$(function ()
{
   $("CommandButtonBack").button({
      icons: {
         primary: "UI_BackButton.png"
      },
      text: false
   });
});
 */
//$("CommandButtonBack").button({ icons: { primary: 'UI_BackButton.png', secondary: 'UI_BackButton_Selected.png'} });
