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

function showCustomizeColorsScreen()
{
   hideBoardElements();
   $('#CustomizeColors').show();

   var colorUnlocked = cef.uiapp.colorsUnlocked();
   buildColorButtons(colorUnlocked);

   removeById('UniformColorsBuyButton');
   if (!colorUnlocked)
   {
      var buyButton = "<div id=\"UniformColorsBuyButton\" class=\"buttonBuy\" style=\"line-height:36px; position:absolute; top:18px; right:25px; z-index:2;\">" + cef.uiapp.locString("Buy") + "</div>";
      $('#CustomizeColors').append(buyButton);
      fixupButton("UniformColorsBuyButton", 45, 35, "BuyBtn-Dn.png", "BuyBtn-Up.png", function ()
      {
         upsellDLC('UNIFORM_COLORS', 'showCustomizeColorsScreen();');
      }, 186, 186);
   }

   setPickedColor(true, cef.uiapp.getPlayerColor(true), false, colorUnlocked);
   setPickedColor(false, cef.uiapp.getPlayerColor(false), false, colorUnlocked);
   $('#CustomColorBaseAvatar').hide();
   $('#CustomColorColorAvatar').hide();

   var avatar = "heroacademy://data/" + cef.uiapp.getLocalAvatar();
   $('#CustomColorBaseAvatar').attr("src", avatar);

   colorizeAvatar(true, cef.uiapp.getPlayerColor(true), 'CustomColorBaseAvatar', 'CustomColorColorAvatar', cef.uiapp.getLocalAvatarColor());
}

//=================================================================================================
function colorizeAvatar(homeColor, colorIndex, baseID, colorID, colorFile, extraID)
{
   // [7/23/12 xemu] early out if the color file doesn't exist
   if (!colorFile)
   {
      $('#' + colorID).hide();
      return;
   }

   var colorCanvas = document.getElementById(colorID);

   var colorImage = new Image();
   var colorString = cef.uiapp.getColorString(homeColor, colorIndex);
   //var colorParamsTemp = colorString.split('(');
   var colorParamsRaw = colorString.slice(4);
   //alert(colorParamsRaw);
   var colorParams = colorParamsRaw.split(',');
   var r = parseInt(colorParams[0], 10);
   var g = parseInt(colorParams[1], 10);
   var b = parseInt(colorParams[2].slice(0, -2), 10);
   //alert(b);
   colorImage.onload = function ()
   {
      colorizeCanvas(colorCanvas, colorImage, r, g, b);
      $('#' + baseID).show();
      $('#' + colorID).show();
      if (extraID)
         $('#' + extraID).show();
   }
   colorImage.src = "heroacademy://data/" + colorFile; //  cef.uiapp.getLocalAvatarColor();
}

//=================================================================================================
function buildColorButtons(isColorUnlocked)
{
   $('#ColorHomePicker').empty();
   $('#ColorAwayPicker').empty();
   addColorButton('ColorHomePicker', 0, true, isColorUnlocked);
   addColorButton('ColorHomePicker', 1, true, isColorUnlocked);
   addColorButton('ColorHomePicker', 2, true, isColorUnlocked);
   addColorButton('ColorHomePicker', 3, true, isColorUnlocked);
   addColorButton('ColorHomePicker', 4, true, isColorUnlocked);
   addColorButton('ColorAwayPicker', 0, false, isColorUnlocked);
   addColorButton('ColorAwayPicker', 1, false, isColorUnlocked);
   addColorButton('ColorAwayPicker', 2, false, isColorUnlocked);
   addColorButton('ColorAwayPicker', 3, false, isColorUnlocked);
   addColorButton('ColorAwayPicker', 4, false, isColorUnlocked);
}

