﻿// Authentication.js
var LOGIN_MODAL_POPUP_ID = "TitleBanner1_Login_ModalPopupExtender";
var g_errors, g_errorcount;
var LOGIN_SEPARATOR = 'LOGIN_&';
var AUTHENTICATE_ACTION = 'AUTHENTICATE';
LOGIN_ORIGINAL_MESSAGE_NO_REGISTRATION = "Enter your username and password to sign.";
LOGIN_ORIGINAL_MESSAGE =    "<P>Enter your username and password to sign or</P> ";

function pageLoad()
{
  Signin.init();
} 

function onRaiseError(error) {
  alert(getFormattedError(error));
}

function getFormattedError(error) {
  var errorFormat = 'An unhandled exception occurred\n\nType: {0}\nMessage: {1}\nStack Trace: {2}';
    
  return String.format(errorFormat, error.get_exceptionType(), error.get_message(), error.get_stackTrace());
}

// Signin Class

var si_window, si_info, si_userName, si_password, si_rememberMe, si_submit, si_cancel;

function Signin(){}

Signin.show = function() {

    //Enable buttons.
    LOGIN_enableCancelButton();
    LOGIN_enableSubmitButton(); 

    Signin.init();

    var modalPopupBehavior = $find(LOGIN_MODAL_POPUP_ID);

    modalPopupBehavior.show();
    si_userName.focus();

  
 // Events.add('SignInCompleted', Signin._SignInCompleted);
}

Signin.cancel = function() {
  Signin.hide();
}

Signin.hide = function() {
  var modalPopupBehavior = $find(LOGIN_MODAL_POPUP_ID);
  modalPopupBehavior.hide();
  
    // Clear the user password.
  si_password.value = "";
    
  // Clear the user name.
  si_userName.value = "";
        
  // user feedback.  
  si_info.style.color = "black";
  if(LoginDialog_AllowRegistrationLink)
    si_info.innerHTML = LOGIN_ORIGINAL_MESSAGE + "<a href='" + LoginDialog_RegistrationUrl + "'> register a new account.</a>";
  else
    si_info.innerHTML = LOGIN_ORIGINAL_MESSAGE_NO_REGISTRATION;     
        
}



// This function calls the login method of the
// authentication service to verify 
// the credentials entered by the user.
// If the credentials are authenticated, the
// authentication service issues a forms 
// authentication cookie. 
Signin.execute = function() {
  si_info.innerHTML = "Validating input...";
    
  if (Signin.isValid()) {
    si_info.innerHTML = "Signing In...";
        
    var callbackString =    AUTHENTICATE_ACTION + LOGIN_SEPARATOR + 
                            si_userName.value + LOGIN_SEPARATOR +
                            si_password.value + LOGIN_SEPARATOR +
                            si_rememberMe.checked;
    // Invoke Callback.
    LOGIN_callServer(callbackString);
    
 
  } 
  else 
  {
    si_info.innerHTML = g_errors;
  } 
  
}

Signin.isValid = function() {
  g_errorCount = 0;
  g_errors = '<ul>';   
  
  if (si_userName.value == '') {
    g_errors += '<li>Username is required.</li>';
    g_errorCount++;
  }
  if (si_password.value == '') {
    g_errors += '<li>Password is required.</li>';
    g_errorCount++;
  }
  
  if (g_errorCount > 0)
    g_errors = String.format('<span class="Login_error">{0} error{1} found.{2}</ul></span>', g_errorCount, (g_errorCount > 0 ? 's' : ''), g_errors);
  
  return g_errorCount == 0;
}


// This function sets and gets the default
// login completed callback function.
Signin.setDefaultLoginCompletedCallBack = function () {
  // Set the default callback function.
  Sys.Services.AuthenticationService.set_defaultLoginCompletedCallback(Signin.onLoginCompleted);
 
  // Get the default callback function.
  var callBack =     
      Sys.Services.AuthenticationService.get_defaultLoginCompletedCallback();
}

// This function sets and gets the default
// logout completed callback function.
Signin.setDefaultLogoutCompletedCallBack = function() {
  // Set the default callback function.
  Sys.Services.AuthenticationService.set_defaultLogoutCompletedCallback(Signin.onLogoutCompleted);
 
  // Get the default callback function.
  var callBack =     
      Sys.Services.AuthenticationService.get_defaultLogoutCompletedCallback();
}

// This function sets and gets the default
// failed callback function.
Signin.setDefaultFailedCallBack = function() {
  // Set the default callback function.
  Sys.Services.AuthenticationService.set_defaultFailedCallback(onRaiseError);
 
  // Get the default callback function.
  var callBack =     
      Sys.Services.AuthenticationService.get_defaultFailedCallback();
}


// The callback function called 
// if the authentication completed successfully.
Signin.onLoginCompleted = function(validCredentials, 
  userContext, methodName) {
    
  // Clear the user password.
  si_password.value = "";
    
  // On success there will be a forms 
  // authentication cookie in the browser.
  if (validCredentials == true) {
      // Clear the user name.
      si_userName.value = "";
      si_rememberMe.checked = false;
      
      // user feedback.  
      si_info.innerHTML = "You have signed in successfully.";
      
      // setting timer to close popupMenu.
      // !!! Variable 'LoginDialog_Delay' is Added dynamically in component's Render method.
      window.setTimeout("Signin.hide();", LoginDialog_Delay);   
      
              
  } else {
    si_info.innerHTML = '<span class="Login_error">Invalid sign in.  Please verify you have entered the correct username and password.</span>';
  }
}

// This is the callback function called 
// if the user logged out successfully.
Signin.onLogoutCompleted = function(result) { 

} 

function stopEvent(e) {
	if(!e) var e = window.event;
	
	//e.cancelBubble is supported by IE - this will kill the bubbling process.
	e.cancelBubble = true;
	e.returnValue = false;

	//e.stopPropagation works only in Firefox.
	if (e.stopPropagation) {
		e.stopPropagation();
		e.preventDefault();
	}
	return false;
}

Signin.onKeyDown = function(e) {
  
  if (e.keyCode == 27) 
  {
    Signin.cancel();
    stopEvent(e);
  } 
  else if (e.keyCode == 13) 
  {
      Signin.execute();
      stopEvent(e);
  }
    
}


Signin.LoginSucceeded = function()
{
  // Clear the user password.
  si_password.value = "";
    
  // Clear the user name.
  si_userName.value = "";
  si_rememberMe.checked = false;
  
  /* !!! old
  // user feedback.  
  si_info.innerHTML = "You have signed in successfully.";
  
  // setting timer to close popupMenu.
  // !!! Variable 'LoginDialog_Delay' is Added dynamically in component's Render method.
  window.setTimeout("Signin.hide();", LoginDialog_Delay);  
  */
  
  Signin.hide();
  window.setTimeout("CONFIRMATIONDIALOG_ShowDialog('LOGIN');",LoginDialog_Delay);
  
}

Signin.LoginFailed = function()
{
    si_info.innerHTML = '<span class="Login_error">Invalid sign in.  Please verify you have entered the correct username and password.</span>';
}
