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

var currentAvatarPage = "";
var currentLeaderboardPage = "";
var currentLeaderboardFriendsOnly = false;
var shownRestartWarning = false;

//=================================================================================================
function navigateTo(navText)
{
   showMediumChatArea(false);
   $('#navmenu').css('height', '100%');
   $('#navmenu').css('width', '100%');
   hideAllLoginUI();
   //alert("nav to (" + navText + ")." + navText.length);
   $('#gameslist').hide();
   if ((navText == null) || (!navText) || (navText == "Home"))
   {
      clearNavEntries();
      assembleBreadcrumbs("");
      navigateToHome();
   }
   else
   {
      var leafDest = parseDestination(navText);

      if ((!isLoggedIn()) && (leafDest == "Customize" || leafDest == "GamesList"))
      {
         loginMagic(navText);
      }
      else
      {
         if (isRealBreadcrumb(navText))
         {
            clearNavEntries();
            assembleBreadcrumbs(navText);
            eval('navigateTo' + leafDest + '();');
         }
      }
   }
}

function isRealBreadcrumb(navText)
{
   // [7/9/2012 xemu] mea culpa, mea culpa, mea maxima culpa
   if (navText.indexOf('Challenges_Meet') == 0)
      return false;

   return true;

}

function showMediumChatArea(isVisible)
{
   var layout = cef.uiapp.getLayoutMode();
   if(layout == cLayoutMedium)
   {
      if(isVisible)
      {
         $('#BackgroundFrame').attr("src", "heroacademy://UI/GameScreen_Med.png");
         $('#navmenu-outer').css('height', '299px');
         $('#ChatArea').show();
      }
      else
      {
         $('#BackgroundFrame').attr("src", "heroacademy://UI/GameScreen-Nav_Med.png");
         $('#gameslist').scrollTop(0);
         $('#navmenu-outer').css('height', '596px');
         $('#ChatArea').hide();
      }
   }
}

//=================================================================================================
function testWheel(event)
{
   alert("foo");
   if (event.wheelDelta)
   {
      alert(event.wheelDelta/120);
   }
}

//=================================================================================================
function navigateToGamesList()
{
   // [7/16/2012 xemu] re-check our server version
   if (!cef.uiapp.checkServerVersion())
   {
      navigateTo('Home');
      return;
   }

   //alert("NAV Games List");
   $('#navmenu').empty();
   $('#navmenu').css('height', '0px');
   $('#navmenu').css('width', '0px');
   $('#gameslist').show();
   purgeGamesList();

   hideBoardElements();
   $('#GamesListScreen').show();
   clearChat();
   showMediumChatArea(true);

   //$('#gameslist').onmousewheel = testWheel;

   /*
   var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x

   if (document.attachEvent) //if IE (and Opera depending on user setting)
      document.attachEvent("on" + mousewheelevt, function (e) { alert('Mouse wheel movement detected!') })
   else if (document.addEventListener) //WC3 browsers
      document.addEventListener(mousewheelevt, function (e) { alert('Mouse wheel movement detected!') }, false)
   */

   cef.uiapp.enableGamesList(true);
   cef.uiapp.manualRequestGamesList();
}

//=================================================================================================
function navigateToHome()
{
   cef.uiapp.closeGameView();
   hideBoardElements();
   //alert("NAV home");
   addNavMenuEntry("GamesList", true);
   addNavMenuEntry("Training");
   addNavMenuEntry("Challenges");
   addNavMenuEntry("Customize");
   addNavMenuEntry("Settings");
   addNavMenuEntry("Leaderboards");
   addMenuEntry("NewsButton", "News", function ()
   {
      hideBoardElements();
      $('#NewsPageFrame').attr("src", cef.uiapp.getNewsURL());
      $('#NewsPage').show();
      $('#UnreadNewsMarker').hide();
      cef.uiapp.markNewsRead();
   });

   var layout = cef.uiapp.getLayoutMode();
   var unreadNews = cef.uiapp.getNumUnreadNewsItems();
   var badgeOffset = 308;
   if (layout == cLayoutMedium)
      badgeOffset = 250;
   if (unreadNews > 0)
   {
      if (unreadNews > 9)
         unreadNews = '9+';
      var unreadNewsMarker = '<p id=\"UnreadNewsMarker\" style=\"position:absolute; left:' + badgeOffset + 'px; bottom:6px; width:24px; height:24px; background:url(\'heroacademy://data/NewChatsBadge-hd.png\') transparent no-repeat; background-size:100%;\" class=\"unreadNewsBadgeText\">' + unreadNews + '</p>';
      $('#NewsButton').append(unreadNewsMarker);
   }

   showHomeScreen();

   overrideStyleByLayoutType();
   if(layout == cLayoutLarge)
   {
      showMOTD();
   }
}

//=================================================================================================
function showHomeScreen()
{
   $('#HomeScreen').show();
   if (cef.uiapp.isLoggedIn())
   {
      var avatarName = cef.uiapp.getLocalAvatar();
      //alert(avatarName);

      $('#HomeAvatarImage').css("background", "url('heroacademy://data/" + avatarName + "') transparent no-repeat ");
      colorizeAvatar(true, cef.uiapp.getPlayerColor(true), 'HomeAvatarImage', 'HomeAvatarColor', cef.uiapp.getLocalAvatarColor());

      $('#HomeAvatarName').html(cef.uiapp.getCurrentUserNickname());
      $('#HomeAvatarDiv').show();
      $('#HomeTwitterButton').show();
   }
   else
   {
      $('#HomeAvatarDiv').hide();
      $('#HomeTwitterButton').hide();
   }

   clearButton('HomeAchievementsButton');
   clearButton('HomeLeaderboardButton');

   fixupButtonNoText('HomeAchievementsButton', 'UI_AchievmentButton_Pressed.png', 'UI_AchievmentButton.png', 'UI_AchievmentButtonRollover.png', true, function ()
   {
      cef.uiapp.showSteamOverlay('Achievements');
   });
   fixupButtonNoText('HomeLeaderboardButton', 'UI_LeaderButton_Pressed.png', 'UI_LeaderButton.png', 'UI_LeaderButtonRollover.png', true, function ()
   {
      alert("TBD Leaderboards");
   });
}

