// Authentication.js

var txtUsername;
var txtPassword;

var textLoggedIn;
var textNotLoggedIn;

var buttonLogin;  
var buttonLogout; 

function pageLoad()
{

	Sys.Services.AuthenticationService.set_path('/Authentication_JSON_AppService.axd');
 	txtUsername = $get("txtLoginUserName");
 	txtPassword = $get("txtLoginPassword");
	
	textLoggedIn = $get("loggedin");
	textNotLoggedIn = $get("notloggedin");

	buttonLogin = $get("ButtonLogin");  
	buttonLogout = $get("ButtonLogout");

	$U.focus(txtUsername);
	
	window.onscroll=function() { positionModal(); }
}            

// This function sets and gets the default
// login completed callback function.
function SetDefaultLoginCompletedCallBack()
{
    // Set the default callback function.
    Sys.Services.AuthenticationService.set_defaultLoginCompletedCallback(OnLoginCompleted);
   
    // Get the default callback function.
    var callBack = Sys.Services.AuthenticationService.get_defaultLoginCompletedCallback();
}

// This function sets and gets the default
// logout completed callback function.
function SetDefaultLogoutCompletedCallBack()
{
    // Set the default callback function.
    Sys.Services.AuthenticationService.set_defaultLogoutCompletedCallback(OnLogoutCompleted);
   
    // Get the default callback function.
    var callBack = Sys.Services.AuthenticationService.get_defaultLogoutCompletedCallback();
}

// This function sets and gets the default
// failed callback function.
function SetDefaultFailedCallBack()
{
    // Set the default callback function.
    Sys.Services.AuthenticationService.set_defaultFailedCallback(OnFailed);
   
    // Get the default callback function.
    var callBack = Sys.Services.AuthenticationService.get_defaultFailedCallback();
}

function OnClickLogin() 
{   
    $U.noDisplayChidren('divLogin', 'span', 'validator');
    $U.noDisplay('loginMessage');
        
    var username = $get("txtLoginUserName").value.trim();
    if (username.length == 0)
    {
        showMessage('valLoginUserName', 'User name is required..', true);
        $U.focus(txtUsername);
        return;
    }

    var txtPassword = $get('txtLoginPassword');
    var password = txtPassword.value;

    if (password.length == 0)
    {
        showMessage('valLoginPassword', 'Password cannot be blank.', true);
        $U.focus(txtPassword);
        return;
    }

    var rememberMe = $get('chkLoginRememberMe').checked;

    // Set the default callback functions.
    SetDefaultLoginCompletedCallBack();
    SetDefaultLogoutCompletedCallBack();
    SetDefaultFailedCallBack();
   
    // Call the authetication service to authenticate
    // the credentials entered by the user.
    Sys.Services.AuthenticationService.login(username, password, rememberMe, null, null, null, null, "User Context");
}

// This function calls the logout method of the
// authentication service to clear the forms 
// authentication cookie.
function OnClickLogout() 
{  
   // Clear the forms authentication cookie. 
   Sys.Services.AuthenticationService.logout(null, null, null, null); 
} 

// This is the callback function called 
// if the authentication fails.      
function OnFailed(error, userContext, methodName)
{			
    // Display feedback message.
	/*DisplayInformation("error:message = " + error.get_message());
	DisplayInformation("error:timedOut = " + error.get_timedOut());
	DisplayInformation("error:statusCode = " + error.get_statusCode());*/
}

// The callback function called 
// if the authentication completed successfully.
function OnLoginCompleted(validCredentials, userContext, methodName)
{
	
    // Clear the user password.
    txtPassword.value = "";
    
    // On success there will be a forms 
    // authentication cookie in the browser.
    if (validCredentials == true) 
    {
        MembershipService.CreateCSCookie(txtUsername.value.trim(), createCSCookie_Callback);
    }
    else 
    {
        showMessage('loginMessage', 'Invalid login credentials.', true);
        $U.focus('txtLoginUserName');
    }
}

function createCSCookie_Callback(result, eventArgs)
{
    window.location.reload();
}

// This is the callback function called 
// if the user logged out successfully.
function OnLogoutCompleted(result) 
{
}

function showMessage(e, msg, err)
{
    var e = $U.fix(e);

    if (err)
    {
        e.style.color = '#ff0000';
    }
    else
    {
        e.style.color = '';
    }

    $U.setText(e, msg);
    $U.display(e);
}

function sendPassword()
{
    $U.noDisplayChidren('divLogin', 'span', 'validator');
    $U.noDisplay('passwordMessage');

    var txtEmail = $get('txtForgotEmail');
    var email = txtEmail.value.trim();

    if (email.length == 0)
    {
        showMessage('valForgotEmail', 'Email cannot be blank.', true);
        $U.focus(txtEmail);
        return;
    }

    if (!isValidEmail(email))
    {
        showMessage('valForgotEmail', 'Invalid email address.', true);
        $U.focus(txtEmail);
        return;
    }

    showMessage('passwordMessage', 'Sending password...', false);
    $get('btnPassword').disabled = true;
    MembershipService.ForgotPassword(email, sendPassword_Callback);
}

function sendPassword_Callback(result, eventArgs)
{
    showMessage('passwordMessage', result, false);
    $get('btnPassword').disabled = false;
}

function isValidEmail(email)
{
    var regExp = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    return regExp.test(email);
}

function showLogin()
{

    $get("txtLoginUserName").value='';
	$get("txtLoginPassword").value='';
	$U.setText('valLoginUserName', '');
	$U.setText('valLoginPassword', '');
	$U.setText('loginMessage', '');
	$U.setText('valForgotEmail', '');
	$U.setText('passwordMessage', '');

    var divModal = $get('divMembershipBox');
    var divDim = $get('divDimBackground');

    $U.display(divModal);
    $U.display(divDim);

    var modalBounds = Sys.UI.DomElement.getBounds(divModal);

    var viewPortWidth = $U.getViewPortWidth();
    var viewPortHeight = $U.getViewPortHeight();
    var contentHeight = $U.getContentHeight();

    var x = Math.round((viewPortWidth - modalBounds.width)/ 2);
    var y = Math.round((viewPortHeight - modalBounds.height)/ 2);

    divDim.style.width = viewPortWidth + 'px';
    divDim.style.height = Math.max(viewPortHeight, contentHeight) + 'px';

    $U.setLocation(divModal, x, y);
    $U.setLocation(divDim, 0, 0);
    
    positionModal();
}

function positionModal()
{
    var divModal=$get("divMembershipBox");
    if (divModal!=null)
    {
        if (divModal.style.display=="")
        {
            var newRect = $U.getWindowInformation();
            var modalXPos=newRect.ScrollY + (newRect.Height/2)-75;
            $get("divMembershipBox").style.top = modalXPos + "px";
        }
    }
}

function hideLogin()
{
    $U.noDisplay('divDimBackground');
    $U.noDisplay('divMembershipBox');
}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
