﻿var mf = window.mf || {};

mf.login = (function() {
    // Private variables
    var tbUserName,
        tbPassword,
        cbRemember,
        good = 'green',
        bad = 'red',
        un = '';
    
    /**
     * function checkForUserInfo()
     * Will check to see if a mfUser cookie exists and if it does, will auto fill the contents of the login.
     */
    function checkForUserInfo() { 
        var cookie = getCookie('mfUser');
        if (cookie) { 
            var index = cookie.indexOf('userName');
            var str = cookie.substring(index, cookie.length);
            index = str.indexOf('=');
            var index2 = str.indexOf('&');
            var user = str.substring(index + 1, index2);
            str = str.substring(index2 + 1, str.length);
            index2 = str.indexOf('=');
            var password = str.substring(index2 + 1, str.length);
            
            if ((user.length > 0) && (password.length > 0)) { 
                tbUserName.val(user);
	            tbPassword.val(password);
	            cbRemember.attr('checked', true);
            }
        }
    }
    
    /**
     * function getCookie(c_name)
     * Will check to see if a cookie with c_name exists, and if it does will return the contents of it
     * @param c_name - String - the name of the cookie being searched for.
     */
    function getCookie(c_name) {
        if (document.cookie.length > 0) {
            c_start = document.cookie.indexOf(c_name + '=');
            if (c_start != -1) { 
                c_start = c_start + c_name.length + 1; 
                c_end = document.cookie.indexOf(';', c_start);
                if (c_end == -1) {
                    c_end = document.cookie.length;
                }
                return unescape(document.cookie.substring(c_start,c_end));
            } 
        }
        return '';
    }
    
    function attemptLogin() {
        if ((tbUserName.val().length > 0) && (tbPassword.val().length > 0)) {
            updateStatus('Attempting login...', good);
            var userInfo = [tbUserName.val(), tbPassword.val(), cbRemember.attr('checked')];
            Sys.Services.AuthenticationService.login(tbUserName.val(), tbPassword.val(), cbRemember.attr('checked'), null, null, loginSuccess, loginFail, userInfo);
            un = tbUserName.val();
            tbUserName.val('');
            tbPassword.val('');
            cbRemember.attr('checked', false);
        }
        else {
            if (tbUserName.val().length === 0) { $('#login-status').text('Username required.').css('color', 'red'); }
            else if (tbPassword.val().length === 0) { $('#login-status').text('Password required.').css('color', 'red'); }
        }
        return false;
    }
    
    /**
     * function loginSuccess(validCredentials, userContext, methodName)
     * Called when the login webservice completes, will attempt to set the Authentication Ticket by calling wsUser.setAuthTicket.
     * If the user did not enter correct un/pwd they will be notified.
     */
    function loginSuccess(validCredentials, userContext, methodName) {
        if (validCredentials) {
            updateStatus('Login Successfull! Loading your data...', good);
            var params = JSON.stringify({ password: userContext[1], remember: userContext[2] });
            mf.util.ajax('/WebServices/wsUser.asmx/setAuthTicket', params, setAuthTicketSuccess, setAuthTicketFailure);
        } else {
            updateStatus('Login Failed. Please try again.', bad);
            tbUserName.focus();
        }
        return false;
    }
    
    /**
     * function loginFail(error)
     * Called when the login webservice fails
     * @param error - Error Object - The object containing the error information from the webservice.
     */
    function loginFail(error) {
        alert(error.get_message());
        updateStatus(error.get_message(), bad);
        return false;
    }
    
    function setAuthTicketSuccess() {
        // after login, check if they are an individual, in a group or group manager
        mf.util.ajax('/WebServices/wsVolunteer.asmx/getVolunteerInfo', '{}', getVolunteerInfoSuccess, getVolunteerInfoFailure);
    }
    
    function setAuthTicketFailure(error) {
        updateStatus('Authentication Failed: ' + error.get_message(), bad);
    }
    
    function getVolunteerInfoSuccess(vInfo) {
        if ( un === 'volunteer_admin' ) {
            window.location = '/admin/';
        }
        else if (vInfo) {
            
            // if they are a group leader, redirect to group manager page
            if (vInfo.isLeader) {
                window.location = '/group-manager/';
            }
            else {
            
                // if they are in a group, redirect to group, individual page
                if (vInfo.groupId > 0) {
                    window.location = '/group-individual/';
                }
                
                // if they are not in a group, redirect to individual page
                else {
                    window.location = '/individual/';
                }
            }
        }
    }
    
    function getVolunteerInfoFailure(error) {
        if ( un === 'volunteer_admin' ) {
            window.location = '/admin/';
        }
    }
    
    function updateStatus(text, fColor) {
        $('#login-status').text(text).css('color', fColor);
    }   
    
    return {

        init: function() {
            // init variables
            tbUserName = $('#tbUserName');
            tbPassword = $('#tbPassword');
            cbRemember = $('#cbRemember');
            
            // add clic login button
            $('#btnLogin').click(attemptLogin);
                
            // if the user is already logged in, load data and redirect
            if (Sys.Services.AuthenticationService.get_isLoggedIn()) {
                mf.util.ajax('/WebServices/wsVolunteer.asmx/getVolunteerInfo', '{}', getVolunteerInfoSuccess, getVolunteerInfoFailure);
            }
            else {
                // check if user info exists on machine
                checkForUserInfo();
            }
                
            if (typeof(Sys) !== "undefined") { Sys.Application.notifyScriptLoaded(); }
        }
        
    };

})();

$(function(){mf.login.init();});