//=================================================================================================
function navigateToChallenges()
{
   clearChat();
   // load the puzzle protos
   cef.uiapp.initPuzzles();
   // get the challenge root category
   var category = cef.uiapp.getPuzzleChallengeCategory();
   // ask the game to push all its categories and puzzles to us
   cef.uiapp.requestPuzzleList(category);
   $('#Challenges').show();
   overrideStyleByLayoutType();
}

//=================================================================================================
function navigateToCustomize()
{
   hideBoardElements();
   addNavMenuEntry("Customize_CustomizeTeams");
   addNavMenuEntry("Customize_CustomizeAvatars");
   addMenuEntry("Customize_CustomizeColors", "Uniform Colors", function ()
   {
      showCustomizeColorsScreen();
   });
   //addNavMenuEntry("Customize_CustomizeTaunts");
   $('#Customize').show();
   overrideStyleByLayoutType();
}

//=================================================================================================
function navigateToCustomizeAvatars()
{
   addMenuEntry("NavAvatars_Council", "Civ_humans_DisplayName", function () { showAvatarPage('humans') });
   addMenuEntry("NavAvatars_DarkElves", "Civ_darkelves_DisplayName", function () { showAvatarPage('darkelves') });
   addMenuEntry("NavAvatars_Dwarves", "Civ_dwarves_DisplayName", function () { showAvatarPage('dwarves') });
   addMenuEntry("NavAvatars_Tribe", "Civ_orcs_DisplayName", function () { showAvatarPage('orcs') });
   addMenuEntry("NavAvatars_TF2", "Civ_tf2a_DisplayName", function () { showAvatarPage('tf2a') });
   overrideStyleByLayoutType();
}

//=================================================================================================
function showAvatarPage(teamName)
{
   currentAvatarPage = teamName;
   switch(teamName)
   {
   case "humans":
      showAvatarSelect('HA_AVATAR_COUNCIL_FREE', 'AVATARS_COUNCIL_SAMPLER', 'AVATARS_COUNCIL_SUPER');
      break;
   case "darkelves":
      showAvatarSelect('HA_AVATAR_DE_FREE', 'AVATARS_DE_SAMPLER', 'AVATARS_DE_SUPER');
      break;
   case "dwarves":
      showAvatarSelect('HA_AVATAR_DW_FREE', 'AVATARS_DW_SAMPLER', 'AVATARS_DW_SUPER');
      break;
   case "orcs":
      showAvatarSelect('HA_AVATAR_TR_FREE', 'AVATARS_TR_SAMPLER', 'AVATARS_TR_SUPER');
      break;
   case "tf2a":
      showAvatarSelect('AVATARS_TF2_BASIC', 'AVATARS_TF2_VANITY', '');
      break;
   default:
      locAlert("Assert: Unable to show avatar page for " + teamName + ".");
      break;
   }
}

//=================================================================================================
function navigateToCustomizeTeams()
{
   addMenuEntry("NavTeamView_Council", "Civ_humans_DisplayName", function () { showTeamDetails('humans'); });
   addMenuEntry("NavTeamView_DarkElves", "Civ_darkelves_DisplayName", function () { showTeamDetails('darkelves'); });
   addMenuEntry("NavTeamView_Dwarves", "Civ_dwarves_DisplayName", function () { showTeamDetails('dwarves'); });
   addMenuEntry("NavTeamView_Tribe", "Civ_orcs_DisplayName", function () { showTeamDetails('orcs'); });
   addMenuEntry("NavTeamView_TF2", "Civ_tf2a_DisplayName", function () { showTeamDetails('tf2a'); });
   overrideStyleByLayoutType();
}

//=================================================================================================
function navigateToLeaderboards()
{
   hideBoardElements();
   //TODO loc these
   addMenuEntry("NavLeaderboards_Total", "Leaderboard_total_wins", function () { showLeaderboardPage('total', currentLeaderboardFriendsOnly) });
   addMenuEntry("NavLeaderboards_Council", "Civ_humans_DisplayName", function () { showLeaderboardPage('humans', currentLeaderboardFriendsOnly) });
   addMenuEntry("NavLeaderboards_DarkElves", "Civ_darkelves_DisplayName", function () { showLeaderboardPage('darkelves', currentLeaderboardFriendsOnly) });
   addMenuEntry("NavLeaderboards_Dwarves", "Civ_dwarves_DisplayName", function () { showLeaderboardPage('dwarves', currentLeaderboardFriendsOnly) });
   addMenuEntry("NavLeaderboards_Tribe", "Civ_orcs_DisplayName", function () { showLeaderboardPage('orcs', currentLeaderboardFriendsOnly) });
   addMenuEntry("NavLeaderboards_TF2", "Civ_tf2a_DisplayName", function () { showLeaderboardPage('tf2a', currentLeaderboardFriendsOnly) });
   
   showLeaderboardPage('total');
   $('#Leaderboards').show();
   overrideStyleByLayoutType();
}