//=================================================================================================
function addColorButton(containerID, colorIndex, isHomeColor, isColorUnlocked)
{
   var colorText = cef.uiapp.getColorString(isHomeColor, colorIndex);

   var layout = cef.uiapp.getLayoutMode();
   if(layout == cLayoutMedium)
   {
      var totalArea = 735;
      var colorBoxSize = 110;
      var colorDivHeight = 175;
   }
   else if(layout == cLayoutLarge)
   {
      var totalArea = 814;
      var colorBoxSize = 135;
      var colorDivHeight = 200;
   }

   var columnSpacing = 10;
   var columnWidth = (totalArea - (columnSpacing * 5)) / 5;
   var colorBoxLeft = (columnWidth - colorBoxSize) / 2;
   var leftPos = colorIndex * (columnWidth + columnSpacing);
   var socketLeft = colorBoxLeft + ((colorBoxSize - 23) / 2) + 2;
   var socketID = "ColorSocket_" + isHomeColor + "_" + colorIndex;
   var displayID = "ColorDisplay_" + isHomeColor + "_" + colorIndex;
   var clickCmd = "upsellDLC('UNIFORM_COLORS', 'showCustomizeColorsScreen();')";
   if (isColorUnlocked || (colorIndex == 0))
      clickCmd = "setPickedColor(" + isHomeColor + ", " + colorIndex + ", true, " + isColorUnlocked + ");";
   var displayTop = 22;
   var colorDiv = "<div onclick=\"" + clickCmd + "\" style=\"position:absolute; left:" + leftPos + "px; width:" + columnWidth + "px; height:" + colorDivHeight + "px; margin:0px; padding:0px;\">";
   var colorDisplayShadow = ""; //  "<div style=\"position:absolute; top:7px; left:" + (colorBoxLeft-2) + "px; width:" + (colorBoxSize+5) + "px; height:" + (colorBoxSize+5) + "px; background-color:black; -webkit-border-radius:20px; border-color:black;\"></div>";
   var colorDisplay = "<div id=\"" + displayID + "\" style=\"position:absolute; top:" + displayTop + "px; left:" + colorBoxLeft + "px; width:" + colorBoxSize + "px; height:" + colorBoxSize + "px; background-color:" + colorText + "-webkit-border-radius:10px; border:4px solid black;\"></div>";
   var socketArt = "heroacademy://data/UI/Socket-Disabled.png";
   if (isColorUnlocked || (colorIndex == 0))
      socketArt = "heroacademy://data/UI/Socket-Empty.png";
   var colorSocket = "<div id=\"" + socketID + "\" style=\"background:url('" + socketArt + "') transparent no-repeat; position:absolute; width:23px; height:23px; bottom:2px;left:" + socketLeft + "px;\"></div>";
   var colorEnd = "</div>";

   $('#' + containerID).append(colorDiv + colorDisplayShadow + colorDisplay + colorSocket + colorEnd);

   if (isColorUnlocked || (colorIndex == 0))
   {
      $('#' + displayID).hover(
         function ()
         {
            var bigSize = colorBoxSize * 1.1;
            var delta = bigSize - colorBoxSize;
            $(this).css("width", bigSize)
            .css("height", bigSize)
            .css("top", displayTop - (delta / 2))
            .css("left", colorBoxLeft - (delta / 2));
         },
         function ()
         {
            $(this).css("width", colorBoxSize)
            .css("height", colorBoxSize)
            .css("top", displayTop)
            .css("left", colorBoxLeft);
         }
      );
   }
}

//=================================================================================================
function setPickedColor(homeColor, colorIndex, setOnServer, colorUnlocked)
{
   clearPickedColor(homeColor, colorUnlocked);

   var socketID = "ColorSocket_" + homeColor + "_" + colorIndex;
   if (colorUnlocked || (colorIndex == 0))
      $("#" + socketID).css("background", "url('heroacademy://data/UI/Socket-Filled.png') transparent no-repeat");

   if (setOnServer)
   {
      cef.uiapp.selectPlayerColor(homeColor, colorIndex);
      colorizeAvatar(homeColor, colorIndex, 'CustomColorBaseAvatar', 'CustomColorColorAvatar', cef.uiapp.getLocalAvatarColor());
   }
}

//=================================================================================================
function clearPickedColor(homeColor, colorUnlocked)
{
   var i;
   for (i=0; i < 5; i++)
   {
      var socketID = "ColorSocket_" + homeColor + "_" + i;
      if (colorUnlocked || (i == 0))
         $("#" + socketID).css("background", "url('heroacademy://data/UI/Socket-Empty.png') transparent no-repeat");
      else
         $("#" + socketID).css("background", "url('heroacademy://data/UI/Socket-Disabled.png') transparent no-repeat");
   }
}

