/**
 * @namespace
 */
var brx = brx || {};
brx.signin = brx.signin || {};


/**
    * This method is used to set up the forget password functionality 
    * on the site.
    * Takes the passed element in the DOM and gets the required form 
    * nodes and places them within forgotPassArgs object.
    * brx.signin.setForgetPassword() is then called if the param resetPassword 
    * is set to true.
    * @param {Object} args
    * @param {Object} args.emailNode **REQUIRED** DOM element of either a 
    * form element or wrapper element of the email.
    * @param {Object} args.errorListNode **REQUIRED** DOM element used to show
    * password hint or error messaging if hint is not available.
    * @param {Object} args.forgotPasswordLink **REQUIRED** DOM element of the 
    * forget password link.
    * @params {element} forget link node set on dom:load
    * @methodOf brx.signin
*/
brx.signin.forgotPassword = function(args) {
    
    //console.log(args) 
    
    if ((args.emailNode.length > 1) || (!args.forgotPasswordLink)
        || (!args.errorListNode) ) {
        return null;
    }
    
    brx.signin.getRBKeys();
    
    var errorListNode = args.errorListNode;
    var emailNode = args.emailNode;
    var forgotPasswordLink = args.forgotPasswordLink;
    var forgotPasswordNote = args.forgotPasswordNote;
    var containerNode = args.containerNode || window.document;
    
    forgotPasswordLink.bind('click', function(evt) {
        evt.preventDefault();
        var email = brx.signin.getEmailAddress(emailNode);
        if (email.length < 1) {
            generic.showErrors([{
                text: brx.signin.forgotPasswordNoEmailProvided
            }], errorListNode);
            generic.showErrorState(emailNode);

            return null;
        }
        brx.signin.getPasswordHint({
            email: email,
            onSuccess: function(result) { 
                var responseData = result.getValue(); 
                if (responseData) {
                    generic.template.get({
						path: '/templates/password-hint.tmpl',
                        object: {
                            hint: responseData
                        },
                        callback: function(html) {
                            errorListNode.html(html);
                            forgotPasswordNote.addClass("hidden");
                            if (args.resetPassword) {
                                brx.signin.initResetPassword(emailNode, containerNode);
                            }
                        }
                    });
                } else {
                    // user not found
                    errorListNode[0].innerHTML = '';
                    generic.showErrors([{
                        text: brx.signin.forgotPasswordEmailNotFound
                    }], errorListNode);
                    generic.showErrorState(emailNode);
                };
            },
            onFailure: function(jsonRpcResponse) {
                var errorObjectsArray = jsonRpcResponse.getMessages();
                var errorKey = errorObjectsArray[0].key;
                if (errorKey === 'user.missing_password_hint') {
                    brx.signin.requestPassword(email, containerNode);
                } else if(errorKey == 'user.password_reset'){
                    generic.template.get({
						path: '/templates/password-already-reset.tmpl',
                        callback: function(html) {
                            errorListNode.html(html);
                            forgotPasswordNote.addClass("hidden");
                            if (args.resetPassword) {
                                brx.signin.initResetPassword(emailNode, containerNode);
                            }
                        }
                    });
                } else {
                    generic.showErrors(errorObjectsArray, errorListNode);
                    generic.showErrorState(brx.account.signinEmailInput);
                }
            }
        });
    });
};


/**
    * This method is used to retrieve a user's password hint.
    * @param {email} the user email that will be passed. **REQUIRED**
    * @param {onSucess}
    * @param {onFailure}
    * @methodOf brx.signin
*/
brx.signin.getPasswordHint = function(args) {
    if (!args.email) {
        return null;
    }
    var onSuccess = args.onSuccess || function() {};
    var onFailure = args.onFailure || function() {};
    generic.jsonrpc.fetch({
        method: 'user.passwdHint',
        params: [{
            "EMAIL_ADDRESS": args.email
        }],
        onSuccess : onSuccess,
        onFailure : onFailure
    });
};


/**
    * This method is used to reset a users password by submitting a hidden form.
    * @param {email} the user's email address **REQUIRED**
    * @param {actionURL} the page URL of the reset page **REQUIRED**
    * **NOTE**: The error check for if an account exists is handled by the password
    * hint function. The reset is hidden inside the password hint function
    * so no duplicate error checking is needed here.
*/
brx.signin.initResetPassword = function(emailNode, containerNode) {
    //have to initialise the link here because it isn't on the page until the pw hint method is invoked
    var email = brx.signin.getEmailAddress(emailNode);
    var resetPassLink = $(containerNode).find('.pwd-reset');
    var resetPassNote = $(containerNode).find('.forgot_pw_note');
    $(resetPassNote).addClass('hidden');
    if (resetPassLink) {
        resetPassLink.bind('click', function(evt) {  
            evt.preventDefault();
            brx.signin.requestPassword(email,containerNode);
        });
    }
};


/**
    * This method is used to direct the user to registration.tmpl or password_request.tmpl.
    * The passed values are injected into the genric form before it is submitted.
    * @param {email} the user email that will be passed. **REQUIRED**
    * @param {actionURL} action url used on user submit. **REQUIRED**
    * @param {returnURL} passed when an action is needed after the user 
    * has gone to the next template page. **NOT REQUIRED**
    * Example case for returnURL is if the user goes through checkout and registers, 
    * the returnURL is used to pass the viewbag action url to the registration page. Once 
    * registration form is filled out, user will be brought to viewbag.
    * @methodOf brx.signin
*/
brx.signin.submitHiddenSigninForm = function(args) {
    if (!args.actionURL || !brx.signin.hiddenForm) {
        return null;
    }
    
    var containerNode = args.containerNode;
    containerNode = $(containerNode);
    
    brx.signin.hiddenForm.attr('action', args.actionURL);
    var hiddenEmailNode = containerNode.find('.sigin-form-hidden-email');
    hiddenEmailNode.val(args.email);
    if (args.returnURL) {
        var hiddenReturnNode = containerNode.find('.sigin-form-hidden-return');
        hiddenReturnNode.val(args.returnURL);
    }
    brx.signin.hiddenForm.submit();
};


/**
    * This method is used to call brx.signin.submitHiddenSigninForm by 
    * passing the user's email used in the reset form submit.
    * @param {String} the user email that will be passed. **REQUIRED**
    * @methodOf brx.signin    
*/
brx.signin.requestPassword = function(emailAddr,containerNode) {
    brx.signin.hiddenForm = containerNode.find('.hidden-form');
    
    if (brx.signin.hiddenForm.length) {
        brx.signin.submitHiddenSigninForm({
            email: emailAddr,
            actionURL: '/account/password_request.tmpl',
            containerNode: containerNode
        });
    }
}

/**
    * This method is used to pull the user's email from either a form
    * input or container html tag wrapper (i.e. div, span, etc)
    * @param {String} emailNode the user email that will be passed. **REQUIRED**
    * @methodOf brx.signin    
*/
brx.signin.getEmailAddress = function(emailNode) {
    var email = emailNode[0].value || emailNode[0].innerHTML;
    return email;
}


/**
    * One-time call to collect specific RB Keys used for forget password.
    * @methodOf brx.signin 
*/
brx.signin.getRBKeys = function() {
    brx.signin.rb = generic.rb("error_messages");
	brx.signin.forgotPasswordEmailNotFound = brx.signin.rb.get("incorrect_pwremind");
	brx.signin.forgotPasswordNoEmailProvided = brx.signin.rb.get("session_pw_hint");
    brx.signin.forgotPasswordMigratedUser = brx.signin.rb.get("migrated.mobile_account.signin");
}