//=================================================================================================
function showLeaderboardPage(teamName, friendsOnly)
{
   cef.uiapp.showLeaderboard(teamName, cNumLeaderboardSlots, friendsOnly);
   currentLeaderboardPage = teamName;
   currentLeaderboardFriendsOnly = friendsOnly;
   
   $('#LeaderboardsTitleBarText').html(cef.uiapp.locString("Leaderboard_" + teamName + "_wins"));
   $('#LeaderboardTeamEmblem1').attr('src', 'heroacademy://UI/LeaderboardsWinIcon_' + teamName + '.png');
   $('#LeaderboardTeamEmblem2').attr('src', 'heroacademy://UI/LeaderboardsWinIcon_' + teamName + '.png');
   
   var layout = cef.uiapp.getLayoutMode();
   if(layout == cLayoutMedium)
   {
      if(friendsOnly)
      {
         $('#LeaderboardsGlobalTab').css('top', '120px');
         $('#LeaderboardsFriendsTab').css('top', '110px');
      }
      else
      {
         $('#LeaderboardsGlobalTab').css('top', '110px');
         $('#LeaderboardsFriendsTab').css('top', '120px');
      }
   }
   else if(layout == cLayoutLarge)
   {
      if(friendsOnly)
      {
         $('#LeaderboardsGlobalTab').css('top', '120px');
         $('#LeaderboardsFriendsTab').css('top', '110px');
      }
      else
      {
         $('#LeaderboardsGlobalTab').css('top', '110px');
         $('#LeaderboardsFriendsTab').css('top', '120px');
      }
   }

   switch(teamName)
   {
   case "total":
      break;
   case "humans":
      break;
   case "darkelves":
      break;
   case "dwarves":
      break;
   case "orcs":
      break;
   case "tf2a":
      break;
   default:
      locAlert("Assert: Unable to show leaderboard page for " + teamName + ".");
      break;
   }
}

//=================================================================================================
function navigateToTraining()
{
   hideBoardElements();
   addNavMenuEntry("Training_TrainingTutorial");
   addMenuEntry("GameGuideButton", "Game Guide", function ()
   {
      showFrame(cef.uiapp.getGameGuideURL());
   });

   addMenuEntry("TrainingVideoButton", "Tips Video", function ()
   {
      //var windowObjectReference;
      //var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes";
      //windowObjectReference = window.open("http://www.robotentertainment.com/", "RE_WindowName", strWindowFeatures);
      var tipsVideoURL = "http://www.youtube.com/embed/nox2dk0_aSA?rel=0"; 
      cef.uiapp.openExternalLink(tipsVideoURL);
   });
   $('#Training').show();
   overrideStyleByLayoutType();
}

//=================================================================================================
function navigateToTrainingBasics()
{
}

//=================================================================================================
function navigateToTrainingTutorial()
{
   // load the puzzle protos
   cef.uiapp.initPuzzles();
   // get the tutorial root category
   var category = cef.uiapp.getPuzzleTutorialCategory();
   // ask the game to push all its categories and puzzles to us
   cef.uiapp.requestPuzzleList(category);
}

//=================================================================================================
function navigateToTrainingGameGuide()
{
}

//=================================================================================================
function navigateToCreateGame()
{
   $('#navmenu').empty();
   
   $('#navmenu').css('height', '100%');
   $('#navmenu').css('width', '100%');

   var layout = cef.uiapp.getLayoutMode();
   if(layout == cLayoutMedium)
   {
      var topMargin = '2px';
      var leftMargin = '4px';
   }
   else if(layout == cLayoutLarge)
   {
      var topMargin = '8px';
      var leftMargin = '6px';
   }

   cef.uiapp.closeGameView();
   listHeader = "<h1 id=\"ByUsernameListHeaderText\" class=\"gameListHeader\" style=\"margin-top:" + topMargin + ";margin-left:" + leftMargin + ";margin-bottom:0px;position:relative;\">" + cef.uiapp.locString("BY USERNAME") + "</h1>";
   $('#navmenu').append(listHeader);

   if(layout == cLayoutMedium)
   {
      entryDiv = "<div class=\"\" style=\"border:1px solid transparent; width:272px; height:44px; background:url('heroacademy://UI/ByUserTextField-Med.png') transparent no-repeat; margin-left:8px; margin-top:12px; position:relative;\" >";
      entryInput = "<form id=\"inviteform\" method=\"post\"><input type=\"text\" style=\"width:272px; height:44px; position:absolute; \" class=\"inviteFormText\" id=\"CreateGameOpponentName\" /><button class=\"\" id=\"CreateGameButton\" style=\"width:44px; height:44px; border:none; margin:0px; padding:0px; position:absolute; right:0px; background:url('heroacademy://UI/ByUserBtn-Up.png') transparent no-repeat; \"/></form>";
   }
   else if(layout == cLayoutLarge)
   {
      entryDiv = "<div class=\"\" style=\"border:1px solid transparent; width:338px; height:44px; background:url('heroacademy://UI/ByUserTextField-Lge.png') transparent no-repeat; margin-left:8px; margin-top:12px; position:relative;\" >";
      entryInput = "<form id=\"inviteform\" method=\"post\"><input type=\"text\" style=\"width:280px; height:44px; position:absolute; \" class=\"inviteFormText\" id=\"CreateGameOpponentName\" /><button class=\"\" id=\"CreateGameButton\" style=\"width:44px; height:44px; border:none; margin:0px; padding:0px; position:absolute; right:8px; background:url('heroacademy://UI/ByUserBtn-Up.png') transparent no-repeat; \"/></form>";
   }

   endDiv = "</div>";
   $('#navmenu').append(entryDiv + entryInput + endDiv);
   fixupButtonNoText('CreateGameButton', 'ByUserBtn-Dn.png', 'ByUserBtn-Up.png', 'ByUserBtn-Up.png', false, null);
   $("#CreateGameOpponentName").focus();
   cef.uiapp.setKeyboardFocus("CreateGameOpponentName");

   // [4/12/12 xemu] crazy binding mojo to let us use a form without triggering a reload
   $('#inviteform').ajaxForm(function ()
   {
      //alert("login yo");
      cef.uiapp.playSound("sound/Generic_Push_Button.mp3");
      showTeamSelect('0', '', false);
   });

   //alert(div1 + inviteBackground + inviteText + inviteButton + div2);
   //$('#navmenu').append(div1 + inviteBackground + inviteText + inviteButton + div2);

   listHeader = "<h1 id=\"SearchListHeaderText\" class=\"gameListHeader\" style=\"margin-top:12px;margin-left:" + leftMargin + ";position:relative;\">" + cef.uiapp.locString("SEARCH") + "</h1>";
   $('#navmenu').append(listHeader);

   var downArt = "MenuNav-Search-Dn_Lge.png";
   var upArt = "MenuNav-Search-Up_Lge.png";
   var layout = cef.uiapp.getLayoutMode();
   if(layout == cLayoutMedium)
   {
      var downArt = "MenuNav-Search-Dn_Med.png";
      var upArt = "MenuNav-Search-Up_Med.png";
   }
   
   // [6/25/12 xemu] changed this to mixed caps to find the right string table string
   addMenuEntryWithArt("NavRandomOpponent", "Random Opponent", downArt, upArt,
      function ()
      {
         showTeamSelect('0', '', true);
      });
   addTwitterNavButton();

   friendHeader = "<h1 id=\"FriendHeaderText\" class=\"gameListHeader\" style=\"margin-top:20px;margin-left:" + leftMargin + ";\">" + cef.uiapp.locString("FRIENDS") + "</h1>";
   $('#navmenu').append(friendHeader);

   cef.uiapp.populateFriends();
   clearChat();

   // [4/24/12 xemu] disabling these until we can do an actual implementation
   //addMenuEntry("Facebook Friends", "");
   //addMenuEntry("SteamFriends", "");
   $(TeamSelect).hide();
   $(GamesListScreen).show();

}

