﻿//Unify various account javascript actions

var accountUtils = new accountObj();

/////////////////////////////////////////////////////////////////////////////
//Account data container & routines
function accountObj() {

    /////////////////////////////////////////////////////////////////////////
    //Member variables
    this.UserId = -1;
    this.ExternalUserId = '';
    this.ExternalUserSource = '';
    this.isNewlyLinkedUser = false;

    this.loginHandlers = new Array();
    this.logoutHandlers = new Array();
    this.touAgree = false;

    /////////////////////////////////////////////////////////////////////////
    // Constants
    this.profileUrl = '/Account/profile?cb=';
    this.signInUrl = '/Account/SignIn?cb=';
    this.votosSignInUrl = '/Account/VotosSignIn?cb=';

    /////////////////////////////////////////////////////////////////////////
    // Utility Methods
    
    //Register an onLogin handler
    this.registerLoginHandler = function (handler) {
        this.loginHandlers.push(handler);
    };

    //Run login handlers
    this.runLoginHandlers = function () {
        for (var i = 0; i < this.loginHandlers.length; i++) {
            this.loginHandlers[i](this);
        }
    };

    //Register an onLogout handler
    this.registerLogoutHandler = function (handler) {
        this.logoutHandlers.push(handler);
    };

    //Run logout handlers
    this.runLogoutHandlers = function () {
        for (var i = 0; i < this.logoutHandlers.length; i++) {
            this.logoutHandlers[i](this);
        }
    };

    /////////////////////////////////////////////////////////////////////////
    ///Get current user
    this.getCurrentUser = function (userCallback) {
        //alert('foo');
        $.getJSON(
                '/user/json/currentUser',
                {},
                function (data) {
                    //if user found, set logged-in status
                    if (data != null) {
                        userCallback(data);
                    }
                }
        );
    }


    /////////////////////////////////////////////////////////////////////////
    // Account Status / Edit
    this.externalUserConnected = function (externalSource, externalIdentifier, connectedCallback) {
        //Attempt to get a linked user
        $.getJSON(
                '/Account/GetLinkedAccount',
                { externalSource: externalSource, externalIdentifier: externalIdentifier },
                function (data) {
                    //if user found, set logged-in status
                    if (data != null
                        && data.UserId > 0) {
                        accountUtils.setLoggedInUser(
                            data,
                            externalSource,
                            externalIdentifier,
                            function () {
                                accountUtils.runLoginHandlers();

                                if (connectedCallback != null) {
                                    connectedCallback(data);
                                }
                            });
                    } else {
                        //otherwise, promote the user
                        accountUtils.promoteUser(externalSource, externalIdentifier, connectedCallback);
                    }
                });
    }

    //////////////////////////////////////////////////////////////////////////////////
    // Link existing user to another social account
    this.linkExistingAccount = function (externalSource, externalIdentifier, callback) {
        $.post(
            '/Account/LinkAccount',
            { userId: this.UserId, externalSource: externalSource, externalIdentifier: externalIdentifier },
            function () {
                //Run handlers
                accountUtils.runLoginHandlers();
                if (callback != null) {
                    callback();
                }
            }
        );
    }

    /////////////////////////////////////////////////////////////////////////
    // Promote anonymous user to be not-anonymous
    this.promoteUser = function (externalSource, externalIdentifier, callback) {
        //Promote user
        $.post(
            '/Account/PromoteCurrentUser',
            {},
            function (data) {
                if (data.UserId != null
                    && data.UserId > 0) {

                    //Link account
                    $.post(
                        '/Account/LinkAccount',
                        { userId: data.UserId, externalSource: externalSource, externalIdentifier: externalIdentifier },
                        function () {
                            //Run handlers
                            accountUtils.isNewlyLinkedUser = true;
                            accountUtils.setLoggedInUser(data, externalSource, externalIdentifier, function () { accountUtils.runLoginHandlers(); });

                            //Callback
                            if (callback != null) {
                                data.isNew = true;
                                callback(data);
                            }
                        });
                }
            }
        );
    }

    this.setProfileProperty = function (userId, propertyName, propertyValue, callback) {
        $.post(
            '/Account/SetProfileProperty',
            { userId: userId, propertyName: propertyName, propertyValue: propertyValue },
            function () { if (callback != null) callback() }
        );

    }

    /////////////////////////////////////////////////////////////////////////
    //Set logged-in user on server-side
    this.setLoggedInUser = function (data, externalSource, externalIdentifier, callback) {
        accountUtils.UserId = data.UserId;
        accountUtils.ExternalUserSource = externalSource;
        accountUtils.ExternalUserId = externalIdentifier;

        //Set user as logged-in
        $.post(
            '/Account/SetLoggedInUser',
            { userId: data.UserId },
            function () {
                if (callback != null)
                    callback();
            });
    }

    /////////////////////////////////////////////////////////////////////////
    //Sign user out of all user sessions
    this.signOut = function () {
        accountUtils.UserId = -1;
        accountUtils.runLogoutHandlers();
        setTimeout('document.location = "/"', 2000);
    }

    /////////////////////////////////////////////////////////////////////////
    // Edit/Create Profile
    this.showEditProfile = function (title, isNew, callback) {
        var realCallback = function () { document.location.reload(); };

        if (callback != null) {
            realCallback = callback;
        }

        var url = accountUtils.profileUrl;

        if (isNew) {
            url = url + '&isNew=true';
        }

        $.modal('<iframe style="overflow:hidden;border:0;" width="750" height="450" scrolling="no" id="editProfileDialog" src="' + url + '" />', {
            modal: true,
            minHeight: 475,
            minWidth: 760,
            autoResize: true,
            overlayClose: false,
            overlayId: 'lightBoxBackground',
            containerId: 'modalDialogContainer',
            closeHTML: '<div class="modalDialogClose"><a class="simplemodal-close" href="#"><span>Close&nbsp;&nbsp;X</span></a></div>',
            close: realCallback
        });
    }

    /////////////////////////////////////////////////////////////////////////
    // Sign in
    this.showSignIn = function (title, callback) {
        var realCallback = function () { document.location.reload(); };

        if (callback != null) {
            realCallback = callback;
        }

        $.modal('<iframe style="overflow:hidden;border:0;" width="595" height="355" scrolling="no" id="signInDialog" src="' + accountUtils.signInUrl + '" >', {
            modal: true,
            minHeight: 400,
            minWidth: 600,
            autoResize: true,
            overlayClose: false,
            overlayId: 'lightBoxBackground',
            containerId: 'modalDialogContainer',
            closeHTML: '<div class="modalDialogClose"><a class="simplemodal-close" href="#"><span>Close&nbsp;&nbsp;X</span></a></div>',
            onClose: realCallback
        });
    }

    ///////////////////////////////////////////////////
    // Votos user sign-in success
    this.onSignInSuccess = function(ajaxContext) {
        if (ajaxContext == null) {
            return;
        }

        var resultObj = ajaxContext.get_object();

        if (resultObj == null) {
            return;
        }

        if (!resultObj.Success) {
            $('#errorMessage').html(resultObj.ErrorMessage);
            return;
        }

        //Otherwise, success!
        accountUtils.isNewlyLinkedUser = resultObj.IsNewAccount;
        accountUtils.UserId = resultObj.User.UserId;
        accountUtils.runLoginHandlers();

        window.parent.jQuery.modal.close();
    }

    //////////////////////////////////////////////////////////////////////////
    // If we have a logged in user we can update the sign-in widget
    this.updateSignInWidget = function (jsonUser) {
        $('#signInWidgetPlace').empty();

        $.ajax({
            url: '/Account/LoginStatusWidget',
            success: function (data) {
                $('#signInWidgetPlace').append(data);
            }
        });
    }

    this.openEmailDialog = function () {
        $('#newEmailDialog').modal({
            modal: true,
            minHeight: 400,
            minWidth: 635,
            autoResize: true,
            overlayClose: false,
            overlayId: 'lightBoxBackground',
            containerId: 'modalDialogContainer',
            closeHTML: '<div class="modalDialogClose"><a class="simplemodal-close" href="#"><span>Close&nbsp;&nbsp;X</span></a></div>',
            onClose: function () { $.modal.close(); }
        });
    }

    this.setNewEmail = function (newEmail) {
        if (newEmail) {
            $.ajax({
                url: 'Account/SendVerificationEmail',
                data: { userId: accountUtils.UserId, address: newEmail },
                success: function (data) {
                    if (data.success) {
                        accountUtils.setProfileProperty(accountUtils.UserId, 'Email', newEmail, null);
                        $.modal.close();
                        var item = { srcElement: { data: "/account/managelinkedaccountspartial"} };
                        loadUserInfoDashboard(item);
                    }
                    else {
                        //do some error reporting here
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    //more error reporting here
                },
                dataType: 'json'
            });
        }
    }

    this.openTerms = function () {
        $('#TOU').modal({
            modal: true,
            minHeight: 395,
            minWidth: 595,
            autoResize: true,
            overlayClose: false,
            onClose: function () {
                $.modal.close();
                $('[name="AgreeToTerms"]').attr('checked', true);
                accountUtils.touAgree = true;
            }
        });
    }

    this.forgotPassword = function () {
        var email = $('#EmailAddress').val();

        $.ajax({
            url: 'ForgotPassword',
            data: { address: email },
            dataType: 'json',
            success: function (data) {
                if (data.success)
                    $('#statusMessage').html(data.message);
                else
                    $('#errorMessage').html(data.message);
            }
        });
    }
}