//=================================================================================================
function colorizeCanvas(myCanvas, image, r, g, b)
{

   // create a new canvas element
   //var myCanvas = document.createElement("canvas");
    //alert(r + " " + g + " " + b);
   var myCanvasContext = myCanvas.getContext("2d");
   var imgWidth = image.width;
   var imgHeight = image.height;
   //alert("CC " + imgWidth + " " + imgHeight);

   //myCanvasContext.fillStyle = "rgb(0,0,0,0)";
   //myCanvasContext.fillRect(0, 0, myCanvas.width, myCanvas.height);
   //myCanvasContext.clear();
   
   // set the width and height to the same as the image
   //myCanvas.width = imgWidth;
   //myCanvas.height = imgHeight;

   var tempCanvas = document.createElement('canvas'); //  Canvas();
   var tempContext = tempCanvas.getContext("2d");
   // draw the image
   tempContext.drawImage(image, 0, 0, myCanvas.width, myCanvas.height);

   // get all the image data into an array
   //alert(tempContext + " " + imgWidth + " " + imgHeight);
   var imageData = tempContext.getImageData(0, 0, imgWidth, imgHeight);
   //alert(imageData);

   // go through it all...
   for (j = 0; j < imageData.width; j++)
   {
      for (i = 0; i < imageData.height; i++)
      {
         // index: red, green, blue, alpha, red, green, blue, alpha..etc.
         var index = (i * 4) * imageData.width + (j * 4);
         var alpha = imageData.data[index + 3];
         //if (alpha == 0)
            //continue;
         var red = imageData.data[index];
         var green = imageData.data[index+1];
         var blue = imageData.data[index + 2];

         /*
         if (alpha > 0)
         {
            alert(red + " " + green + " " + blue);
         }
         */

         // set the red to the same
         imageData.data[index] = r * (red / 256);

         // set the rest to black
         imageData.data[index + 1] = g * (green / 256);
         imageData.data[index + 2] = b * (blue / 256); 
         imageData.data[index + 3] = alpha;
         //delete c;
      }
   }

   // put the image data back into the canvas
   //alert(imageData.width + " " + imageData.height);
   myCanvasContext.putImageData(imageData, 0, 0, 0, 0, imageData.width, imageData.height);

   // append it to the body
   //document.body.appendChild(myCanvas);
}

//=================================================================================================
function showAvatarSelect(pack1, pack2, pack3)
{
   hideBoardElements();
   $('#CustomizeAvatars').show();
   $('#AvatarContainer').empty();
   var packCount = 0;
   var steamAvatarsUnlocked = true; //pack2 and pack3 unlocked via steamDLC
   packCount = cef.uiapp.addAvatarsForPack(pack1, packCount);
   if (pack2)
   {
      packCount = cef.uiapp.addAvatarsForPack(pack2, packCount);
      if(!cef.uiapp.ownsAvatarPack(pack2))
         steamAvatarsUnlocked = false;
   }
   if (pack3)
   {
      packCount = cef.uiapp.addAvatarsForPack(pack3, packCount);
      if(!cef.uiapp.ownsAvatarPack(pack3))
         steamAvatarsUnlocked = false;
   }
   avatarSocketCount = packCount;

   var hoverDiv = "<div id=\"AvatarHover\" style=\"display:none; background:url('heroacademy://UI/SelectTeamGlow.png') transparent no-repeat; background-size:100%; position:absolute;z-index:0;width:148px; height:148px;\"></div>";
   $('#AvatarContainer').append(hoverDiv);

   $('#CustomAvatarBaseAvatar').hide();
   $('#CustomAvatarColorAvatar').hide();

   var avatar = "heroacademy://data/" + cef.uiapp.getLocalAvatar();
   $('#CustomAvatarBaseAvatar').attr("src", avatar);

   colorizeAvatar(true, cef.uiapp.getPlayerColor(true), 'CustomAvatarBaseAvatar', 'CustomAvatarColorAvatar', cef.uiapp.getLocalAvatarColor());

   removeById('AvatarsBuyButton');
   if (!steamAvatarsUnlocked)
   {
      var buyButton = "<div id=\"AvatarsBuyButton\" class=\"buttonBuy\" style=\"line-height:36px; position:absolute; top:18px; right:25px; z-index:2;\">" + cef.uiapp.locString("Buy") + "</div>";
      $('#CustomizeAvatars').append(buyButton);
      fixupButton("AvatarsBuyButton", 45, 35, "BuyBtn-Dn.png", "BuyBtn-Up.png", function ()
      {
         upsellDLC(pack2, 'showAvatarPage(currentAvatarPage)');
      }, 186, 186);
   }

   /*
   $('#AvatarContainer').hover(
      function () {  },
      function () { $("#AvatarHover").hide();  }
   );
   */
   
}

