var uscc = uscc || {};
uscc.authentication = uscc.authentication || {};

uscc.authentication.ActivateAccount = (function(containerSelector, options){

    var _options = $.extend({}, {}, options),
        _containerSelector = containerSelector,
        _cookie = new newbay.util.Cookie(),
        _dialog = newbay.widget.OKDialog(),
        _hasAlreadySubmittedYoungAge = false,
        _formElements = {
            PINONE: {
                    id: "old-pwd",
                    validationType:"mandatory_text",
                    localizedError:"Please enter an old password"
                 },
            PINTWO: {
                    id: "new-pwd",
                    validationType:"mandatory_text",
                    localizedError:"Please enter in a new password"
                },
            CONPWD: {
                    id: "confirm-pwd",
                    validationType:"mandatory_text",
                    localizedError:"Please confirm your new password"
                },
            TANDC: {
                    id: "acctandcs",
                    validationType:"mandatory_check",
                    localizedError:"You must accept Terms & Conditions to continue"
                }
        },
        _super = new newbay.pva.widget.Form ({containerSelector: containerSelector, formElements: _formElements});

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

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

        if(_super.validate()){
            //need to send account type and msisdn
            var profileData = {
                    msisdn              : $containerSelector.find("#msisdn").val(),
                    accountType         : $containerSelector.find("#acctype").val(),
                    oldPassword         : $containerSelector.find("#old-pwd").val(),
                    newPassword         : $containerSelector.find("#new-pwd").val(),
                    confirmNewPassword  : $containerSelector.find("#confirm-pwd").val()
            }

            //validate DOB
            if ($("#dob_year").val() == "--" || $("#dob_month").val() == "--" || $("#dob_date").val() == "--") {
                newbay.pva.widget.OKDialog.setText("Please enter a valid Date of birth.")
                          .open()
                          .setDialogOption("title", "Invalid User Details");  //TODO: convert to l10n string
                return;
            }

            var userDob = new Date(parseInt($("#dob_year").val(),10), parseInt($("#dob_month").val(),10), parseInt($("#dob_date").val(),10)),
                oldEnough = false,
                now = new Date();

            if ((now.getFullYear() - userDob.getFullYear()) > 13) {
                oldEnough = true;
            } else if ((now.getFullYear() - userDob.getFullYear()) == 13 && ((userDob.getMonth() == now.getMonth() && userDob.getDate() <= now.getDate()) || userDob.getMonth() < now.getMonth())) {
                oldEnough = true;
            }


            if (!oldEnough) {
                if (!_hasAlreadySubmittedYoungAge) {
                    newbay.pva.widget.OKDialog.setText("The date of birth entered means you are too young to qualify for this service. Please verify the date entered is correct and try again.")
                          .open()
                          .setDialogOption("title", "Invalid User Details");
                    _hasAlreadySubmittedYoungAge = true;
                    return;
                } else {
                    newbay.pva.widget.OKDialog.setText("The date of birth entered means you are too young to qualify for this service. Your account will now be deleted.")
                          .open()
                          .setDialogOption("title", "Invalid User Details");
                    newbay.pva.widget.OKDialog.subscribe("close", function(){
                        _deleteAccount(function() {
                            location.replace("../../../signout");
                        });
                    });
                    return false;
                }
            }

            if (profileData.newPassword !== profileData.confirmNewPassword) {   //if new & confirm passwords do not match
                newbay.pva.widget.OKDialog.setText("New and Confirm passwords do not match, please correct and try again.")
                          .open()
                          .setDialogOption("title", "Password mismatch");

                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          :   "/atpbridge?operationName=activate",
               data         :   profileData,
               contentType  :   "application/x-www-form-urlencoded",
               beforeSend   :   function(xhr){
                    xhr.setRequestHeader("X-Service-Identifier", "USC");
               },
               success      :   function(response){
                    _handleSuccess(response);
               },
               error      :   function(response){
                   _handleFailure(response);
               }
            });
        }
    };

    var _deleteAccount = function(callbackFunc) {
        var deleteData = {
            "lcid":newbay.authentication.systemSettings.lcid,
            "reason":10
        };

        $.ajax({
               type         :   "POST",
               url          :   "/atpbridge?operationName=userDelete",
               data         :   deleteData,
               contentType  :   "application/x-www-form-urlencoded",
               beforeSend   :   function(xhr){
                    xhr.setRequestHeader("X-Service-Identifier", "USC");
               },
               complete:   callbackFunc
            });
    };

    var _handleSuccess = function(response){
        //check to see if the response contains errors
        if(response.errors){//response.errors[0].code === "2021"

            _super.setLoading(false);
            _dialog.setText("Incorrect password or new passwords entered do not match.");
            _dialog.open();
            _dialog.setDialogOption("title", "Invalid Password");

        }else{

            _cookie.createCookie('NWB', response.access_token);
            _cookie.createCookie('NWB_NS', response.lcid);
            _cookie.createCookie('NWB_LCID', response.lcid);

            _dialog.setText("Account Activated! Click OK to go to the Welcome page.");
            _dialog.open();
            _dialog.setDialogOption("title", "Account Activated");
            _dialog.subscribe("okclick", function(){
                location.href = "http://" + location.host + newbay.authentication.systemSettings.contextWebApp+"/"+ response.lcid +"/welcome";
            });
              
        }
    };

    var _handleFailure = function(response){
        _super.setLoading(false);
        if (response.status == 401) {
            _dialog.setText("Your old password is incorrect. Please correct your old password and try again.");
        } else {
            _dialog.setText("An error occurred while trying to complete your request. Please try again.");
        }
        _dialog.open();
        _dialog.setDialogOption("title", "Error");
    };

    var _createDOBValues = function() {
        var optionsHtml="",
            months=["January","February","March","April","May","June","July","August","September", "October","November","December"];
        optionsHtml = "<option value='--'>--</option>";
        for (var i=1; i <= 31; i++) {
            optionsHtml += "<option value='"+i+"'>" + i + "</option>";
        }
        $("#dob_date").html(optionsHtml);

        optionsHtml = "<option value='--'>--</option>";
        for (i=0; i <= 11; i++) {
            optionsHtml += "<option value='"+i+"'>" + months[i] + "</option>";
        }
        $("#dob_month").html(optionsHtml);

        optionsHtml = "<option value='--'>--</option>";
        var thisYear = new Date().getFullYear();
        for (i=(thisYear-120); i <= thisYear; i++) {
            optionsHtml += "<option value='"+i+"'>" + i + "</option>";
        }
        $("#dob_year").html(optionsHtml);
    };

    var _init = function(){
        $(_containerSelector).delegate("#uscc-active-btn", "click", function(event){
            event.preventDefault();
            _activateUser();
        });

        $(_containerSelector).delegate("#uscc-cancel", "click", function(event){
            event.preventDefault();
            location.href = newbay.authentication.systemSettings.contextWebApp+"/intro";
        });

        _createDOBValues();
    };

    _init();

    return _self;
});

