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

var cqrTimeout;
var preLoginDestination = "";
var currentLoginUI = "";
var currentPurchasePageRefresh = "";

//==================================   Navigation   ===============================================
//=================================================================================================
function hideAllLoginUI()
{
   $('#PreloginUI').hide();
   $('#AccountCreateUI').hide();
   $('#LoginUI').hide();
   $('#PasswordResetUI').hide();
   $('#SetPasswordUI').hide();
   
   // Not really a login UI but whatever
   $('#FirstTimeSplashScreen').hide();
   currentLoginUI = "";
}

//=================================================================================================
function switchToLoginUI(uistring)
{
   //Display various login UI pages independently of breadcrumbs and NavEntries
   $('#gameslist').hide();
   clearChat();
   hideBoardElements();

   hideAllLoginUI();
   $(uistring).show();
   currentLoginUI = uistring;
}

//=================================================================================================
function clickCancelButton()
{
   switch(currentLoginUI)
   {
   case '#PasswordResetUI':
      switchToLoginUI('#LoginUI');
      break;
   case '#LoginUI':
   case '#AccountCreateUI':
      switchToLoginUI('#PreloginUI');
      break;
   case '#SetPasswordUI':
      cancelSetPassword();
      break;
   case '#TeamSelect': //Not really login UI but whatevs.
      $('#TeamSelectDeclineGame').click();
      break;
   case '#PreloginUI':
   case '':
   default:
      break; //Do nothing.
   }
}

//==================================   Launch   ===================================================
//=================================================================================================
function prepLaunch()
{
   //Dynamically prepares various resolution layouts in C++. Initializes game.
   cef.uiapp.prepLaunch();
}

function loadingFinished(isFirstGame)
{
   if(isFirstGame)
   {
      $('#FirstTimeSplashScreen').show();
   }
   else
   {
      //Called from C++ after prepLaunch is finished.
      navigateTo("Home");

      //Attempt to autologin
      cef.uiapp.autoLogin();
   }
   cef.uiapp.closeSplashScreen();
}

function skipTutorial()
{
   cef.uiapp.setNotFirstGame();
   navigateTo("Home");
   cef.uiapp.autoLogin();
}

//==================================   Login   ====================================================
//=================================================================================================
function loginMagic(navTextOfDestination)
{
   //Force login through autologin, create account, or existing account(+forgotpassword) login pages
   //Freeze the breadcrumbs during this process and magically return the user back to their prior destination

   if(isLoggedIn())
   {
      navigateTo(navTextOfDestination);
   }
   else
   {
      preLoginDestination = navTextOfDestination;
      switchToLoginUI('#PreloginUI');
   }
}

//=================================================================================================
function doLogin()
{
   if($('#account').val().length <= 0)
   {
      locAlert("Please enter an email address to connect.");
      return;
   }
   
   if(!isValidEmailAddress($('#account').val()))
   {
      locAlert("The email address you have entered doesn't appear to be valid.");
      return;
   }
   
   cef.uiapp.loginButton($('#account').val(), $('#password').val());
}

//=================================================================================================
function loginFailed(error)
{
   var cJSLoginOk = 0;
   var cJSLoginBadCredentials = 1;
   var cJSLoginFailed = 2;
   var cJSServerDown = 99;

   switch (error)
   {
   case cJSServerDown:
      serverDown();
      break;
   case cJSLoginBadCredentials:
      locAlert("Login Failure");
      break;
   case cJSLoginFailed:
   default:
      locAlert("Login Failure, please retry.");
      break;
   }
}

//=================================================================================================
function serverDown()
{
   locAlert("Unable to connect to the Hero Academy servers.  Please check your internet connection or try again in a few minutes.");
}

//=================================================================================================
function loginSuccess()
{
   if(preLoginDestination == "")
   {
      navigateTo("Home");  //Must be called dynamically to reset breadcrumbs
   }
   else
   {
      navigateTo(preLoginDestination);
   }
}

//=================================================================================================
function doLogout()
{
   if(isLoggedIn())
   {
      password.value = "";
      password_create.value = "";
      repassword_create.value = "";
      password_setpw.value = "";
      repassword_setpw.value = "";

      purgeGamesList();
      cef.uiapp.logoutButton();
   }
}

//=================================================================================================
function logoutFailed()
{
   preLoginDestination = "";
   locAlert('An error occurred attempting to log you out.');
   navigateTo("Home");
}

//=================================================================================================
function logoutSuccess()
{
   preLoginDestination = "";
   clearTimeout(cqrTimeout);
   navigateTo("Home");
}

//=================================================================================================
function isLoggedIn()
{
   return cef.uiapp.isLoggedIn();
}

//==================================   Forms   ====================================================
//=================================================================================================
function setUsername(username)
{
   $('#account').val(username);
}

//=================================================================================================
function setPassword(pwd)
{
   $('#password').val(pwd);
}

//=================================================================================================
function isValidEmailAddress(email)
{
   var atpos=email.indexOf("@");
   var dotpos=email.lastIndexOf(".");
   if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
   {
      return false;
   }
   return true;
}