function addTwitterNavButton()
{
   var layout = cef.uiapp.getLayoutMode();

   var twDownArt = "MenuNav-Twitter-Dn_Lge.png";
   var twUpArt = "MenuNav-Twitter-Up_Lge.png";
   if (layout == cLayoutMedium)
   {
      twDownArt = "MenuNav-Twitter-Dn_Med.png";
      twUpArt = "MenuNav-Twitter-Up_Med.png";
   }

   addMenuEntryWithArt("NavCreateTwitter", "Twitter", twDownArt, twUpArt,
      function ()
      {
         doTwitterButton();
      });
}

//=================================================================================================
function navigateToSettings()
{
   createSoundPrefButton();
   createPrefToggleButton("Settings_ColorizeAvatar", "Avatar Color: ", "iTactics_AvatarColor");
   if (cef.uiapp.allowLayoutSetting())
      createPrefToggleButton("Settings_CompactLayout", "Compact Layout: ", "iTactics_MediumLayout", true);
   createPrefToggleButton("Settings_PartialUndo", "Partial Undo: ", "iTactics_PartialUndo");
   createPrefValueButton("Settings_FirstTurnAP", "First Turn AP: %d", "iTactics_FirstTurnAP", 3, 5, 5);
   if (isLoggedIn())
   {
      addMenuSpacer();
      addMenuEntry("Settings_Logout", "Log Out", function ()
      {
         doLogout();
      });
      addMenuEntry("Settings_SetPassword", "Set Password", function ()
      {
         hideBoardElements();
         $('#SetPasswordUI').show();
         currentLoginUI = "#SetPasswordUI";
      });
   }
   addMenuSpacer();
   addMenuEntry("Settings_Credits", "Credits", function () 
   {
      showFrame("heroacademy://Credits/Credits.html");
   });
   addMenuEntry("Settings_REcom", "Robot Entertainment", function ()
   {
      var linkURL = "http://www.robotentertainment.com";
      cef.uiapp.openExternalLink(linkURL);
   });
   addMenuEntry("Settings_About", "About", function () 
   {
      showFrame("heroacademy://About/About.html");
   });

   showHomeScreen();
   overrideStyleByLayoutType();
}

//=================================================================================================
function addMenuSpacer()
{
   var layout = cef.uiapp.getLayoutMode();
   if(layout == cLayoutMedium)
   {
      var spacer = "<div style=\"height:15px;\"/>";
      $('#navmenu').append(spacer);
   }
   else if(layout == cLayoutLarge)
   {
      var spacer = "<div style=\"height:64px;\"/>";
      $('#navmenu').append(spacer);
   }
}

//=================================================================================================
function getSoundText()
{
   if (cef.uiapp.areSoundsEnabled())
      return "Sound: ON";
   else
      return "Sound: OFF";
}

//=================================================================================================
function createSoundPrefButton()
{
   var soundText = getSoundText();

   addMenuEntry("Settings_SoundPref", soundText, function ()
   {
      cef.uiapp.toggleSound();
      $("#Settings_SoundPref").html(cef.uiapp.locString(getSoundText()));
   });
}

//=================================================================================================
function getPrefBoolText(prefTextFragment, prefName)
{
   if (cef.uiapp.checkPref(prefName))
      return prefTextFragment + "ON";
   else
      return prefTextFragment + "OFF";
}