uscc.authentication.ActivateLegacyAccount = (function(containerSelector, options){

    var _options = $.extend({}, {}, options),
        _containerSelector = containerSelector,
        _cookie = new newbay.util.Cookie(),
        _dialog = newbay.widget.OKDialog(),
        _hasAlreadySubmittedYoungAge = false,
        _formElements = {
            PSWRD: {
                    id: "psword",
                    validationType:"mandatory_text",
                    localizedError:"Please enter your password"
                 },
            TANDC: {
                    id: "acctandcs",
                    validationType:"mandatory_check",
                    localizedError:"You must accept Terms & Conditions to continue"
                }
        },
        _super = new newbay.pva.widget.Form ({containerSelector: containerSelector, formElements: _formElements});

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

    var _activateLegacyUser = function()
    {

        if(_super.validate()){
            //need to send msisdn and password
            var data = {
                msisdn: $("#mdn").val(),
                accountPassword: $("#psword").val()
            };
            _super.setLoading(true);

            $.ajax({
               type         :   "POST",
               url          :   "/atpbridge?operationName=activateMigratee",
               data         :   data,
               contentType  :   "application/x-www-form-urlencoded",
               beforeSend   :   function(xhr){
                    xhr.setRequestHeader("X-Service-Identifier", "USC");
               },
               success      :   function(response){
                    _handleSuccess(response);
               },
               error      :   function(response){
                   _handleFailure(response);
               }
            });
        }
    };

    var _handleSuccess = function(response){
        //check to see if the response contains errors
        _cookie.createCookie('NWB', response.access_token);
        _cookie.createCookie('NWB_NS', response.lcid);
        _cookie.createCookie('NWB_LCID', response.lcid);

        _dialog.setText("Account Activated! Click OK to go to the Welcome page.");
        _dialog.open();
        _dialog.setDialogOption("title", "Account Activated");
        _dialog.subscribe("okclick", function(){
            location.href = "http://" + location.host + newbay.authentication.systemSettings.contextWebApp+"/"+ response.lcid +"/welcome";
        });
    };

    var _handleFailure = function(response){
        var json = null;
        try {
            json = JSON.parse(response.responseText);
        } catch (e) {}
        if (json != null && json.errors && json.errors.length > 0 && json.errors[0].code == "2021") {
            _dialog.setText("The password entered is incorrect.");
        } else {
            _dialog.setText("An error occurred while trying to complete your request. Please try again.");
        }
        _super.setLoading(false);
        _dialog.open();
        _dialog.setDialogOption("title", "Error");
    };

    var _init = function(){
        $(_containerSelector).delegate("#uscc-active-btn", "click", function(event){
            event.preventDefault();
            _activateLegacyUser();
        });

        $(_containerSelector).delegate("#uscc-cancel", "click", function(event){
            event.preventDefault();
            location.href = newbay.authentication.systemSettings.contextWebApp+"/intro";
        });

        $("#uscc-act-form").submit(function(e) {
            e.preventDefault();
            _activateLegacyUser();
        });
    };

    _init();

    return _self;
});