//=================================================================================================
function addAvatarPackEntry(index, packName, trueIndex, avatarFile, avatarColorFile, colorIndex, packOwned)
{
   var layout = cef.uiapp.getLayoutMode();
   if(layout == cLayoutMedium)
   {
      var totalWidth = 924;
      var avatarSpacing = 26;
      var avatarSpacingVert = 38;
      var glowOffsetX = -8;
      var buyTeamBannerUp = "BuyTeamButton_Med-Up.png";
      var buyTeamBannerDn = "BuyTeamButton_Med-Dn.png";
   }
   else if(layout == cLayoutLarge)
   {
      var totalWidth = 980;
      var avatarSpacing = 14;
      var avatarSpacingVert = 52;
      var glowOffsetX = 0;
      var buyTeamBannerUp = "BuyTeamButton_Lge-Up.png";
      var buyTeamBannerDn = "BuyTeamButton_Lge-Dn.png";
   }
   var numColumns = 6;
   var avatarWidth = (totalWidth - (avatarSpacing * numColumns)) / numColumns;
   //alert(avatarWidth);
   var avatarHeight = avatarWidth;
   var socketLeft = (avatarWidth - 23) / 2;

   var topPos = Math.floor(index / numColumns) * (avatarHeight + avatarSpacingVert);
   //alert(topPos);
   var leftPos = (index % numColumns) * (avatarWidth + avatarSpacing);

   var clickFunc = "upsellDLC('" + packName + "', 'showAvatarPage(currentAvatarPage);');"
   if (packOwned)
      clickFunc = "avatarSelect('" + packName + "', " + trueIndex + ", " + index + ");";
   //alert(clickFunc);
   var avatarStart = "<div id='Avatar" + index + "' style='position:absolute; top:" + topPos + "px; left:" + leftPos + "px; width:" + avatarWidth + "px; height:" + (avatarHeight + 23 + 12) + "px;z-index:1' onclick=\"" + clickFunc + "\">";
   var avatarImg = "<img id='AvatarBase" + index + "' src='heroacademy://data/" + avatarFile + "' style='display:none; position:absolute;width:" + avatarWidth + "px; height:" + avatarHeight + "px;'>";
   var avatarCanvas = "<canvas id='AvatarColor" + index + "' style='position:absolute; display:none' width='" + avatarWidth + "' height='" + avatarHeight + "'></canvas>";
   var socketArt = "heroacademy://data/UI/Socket-Disabled.png";
   if (packOwned)
      socketArt = "heroacademy://data/UI/Socket-Empty.png";
   var socketArtActive = "heroacademy://data/UI/Socket-Filled.png";
   var socketID = 'AvatarSocket' + index;
   var socketID2 = 'AvatarSocketActive' + index;
   var socket1 = "<div id=\"" + socketID + "\" style=\"display:none;background-image:url('" + socketArt + "'); position:absolute; width:23px; height:23px; bottom:8px;left:" + socketLeft + "px;z-index:2\"></div>";

   //// [8/2/2012 sveligati] - New version of DLCs: Free, Sampler, and Super avatar packs now come with team. Council(team, free, sampler, super) and TF2(team, basic, variety) come free with base game.
   //if (packName.substr(-5) === "_FREE" && !packOwned) //If the avatar comes with a team, change the unowned socket to the "Buy Team" logo.
   //{
   //   var freeWithTeam = true;
   //   socket1 = "<div id=\"" + socketID + "\" style=\"display:none;background-image:url('heroacademy://UI/" + buyTeamBannerUp + "');\" class=\"buyTeamBanner\">" + cef.uiapp.locString("Buy Team") + "</div>";
   //   if(layout == cLayoutMedium)
   //      socket1 = "<div id=\"" + socketID + "\" style=\"display:none;background-image:url('heroacademy://UI/" + buyTeamBannerUp + "'); left:-7px; bottom:-2px; width:141px; height:37px; line-height:27px; \" class=\"buyTeamBanner\">" + cef.uiapp.locString("Buy Team") + "</div>";
   //}

   var socket2 = "<div id=\"" + socketID2 + "\" style=\"display:none;background-image:url('" + socketArtActive + "'); position:absolute; width:23px; height:23px; bottom:8px;left:" + socketLeft + "px;z-index:2\"></div>";
   var avatarEnd = "</div>";
   $('#AvatarContainer').append(avatarStart + avatarImg + avatarCanvas + socket1 + socket2 + avatarEnd);
   colorizeAvatar(true, colorIndex, 'AvatarBase' + index, 'AvatarColor' + index, avatarColorFile, socketID);

   if(freeWithTeam)
      fixupButton(socketID, 35, 30, buyTeamBannerDn, buyTeamBannerUp, null, 186, 186);

   if (packOwned)
   {
      var avatarIndex = index;
      $("#Avatar" + avatarIndex).hover(
         function ()
         {
            $("#AvatarHover").css("left", (leftPos + glowOffsetX) + "px")
            .css("top", (topPos + avatarHeight - 64).toString() + "px");
            $("#AvatarHover").show();

            /*
            $("#AvatarBase" + avatarIndex).css("width", (avatarWidth + 8).toString() + 'px')
            .css("height", (avatarWidth + 8).toString() + 'px')
            .css("top", '-4px')
            .css("left", '-4px');
            */
            //colorizeAvatar(true, colorIndex, 'AvatarBase' + avatarIndex, 'AvatarColor' + avatarIndex, avatarColorFile);
         },
         function ()
         {
            $("#AvatarHover").hide();

            /*
            $("#AvatarBase" + avatarIndex).css("width", (avatarWidth).toString() + 'px')
            .css("height", (avatarWidth).toString() + 'px')
            .css("top", '0px')
            .css("left", '0px');
            */
            //colorizeAvatar(true, colorIndex, 'AvatarBase' + avatarIndex, 'AvatarColor' + avatarIndex, avatarColorFile);
         }
      );
   }
}

