newbay.namespace("pva.uicomponent");

newbay.pva.uicomponent.ResetPassword = (function(containerSelector, options){

    var _options = $.extend({}, {}, options),
        _containerSelector = containerSelector,
        _cookie = new newbay.util.Cookie(),
        _errorMsgs = newbay.pva.locale,

        _formElements = {
            PWORD: {
                    id: "psword",
                    validationType:"mandatory_text",
                    localizedError:"Please enter your current password."
                 },
            PWORDNEW: {
                    id: "npsword",
                    validationType:"mandatory_text",
                    localizedError:"Please enter in a new password."
                },
            PWORDOLD: {
                    id: "cpsword",
                    validationType:"mandatory_text",
                    localizedError:"Please confirm your password."
                }
        },
        _super = new newbay.pva.widget.Form ({containerSelector: containerSelector, formElements: _formElements});

    //extend the Form Widget
    var _self = $.extend({}, _super, {});

    var _changePassword = function()
    {
        var $containerSelector = $(_containerSelector);

                    //need to send account type and msisdn
        var profileData = {
                    accountPassword     : $containerSelector.find("#psword").val(),
                    newPassword         : $containerSelector.find("#npsword").val(),
                    confirmNewPassword  : $containerSelector.find("#cpsword").val(),
                    lcid                : newbay.pva.systemSettings.lcid
        };

        if (!_super.validate()) return;


        if(profileData.newPassword !== profileData.confirmNewPassword){
            _passwordDonotMatch();
            return;
        } else if (/^.*(?=.{6,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/.test(profileData.newPassword) === false) {
            newbay.pva.widget.OKDialog.setText("Your new password is not strong enough. Password must be a minimum of 6 characters, must contain at least one lowercase letter, one uppercase letter, one number, and can not contain symbols. Please try again.").open().setDialogOption("title", "Password Reset");
            return;
        }

        _super.setLoading(true);

        $.ajax({
           type         :   "POST",
           url          :   "/webauth/profile ",
           data         :   profileData,
           contentType  :   "application/x-www-form-urlencoded",
           beforeSend   :   function(xhr){
                xhr.setRequestHeader("X-Service-Identifier", "USC");
           },
           complete   :   function(response){
               if(response.status === 401){
                    _oldPasswordWrong();
               }
           },
           success      :   function(response){
                _handleSuccess(response);
           },
           error      :   function(response){
               _handleFailure(response);
           }
        });
    };

    var _passwordDonotMatch = function(){
        _super.setLoading(false);
        newbay.pva.widget.OKDialog.setText("Your passwords do not match. Please try again.").open().setDialogOption("title", "Password Reset");
    };

    var _oldPasswordWrong = function() {
        _super.setLoading(false);
        newbay.pva.widget.OKDialog.setText("Your Old Password is incorrect. Please try again.").open().setDialogOption("title", "Password Reset");
    };

    var _handleSuccess = function(response){
        _super.setLoading(false);
         newbay.pva.widget.OKDialog.setText("Your password has now been changed.").open().setDialogOption("title", "Password Reset");
        $("#cpsword, #psword, #npsword").val("");
    };

    var _handleFailure = function(xhr) {
        _super.setLoading(false);
        var ro = xhr.responseObject,
        l=newbay.pva.locale,
        msg = "An error occurred while trying to complete your request. Please try again.";
        try {
            ro = JSON.parse(xhr.responseText);
            if ($.isArray(ro.errors) && ro.errors.length > 0 && l.hasOwnProperty(ro.errors[0].message)) {
                msg = l[ro.errors[0].message];
            }
        } catch(e) {}
        newbay.pva.widget.OKDialog.setText(msg).open().setDialogOption("title", "Error");
    };

    var _init = function(){
        $(_containerSelector).delegate("#save-pwdchg", "click", function(event){
            event.preventDefault();
            _changePassword ();
        });
        $(_containerSelector).delegate("#cpsword, #psword, #npsword", "keyup", function(event){
            if (event.keyCode==13)  {
                _changePassword ();
            }
        });

    };

    _init();

    return _self;
});