//=================================================================================================
function createPrefToggleButton(buttonName, prefTextFragment, prefName, requireRestart)
{
   var prefText = getPrefBoolText(prefTextFragment, prefName);
   addMenuEntry(buttonName, prefText, function ()
   {
      cef.uiapp.togglePref(prefName);
      $("#" + buttonName).html(cef.uiapp.locString(getPrefBoolText(prefTextFragment, prefName)));
      if (requireRestart && !shownRestartWarning)
      {
         locAlert("ChangeRequiredRelaunch");
         shownRestartWarning = true;
      }
   });
}

//=================================================================================================
function getPrefValueText(prefTextFragment, prefName, prefDefaultVal)
{
   return cef.uiapp.formatByPrefValue(prefTextFragment, prefName, prefDefaultVal);
}

//=================================================================================================
function createPrefValueButton(buttonName, prefTextFragment, prefName, minVal, maxVal, defaultVal)
{
   var prefText = getPrefValueText(prefTextFragment, prefName, defaultVal);
   addMenuEntry(buttonName, prefText, function ()
   {
      cef.uiapp.cyclePrefValue(prefName, minVal, maxVal, defaultVal);
      $("#" + buttonName).html(cef.uiapp.locString(getPrefValueText(prefTextFragment, prefName, defaultVal)));
   });
}

//=================================================================================================
function showFrame(frameURL)
{
   hideBoardElements();
   $("#FramePageInner").attr("src", frameURL);
   $("#FramePage").show();
}

//=================================================================================================
function prepareForNewPuzzles(categoryName)
{
   hideAllLoginUI();
   $('#gameslist').hide();
   var navString = "Challenges_" + categoryName;
   clearNavEntries();
   assembleBreadcrumbs(navString);
}

//=================================================================================================
function gotoFirstTutorial()
{
   navigateTo('Training_TrainingTutorial');
   hideBoardElements();
   $('#GameBoard').show();
   cef.uiapp.showGameView();
   cef.uiapp.launchFirstTutorial();
}

//=================================================================================================
function addFriendEntry(index, friendName, personaState, steamID, isHAPlayer)
{
   var downArt = "";  
   var upArt = "";  
   var layout = cef.uiapp.getLayoutMode();
   if (layout == cLayoutMedium)
   {
      if (isHAPlayer)
      {
         downArt = "MenuNav-HA-Dn_Med.png";
         upArt = "MenuNav-HA-Up_Med.png";
      }
      else
      {
         downArt = "MenuNav-Steam-Dn_Med.png";
         upArt = "MenuNav-Steam-Up_Med.png";
      }
   }
   else
   {
      if (isHAPlayer)
      {
         downArt = "MenuNav-HA-Dn_Lge.png";
         upArt = "MenuNav-HA-Up_Lge.png";
      }
      else
      {
         downArt = "MenuNav-Steam-Dn_Lge.png";
         upArt = "MenuNav-Steam-Up_Lge.png";
      }
   }

   addMenuEntryWithArt("NavFriend_" + index, friendName, downArt, upArt, function ()
   {
      //alert("Friend invites are not yet implemented. (" + friendName + ")");
      cef.uiapp.steamFriendClicked(steamID);
   });
   if (personaState == 1)
   {
      $('#NavFriend_' + index).css("-webkit-text-fill-color", "lightgreen");
      //$('#NavFriend_' + friendName).attr("title", "test tooltip");
   }
}

//=================================================================================================
function clearNavEntries()
{
   //alert("clear nav entries");
   $('#navmenu').empty();
   $('#breadcrumbs').empty();
}

//=================================================================================================
function getNavDisplayString(dest)
{
   var navText = dest;
   // move this to C++ and localize
   if (dest == "GamesList")
      navText = "Play!";
   else if (dest == "TrainingBasics")
      navText = "Basics";
   else if (dest == "TrainingTutorial")
      navText = "Tutorial";
   else if (dest == "CustomizeTeams")
      navText = "Heroic Teams";
   else if (dest == "CustomizeAvatars")
      navText = "Avatars";
   else if (dest == "CustomizeTaunts")
      navText = "Taunts";
   else if (dest == "Logout")
      navText = "Log Out";

   return navText;
}

//=================================================================================================
function getNavString(dest)
{
   var navText = getNavDisplayString(dest);
   return cef.uiapp.locString(navText);
}

//=================================================================================================
function getBreadcrumbString(dest)
{
   //Shorter versions of these strings for the breadrumbs.

   var navText = getNavDisplayString(dest);
   // move this to C++ and localize
   if (dest == "CustomizeTeams")
      navText = "Teams";
   else if (dest == "CreateGame")
      navText = "Create";
   else if (dest == "Meet the Council")
      navText = "Civ_humans_DisplayName";
   else if (dest == "Meet the Dark Elves")
      navText = "Civ_darkelves_DisplayName";
   else if (dest == "Meet the Dwarves")
      navText = "Civ_dwarves_DisplayName";
   else if (dest == "Meet the Tribe")
      navText = "Civ_orcs_DisplayName";
   else if (dest == "Meet Team Fortress")
      navText = "Civ_tf2a_DisplayName";

   return cef.uiapp.locString(navText);
}