//=================================================================================================
function avatarSelect(packName, trueIndex, avatarIndex)
{
   //alert("AS " + packName + " " + trueIndex + " " + avatarIndex);
   var socketID = 'AvatarSocket' + avatarIndex;
   var socketActiveID = 'AvatarSocketActive' + avatarIndex;
   $("#" + socketActiveID).show();
   $("#" + socketID).hide();
   resetAllAvatarSockets(socketID);
   //alert("B " + $("#" + socketID).css("background-image"));
   cef.uiapp.selectAvatar(packName, trueIndex);

   $('#CustomAvatarBaseAvatar').hide();
   $('#CustomAvatarColorAvatar').hide();
   var avatar = "heroacademy://data/" + cef.uiapp.getLocalAvatar();
   $('#CustomAvatarBaseAvatar').attr("src", avatar);
   colorizeAvatar(true, cef.uiapp.getPlayerColor(true), 'CustomAvatarBaseAvatar', 'CustomAvatarColorAvatar', cef.uiapp.getLocalAvatarColor());
}

//=================================================================================================
function resetAllAvatarSockets(excludeSocket)
{
   var i = 0;
   //alert("ASC " + avatarSocketCount);
   for (i = 0; i < avatarSocketCount; i++)
   {
      var socketID = 'AvatarSocket' + i;
      if (socketID == excludeSocket)
         continue;
      var socketActiveID = 'AvatarSocketActive' + i;
      $("#" + socketID).show();
      $("#" + socketActiveID).hide();
   }
}

//=================================================================================================
function showTeamDetails(teamName)
{
   hideBoardElements();
   $('#TeamDetailEntries0').empty();
   $('#TeamDetailEntries1').empty();
   $('#TeamDetailEntries2').empty();
   removeById('TeamDetailBackButton');
   removeById('TeamDetailBuyButton');
   cef.uiapp.populateTeamDetails(teamName);
   $('#TeamDetails').show();
   //cef.uiapp.populateTeamEntityDetails(teamName);
}