//=================================================================================================
function createAccount()
{
   if($('#email_create').val().length <= 0)
   {
      locAlert("Please enter an email address to connect.");
      return;
   }

   if(!isValidEmailAddress($('#email_create').val()))
   {
      locAlert("The email address you have entered doesn't appear to be valid.");
      return;
   }
   
   if( ($('#account_create').val().length < 4) || ($('#account_create').val().length > 16) )
   {
      locAlert("The Nickname you have entered doesn't appear to be valid.  Alpha-numeric, hyphen and underscore.  Between 4 and 16 characters.");
      return;
   }

   if($('#password_create').val().length <= 5)
   {
      locAlert("The password you entered is invalid.  Password must be greater than 6 characters long.");
      return;
   }

   if($('#password_create').val() != $('#repassword_create').val())
   {
      locAlert("The two passwords do not match.  Please correct and try again.");
      return;
   }

   var cJSCreateAccountWithNickOk = 0;
   var cJSCreateAccountWithNickFailed = 1;
   var cJSCreateAccountWithNickInvalidEmail = 2;
   var cJSCreateAccountWithNickInvalidPassword = 3;
   var cJSCreateAccountWithNickInvalidNickname = 4;
   var cJSCreateAccountWithNickDuplicateNickname = 5;
   var cJSCreateAccountWithNickDuplicateEmail = 6;
   var cJSServerDown = 99;

   var result = 99;
   result = cef.uiapp.createAccount($('#email_create').val(), $('#account_create').val(), $('#password_create').val());

   switch(result)
   {
   case cJSCreateAccountWithNickOk:
      locAlert("Account Created.");
      return;
   case cJSCreateAccountWithNickFailed:
      locAlert("General Error.  Please Try Your Request Again");
      break;
   case cJSCreateAccountWithNickInvalidEmail:
      locAlert("The email address you have entered doesn't appear to be valid.");
      break;
   case cJSCreateAccountWithNickInvalidPassword:
      locAlert("The password you entered is invalid.  Password must be greater than 6 characters long.");
      break;
   case cJSCreateAccountWithNickInvalidNickname:
      locAlert("The Nickname you have entered doesn't appear to be valid.  Alpha-numeric, hyphen and underscore.  Between 4 and 16 characters.");
      break;
   case cJSCreateAccountWithNickDuplicateNickname:
      locAlert("The Nickname you have entered is already in use.");
      break;
   case cJSCreateAccountWithNickDuplicateEmail:
      locAlert("The Email you have entered is already in use. Try logging in?");
      break;
   case cJSServerDown:
      serverDown();
      break;
   default:
      locAlert("Failed to create account.  Try again later.");
      break;
   }
}

//=================================================================================================
function resetPassword()
{
   if(!isValidEmailAddress($('#email').val()))
   {
      locAlert("The email address you have entered doesn't appear to be valid.");
      return;
   }
      
   cef.uiapp.resetPassword($('#email').val());
   locAlert("Reset Password Request Submitted.  Please check your email.");
   switchToLoginUI('#PreloginUI');
}

//=================================================================================================
function setPasswordRequest()
{
   if ($('#password_setpw').val().length <= 5)
   {
      locAlert("The password you entered is invalid.  Password must be greater than 6 characters long.");
      return;
   }

   if ($('#password_setpw').val() != $('#repassword_setpw').val())
   {
      locAlert("The two passwords do not match.  Please correct and try again.");
      return;
   }

   cef.uiapp.setPassword($('#password_setpw').val());
   hideAllLoginUI();
   showHomeScreen();
}

//=================================================================================================
function cancelSetPassword()
{
   hideAllLoginUI();
   //$('#HomeScreen').show();
   showHomeScreen();
}

//=================================================================================================
function upsellDLC(dlcstring, onPurchase)
{
   //Attempt to purchase DLC. Process errors and execute appropriate javascript response.

   currentPurchasePageRefresh = "";
   var cJSSteamPurchaseFailed = 0;
   var cJSSteamPurchaseROServerDown = 1;
   var cJSSteamPurchaseROServerError = 2;
   var cJSSteamPurchaseAlreadyOwnedOnRO = 3;
   var cJSSteamPurchaseGrantedItemsToRO = 4;
   var cJSSteamPurchasePopupStorepage = 5;

   var result = 99;
   result = cef.uiapp.purchaseDLC(dlcstring);

   switch(result)
   {
   case cJSSteamPurchaseAlreadyOwnedOnRO:
   case cJSSteamPurchaseGrantedItemsToRO:
      // Refresh the offending purchase page
      eval(onPurchase);
      break;
   case cJSSteamPurchasePopupStorepage:
      // Steam storepage has been popped up. Save the function to refresh the page in case the user buys the item and we get a Steam DlcInstalled_t callback.
      currentPurchasePageRefresh = onPurchase;
      break;
   case cJSSteamPurchaseROServerDown:
      serverDown();
      break;
   case cJSSteamPurchaseROServerError:
      locAlert("HA Server Error: Unable to grant " + dlcstring + " to RO account.");
      break;
   case cJSSteamPurchaseFailed:
   default:
      locAlert("Assert: DLC error for " + dlcstring);
      break;
   }
}

//=================================================================================================
$(document).ready(function ()
{
   $("#account").focus();

   // [5/30/12 sveligati] This disables form submission/triggering a reload.
   // Now you can have multiple buttons in a form and act only on one of them.
   $('#loginform').ajaxForm();
   $('#accountcreateform').ajaxForm();
   $('#passwordresetform').ajaxForm();
   $('#setpasswordform').ajaxForm();
});

//=================================================================================================
$(document).keyup(function(e)
{
   // [6/05/12 sveligati] This allows you to use the escape key to navigate through our login forms.
   // Might have to hook this up to the nav menu breadcrumbs later...
   var KEYCODE_ESC = 27;
   if (e.keyCode == KEYCODE_ESC)
   {
      clickCancelButton();
   }
});