//=================================================================================================
function addNavMenuEntry(navDest, useBigButton)
{
   // <div class="navMenuEntry" onclick="alert('B');"><img src="heroacademy://data/UI/BarButton.png" class="navMenuBackground" ><p class="navMenuText">TRAINING</p></img></div>
   var navList = navDest.split('_');
   var leafDest = navList[navList.length - 1];
   var displayText = getNavString(leafDest);
   //alert(displayText);

   var buttonClass = "navMenuButton";
   var bigSize = 60;
   var normalSize = 45;
   if (useBigButton)
   {
      buttonClass = "navMenuButtonBig";
      bigSize = 120;
      normalSize = 85;
   }

   var layout = cef.uiapp.getLayoutMode();
   if(layout == cLayoutMedium)
   {
      var downArt = "MenuNav-Dn_Med.png";
      var upArt = "MenuNav-Up_Med.png";
      if (useBigButton)
      {
         downArt = "PlayButton-Dn_Med.png";
         upArt = "PlayButton-Up_Med.png"
         hoverArt = "PlayButton-Up_Med.png";
      }

      var buttonID = 'navMenuButton' + navDest;
      buttonText = "<div id=\"" + buttonID + "\"  class=\"" + buttonClass + "\" style=\"\">" + displayText + "</div>";
      $('#navmenu').append(buttonText);

      fixupButton(buttonID, bigSize, normalSize, downArt, upArt, function () { navigateTo(navDest); }, 278, 275);
   }
   else if(layout == cLayoutLarge)
   {
      var downArt = "MenuNav-Dn_Lge.png";
      var upArt = "MenuNav-Up_Lge.png";
      if (useBigButton)
      {
         downArt = "PlayButton-Dn_Lge.png";
         upArt = "PlayButton-Up_Lge.png"
         hoverArt = "PlayButton-Up_Lge.png";
      }

      var buttonID = 'navMenuButton' + navDest;
      buttonText = "<div id=\"" + buttonID + "\"  class=\"" + buttonClass + "\" style=\"\">" + displayText + "</div>";
      $('#navmenu').append(buttonText);

      fixupButton(buttonID, bigSize, normalSize, downArt, upArt, function () { navigateTo(navDest); }, 338, 335);
   }
   
   overrideStyleByLayoutType();
}


//=================================================================================================
function fixupButtonSmall(buttonID, downArt, upArt)
{
   var bigSize = 28;
   var normalSize = 25;
   fixupButton(buttonID, bigSize, normalSize, downArt, upArt, null, 186, 186);
}

//=================================================================================================
function fixupButtonNoText(buttonID, downArt, upArt, hoverArt, playSound, clickFunc)
{
   $('#' + buttonID).css("background", "url('heroacademy://UI/" + upArt + "') transparent no-repeat");

   $('#' + buttonID).hover(
      function ()
      {
         $(this).css("background", "url('heroacademy://UI/" + hoverArt + "') transparent no-repeat");
      },
      function ()
      {
         // [5/17/12 xemu] ok, this is needed so that if you mouse down, then mouse away, that the button isn't stuck down.  Bleh.
         $(this).css("background", "url('heroacademy://UI/" + upArt + "') transparent no-repeat");
      }
   );

   $('#' + buttonID).mousedown(function ()
   {
      $(this).css("background", "url('heroacademy://UI/" + downArt + "') transparent no-repeat");
   });
   $('#' + buttonID).mouseup(function ()
   {
      if(playSound)
         cef.uiapp.playSound("sound/Generic_Push_Button.mp3");
      $(this).css("background", "url('heroacademy://UI/" + upArt + "') transparent no-repeat");
      if (clickFunc != null)
         clickFunc();
   });
}

//=================================================================================================
function measureContents(elementID, fontSize)
{
   var rulerElement = document.getElementById("StringRuler");
   var element = document.getElementById(elementID);
   rulerElement.style.fontSize = fontSize;
   rulerElement.textContent = element.textContent;
   return [rulerElement.clientWidth, rulerElement.clientHeight];
}

//=================================================================================================
function fixupButton(buttonID, bigSize, normalSize, downArt, upArt, clickFunc, maxWidth, factorWidth)
{
   var measuredSize = measureContents(buttonID, bigSize);
   //cef.uiapp.printf("fixupButton measurements: [x:" + measuredSize[0] + ", y:" + measuredSize[1] + "]\n");

   // first, guess a size starting point based off of overage proportions
   var normalRatio = 1.0;
   if (measuredSize[0] > maxWidth)
   {
      //cef.uiapp.printf("fixupButton adjusting font size for \"" + document.getElementById(buttonID).innerHTML);
      //cef.uiapp.printf("\"; normalSize:" + normalSize + ", bigSize:" + bigSize + ", measuredWidth: " + measuredSize[0] + ", ");

      normalRatio = normalSize / bigSize;
      bigSize = Math.round(bigSize / (measuredSize[0] / factorWidth));
      normalSize = Math.round(bigSize * normalRatio);
      // now see if we fixed the problem
      measuredSize = measureContents(buttonID, bigSize);

      //cef.uiapp.printf("finalNormal:" + normalSize + ", finalBig:" + bigSize + "\n");
      //cef.uiapp.printf("maxWidth:" + maxWidth + ", finalWidth:" + measuredSize[0] + "\n");
   }
   // if that didn't work, iteratively decrease size until it does
   while (measuredSize[0] > maxWidth)
   {
      bigSize = bigSize - 2;
      normalSize = Math.round(bigSize * normalRatio);
      measuredSize = measureContents(buttonID, bigSize);

      //cef.uiapp.printf("Iterating on size: testing size " + bigSize + " resulting in width " + measuredSize[0] + " out of " + maxWidth + "\n");
   }
   $('#' + buttonID).css("font-size", normalSize);
   $('#' + buttonID).css("background", "url('heroacademy://UI/" + upArt + "') transparent no-repeat");

   $('#' + buttonID).hover(
      function ()
      {
         $('#' + buttonID).css("font-size", bigSize);
         //$(this).css("background", "url('heroacademy://UI/" + hoverArt + "') transparent no-repeat"); 
      },
      function ()
      {
         $('#' + buttonID).css("font-size", normalSize);
         // [5/17/12 xemu] ok, this is needed so that if you mouse down, then mouse away, that the button isn't stuck down.  Bleh.
         $(this).css("background", "url('heroacademy://UI/" + upArt + "') transparent no-repeat");
      }
   );

   $('#' + buttonID).mousedown(function ()
   {
      $(this).css("background", "url('heroacademy://UI/" + downArt + "') transparent no-repeat");
   });
   $('#' + buttonID).mouseup(function ()
   {
      cef.uiapp.playSound("sound/Generic_Push_Button.mp3");
      $(this).css("background", "url('heroacademy://UI/" + upArt + "') transparent no-repeat");
      if (clickFunc != null)
         clickFunc();
   });
}