//=================================================================================================
function addTeamDetails(teamName, teamInvID, teamDisplayName, teamColor, teamDescription, teamBackground, teamEmblem, teamBonusIcon, teamBonusName, teamBonusText, teamUnlocked)
{
   $("#TeamDetailContainer").hide();

   var useBackground = "heroacademy://" + teamBackground;
   //alert(useBackground);
   $('#TeamDetailImage').attr("src", "");
   $('#TeamDetailEmblem').attr("src", "heroacademy://data/" + teamEmblem);
   $('#TeamDetailName').html(teamDisplayName);
   $('#TeamDetailName')[0].style.textShadow = "2px 2px " + teamColor;

   $('#TeamDetailDescription').html(teamDescription);

   addDetailEntry(2, teamBonusName, cef.uiapp.locString("Team Bonus"), teamBonusIcon, teamBonusText);

   if (!teamUnlocked)
   {
      var buyButton = "<div id=\"TeamDetailBuyButton\" class=\"buttonBuy\" style=\"line-height:36px; position:absolute; top:18px; right:25px; z-index:2;\">" + cef.uiapp.locString("Buy") + "</div>";
      $('#TeamDetails').append(buyButton);
      fixupButton("TeamDetailBuyButton", 45, 35, "BuyBtn-Dn.png", "BuyBtn-Up.png", function ()
      {
         upsellDLC(teamInvID, '$("#TeamDetailBuyButton").hide();');
         //alert("foo");
      }, 186, 186);
   }

   $('#TeamDetailImage').load( function ()
   {
      $('#TeamDetailContainer').show();
      $('#TeamDetailImage').show();
   });
   $('#TeamDetailImage').attr("src", useBackground);
}

//=================================================================================================
function addTeamLongDesc(longDesc)
{
   $('#TeamDetailLongDesc').html(longDesc);
}

//=================================================================================================
function addDetailEntry(column, entryTitle, entrySubtitle, entryIcon, entryText)
{
   var entryStart = "<div style=\"position:relative; height:100px; width:100%;\">";
   var entryImage = "<img src=\"heroacademy://data/" + entryIcon + "\" style=\"position:absolute; width:96px; height:96px\">";
   var subtitleStyle = 'margin-left:15px;';
   var titleStyle = 'position:absolute;left:105px;top:12px';
   var entryStyle = 'position:absolute;left:105px;top:42px';
   if (cef.uiapp.getUseSmallTeamDetails())
   {
      subtitleStyle = 'margin-left:7px;font-size:12px';
      titleStyle = 'position:absolute;left:105px;top:12px; font-size:22px;';
      entryStyle = 'position:absolute;left:105px;top:42px; font-size:18px';
   }

   var entryTitlePara = "<p class=\"teamDetailTitle\" style=\"" + titleStyle + "\">" + entryTitle + "<span class=\"teamDetailSubtitle\" style=\"" + subtitleStyle + "\">" + entrySubtitle + "</span></p>";
   var entryDisplay = "<p class=\"teamDetailText\" style=\"" + entryStyle + "\">" + entryText + "</p>";
   var entryEnd = "</div>";
   $('#TeamDetailEntries' + column.toString()).append(entryStart + entryImage + entryTitlePara + entryDisplay + entryEnd);
}

//=================================================================================================
function addTeamHelpBackButton(oldScreen, gameBoard)
{
   var backButton = "<div id=\"TeamDetailBackButton\" class=\"buttonBack\" style=\"line-height:36px; position:absolute; top:18px; left:12px; z-index:2;\">" + cef.uiapp.locString("Back") + "</div>";
   $('#TeamDetails').append(backButton);
   fixupButton("TeamDetailBackButton", 45, 35, "BackBtn-Dn.png", "BackBtn-Up.png", function ()
   {
      $('#TeamDetails').hide();
      $('#' + oldScreen).show();
      if (gameBoard)
      {
         cef.uiapp.showGameView();         
      }
   }, 186, 186);

}

//=================================================================================================