//=================================================================================================
function formSubmitPlaySound()
{
   cef.uiapp.playSound("sound/Generic_Push_Button.mp3");
   return true;
}

//=================================================================================================
function fixupButtonWithHeight(buttonID, bigSize, normalSize, downArt, upArt, clickFunc, maxWidth, factorWidth, maxHeight) 
{
   var measuredSize = measureContents(buttonID, bigSize);
   // step down our big font one point at a time until we've found a reasonable height
   var normalRatio = normalSize / bigSize;
   while (measuredSize[1] > maxHeight) 
   {
      bigSize = bigSize - 1;
      normalSize = Math.round(bigSize * normalRatio);
      measuredSize = measureContents(buttonID, bigSize);

      //cef.uiapp.printf("Iterating on size: testing size " + bigSize + " resulting in width " + measuredSize[0] + " out of " + maxWidth + "\n");
   }

   fixupButton(buttonID, bigSize, normalSize, downArt, upArt, clickFunc, maxWidth, factorWidth);
}


//=================================================================================================
function fixupButtonSubtext(buttonID, textID, hoverTopBig, hoverTopNormal, bigSize, normalSize, downArt, upArt, clickFunc)
{
   // [5/24/12 xemu] try setting this to the big size, see if we overflow, and if so, scale both big and small sizes down.
   var maxWidth = 164;
   //alert(buttonID + " " + textID);
   $('#' + textID).css("font-size", bigSize);
   //var bigWidth = document.getElementById(textID + 'P').scrollWidth;
   var bigWidth = document.getElementById(textID).scrollWidth;
   //alert(textID + " " + bigWidth);

   $('#' + textID).css("top", hoverTopNormal);
   if (bigWidth > maxWidth)
   {
      //var overFactor = (bigWidth / maxWidth);
      // [6/4/12 xemu] forcing this to just one alternate "small" size" for easier positioning
      var overFactor = 2.2;

      //alert(bigWidth + " " + maxWidth);
      bigSize = bigSize / overFactor;
      //var delta = normalSize - bigSize;
      //hoverTopNormal = hoverTopNormal + (6 * overFactor);
      //hoverTopBig = hoverTopBig + (11 * overFactor);

      //alert(delta);
      //alert(hoverTopBig + " " + hoverTopNormal + " " + overFactor);
      hoverTopBig = -1; 
      hoverTopNormal = 4;
      normalSize = bigSize * 0.8;
      //hoverTopNormal = hoverTopBig * (1 + (1 - 0.8));
      $('#' + textID).css("top", hoverTopNormal);
   }
   $('#' + textID).css("font-size", normalSize);

   $('#' + buttonID).hover(
      function ()
      {
         $('#' + textID).css("font-size", bigSize);
         $('#' + textID).css("top", hoverTopBig);
         //$(this).css("background", "url('heroacademy://UI/" + hoverArt + "') transparent no-repeat"); 
      },
      function ()
      {
         $('#' + textID).css("font-size", normalSize);
         $('#' + textID).css("top", hoverTopNormal);
         $(this).css("background", "url('heroacademy://UI/" + upArt + "') transparent no-repeat");
      }
   );

   $('#' + buttonID).mousedown(function ()
   {
      $(this).css("background", "url('heroacademy://UI/" + downArt + "') transparent no-repeat");
   });
   $('#' + buttonID).mouseup(function ()
   {
      $(this).css("background", "url('heroacademy://UI/" + upArt + "') transparent no-repeat");
      clickFunc();
   });

}

//=================================================================================================
function addMenuEntry(buttonID, displayText, onClickFunc)
{
   var buttonClass = "navMenuButton";
   var buttonText = "<div id=\"" + buttonID + "\"  class=\"" + buttonClass + "\"  >" + cef.uiapp.locString(displayText) + "</div>";
   var bigSize = 60;
   var normalSize = 45;

   var layout = cef.uiapp.getLayoutMode();
   if(layout == cLayoutMedium)
   {
      var downArt = "MenuNav-Dn_Med.png";
      var upArt = "MenuNav-Up_Med.png"
      $('#navmenu').append(buttonText);
      fixupButton(buttonID, bigSize, normalSize, downArt, upArt, function () { onClickFunc(); }, 278, 275);
   }
   else if(layout == cLayoutLarge)
   {
      var downArt = "MenuNav-Dn_Lge.png";
      var upArt = "MenuNav-Up_Lge.png"
      $('#navmenu').append(buttonText);
      fixupButton(buttonID, bigSize, normalSize, downArt, upArt, function () { onClickFunc(); }, 338, 335);
   }

}

//=================================================================================================
function addMenuEntryWithArt(buttonID, displayText, downArt, upArt, onClickFunc)
{
   var buttonClass = "navMenuButtonLeftAlign";
   var buttonText = "<div id=\"" + buttonID + "\"  class=\"" + buttonClass + "\" style=\"background:url('heroacademy://UI/" + upArt + "') transparent no-repeat;\" >" + cef.uiapp.locString(displayText) + "</div>";

   var layout = cef.uiapp.getLayoutMode();
   if(layout == cLayoutMedium)
   {
      var bigSize = 40;
      var normalSize = 35;
      $('#navmenu').append(buttonText);
      //alert($('#' + buttonID).html());
      fixupButton(buttonID, bigSize, normalSize, downArt, upArt, function () { onClickFunc(); }, 197, 190);
   }
   else if(layout == cLayoutLarge)
   {
      var bigSize = 50;
      var normalSize = 45;
      $('#navmenu').append(buttonText);
      //alert($('#' + buttonID).html());
      fixupButton(buttonID, bigSize, normalSize, downArt, upArt, function () { onClickFunc(); }, 265, 260);
   }
   
   overrideStyleByLayoutType();
}

//=================================================================================================
function updateMenuEntryWithArt(buttonID, displayText, downArt, upArt, onClickFunc)
{
   $("#" + buttonID).css("background", "url('heroacademy://UI/" + upArt + "') transparent no-repeat");
   
   var layout = cef.uiapp.getLayoutMode();
   if(layout == cLayoutMedium)
   {
      var bigSize = 40;
      var normalSize = 35;
      fixupButton(buttonID, bigSize, normalSize, downArt, upArt, function () { onClickFunc(); }, 197, 190);
   }
   else if(layout == cLayoutLarge)
   {
      var bigSize = 50;
      var normalSize = 45;
      fixupButton(buttonID, bigSize, normalSize, downArt, upArt, function () { onClickFunc(); }, 265, 260);
   }
}

//=================================================================================================
function assembleBreadcrumbs(navText)
{
   navList = navText.split('_');
   if (!navText)
      addBreadcrumb(0, "Home", "", true);
   else
      addBreadcrumb(0, "Home", "", false);
   $.each(navList, function (i, val)
   {
      var destination = "";
      for (j = 0; j <= i; j++)
      {
         if (j > 0)
            destination += "_";
         destination += navList[j];
      }
      if (destination)
      {
         var finalEntry = false;
         if (i == navList.length-1)
            finalEntry = true;
         addBreadcrumb(i + 1, getBreadcrumbString(val), destination, finalEntry);
      }
   });
}

//=================================================================================================
function parseDestination(navText)
{
   navList = navText.split('_');
   // our actual destination is the last item in the list
   leafDest = navList[navList.length - 1];
   return leafDest;
}

//=================================================================================================
function addBreadcrumb(index, displayText, destination, finalEntry)
{
   var layout = cef.uiapp.getLayoutMode();
   if((layout == cLayoutMedium) && (index == 1) && !finalEntry)
   {
      //Use a "..." mini breadcrumb
      //alert("AB " + displayText + " / " + destination + " / " + finalEntry);
      var buttonID = "BreadCrumb" + destination.split(' ').join(''); //Must remove spaces to use as a buttonID
      var buttonClass = "breadcrumbButtonMini";
      var leftpos = index * 130;
      var buttonArt = 'NavButton-Up_Mini.png';
      buttonText = "<div id=\"" + buttonID + "\"  class=\"" + buttonClass + "\" style=\"position:absolute;left:" + leftpos + "px\; background:url('" + buttonArt + "') transparent no-repeat;\" >...</div>";
      var bigSize = 35;
      var normalSize = 32;
      var downArt = "NavButton-Dn.png";
      var upArt = buttonArt;
      $('#breadcrumbs').append(buttonText);
      fixupButton(buttonID, bigSize, normalSize, downArt, upArt, function () { navigateTo(destination.toString()); }, 84, 80);
   }
   else
   {
      //alert("AB " + displayText + " / " + destination + " / " + finalEntry);
      var buttonID = "BreadCrumb" + destination.split(' ').join(''); //Must remove spaces to use as a buttonID
      var buttonClass = "breadcrumbButton";
      var leftpos = index * 130;
      if((layout == cLayoutMedium) && (index == 2) && finalEntry)
         leftpos = leftpos - 72; //Previous breadcrumb is mini breadcrumb. Shift left by 72
      var buttonArt = 'NavButton-Up.png';
      if (finalEntry)
         buttonArt = 'NavButton-Glow.png';
      buttonText = "<div id=\"" + buttonID + "\"  class=\"" + buttonClass + "\" style=\"position:absolute;left:" + leftpos + "px\; background:url('" + buttonArt + "') transparent no-repeat;\" >" + cef.uiapp.locString(displayText) + "</div>";
      var bigSize = 35;
      var normalSize = 32;
      var downArt = "NavButton-Dn.png";
      var upArt = buttonArt;
      $('#breadcrumbs').append(buttonText);
      fixupButton(buttonID, bigSize, normalSize, downArt, upArt, function () { navigateTo(destination.toString()); }, 84, 80);
   }
   // [5/12/2012 xemu] add in the spacers
   if (index > 0)
   {
      var spacerpos = leftpos - 15;
      spacerText = "<p style=\"background:url('heroacademy://UI/NavArrow.png') transparent no-repeat; position:absolute; left:" + spacerpos + "px;top:8px;margin:0px;width:16px;height:24px;\">";
      //alert(spacerText);
      $('#breadcrumbs').append(spacerText);
   }
}

