﻿var Sawbuck = window.Sawbuck || {};

//Singleton (eager-loading)
Sawbuck.UserManager = (function() {

    var _loggedIn = false;
    var _userID = null;
    var _alertsOn = false;
    var _alertsFrequency = 2;
    var _partnerID = 0;

    var _emailRegEx = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/

    var _listeners = {};

    var _successFade = 5000;

    function loadUserID() {
        if (cookie = Sawbuck.Utilities.readCookie("User")) {
            _userID = cookie.substring("UserID=".length, cookie.length);
        };
    }

    function onLogout() {
        for (var l in _listeners) {
            if (l == "onlogout" || l == "onLogout") {
                _listeners[l]();
            }
        }
    }

    function updateRSSLinks() {
        $j(".rssLink").each(function() {
            this.href = this.href.replace(/\/rss/, "/rss/" + _userID);
        });
    }

    function updateHeaderLinks() {
        $j(".registerLink").hide();
        $j(".signInLink").hide();
        $j(".logoutLink").show();
    }

    function onLogin() {
        updateHeaderLinks();
        updateRSSLinks()
        loadUserID();
        $j("#signInWindow").dialog('close');
        $j("#registrationWindow").dialog('close');
        _loggedIn = true;
        for (var l in _listeners["onLogin"]) {
            _listeners["onLogin"][l]({ userID: _userID });
        }
    }

    function onRegister(email) {
        // updateHeaderLinks();
        // updateRSSLinks()
        // loadUserID();
        // $j("#registrationWindow").dialog('close');
        // _loggedIn = true;
        /*
        for (var l in _listeners["onRegister"]) {
        _listeners["onRegister"][l]({ userID: _userID });
        }
        */
        displayConfirmationText(email);
    }

    function resendConfirmationEmail(email) {
        $j.ajax({
            type: "POST",
            url: "/service/WebService.asmx/ResendVerificationLetter",
            data: Sawbuck.Utilities.toJson({ Url: window.location.toString() }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            processData: false,
            success: function(response) {
                if (email)
                    alert("Your confirmation email has been re-sent to " + email + ".");
                else
                    alert("Your confirmation email has been re-sent.");
            }
            , error: function() {
                // There was a problem sending this invitation
            }
        });
    }

    function displayFormError(form, error) {
        var errorField = $j(form).find(".error_warning")[0];
        $j(errorField).text(error);
        $j(errorField).show();
    }

    function updateInfo(firstName, lastName, email) {
        var form = $j("#updateInfoForm").children("form");

        firstName = Sawbuck.Utilities.trim(firstName);
        lastName = Sawbuck.Utilities.trim(lastName);
        email = Sawbuck.Utilities.trim(email);

        if (!firstName || !lastName || !email) {
            displayFormError(form, "All fields are required");
            return false;
        }
        if (!_emailRegEx.test(email)) {
            displayFormError(form, 'Not a valid email address');
            return false;
        }

        $j.ajax({
            type: "POST",
            url: "/service/WebService.asmx/UpdateAccountInfo",
            data: Sawbuck.Utilities.toJson({ Email: email, FirstName: firstName, LastName: lastName }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            processData: false,
            success: function(response) {
                if (response.d == true) {
                    $j("#updateInfoForm").dialog('close');
                    $j("#plFname").text(firstName);
                    $j("#plEmail").text(email);
                    $j("#updateInfoSuccess").show();
                    setTimeout(function() { $j("#updateInfoSuccess").fadeOut('slow') }, _successFade);
                }
                else {
                    displayFormError(form, "The email address you entered is already in use.");
                }
            }
            , error: function() {
                // There was a problem sending this invitation
            }
        });

    }

    function register(form) {

        firstName = $j(form).find("input[name=first_name]").val();
        lastName = $j(form).find("input[name=last_name]").val();
        email = $j(form).find("input[name=email_address]").val();
        email2 = email; //$j(this).find("input[name=email]").val();
        pw = $j(form).find("input[name=password]").val();
        pw2 = $j(form).find("input[name=confirm_password]").val();
        agree = $j(form).find("input[name=terms_of_use]:checked").length == 1;

        email = Sawbuck.Utilities.trim(email);
        email2 = Sawbuck.Utilities.trim(email2);
        pw = Sawbuck.Utilities.trim(pw);
        pw2 = Sawbuck.Utilities.trim(pw2);

        if (Sawbuck.Utilities.trim(firstName).length < 2 || Sawbuck.Utilities.trim(lastName).length < 2) {
            displayFormError(form, 'Must enter your first and last name');
        }
        else if (!_emailRegEx.test(email)) {
            displayFormError(form, 'Not a valid email address');
        }
        else if (pw.length < 5) {
            displayFormError(form, 'Password must be at least 5 characters long');
        }
        else if (pw != pw2) {
            displayFormError(form, "Passwords do not match");
        }
        else if (!agree) {
            displayFormError(form, 'Must click "I Agree to the Terms Of Use"');
        }
        else {
            data = { Email: email, Password: pw, Password1: pw2, FirstName: firstName, LastName: lastName, Url: window.location.toString() };
            $j.ajax({
                type: "POST",
                url: "/service/WebService.asmx/Register",
                data: Sawbuck.Utilities.toJson(data),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processData: false,
                dataFilter: function(data, type) {
                    //Turns ASP.NET dates into Javascript readable dates
                    return data.replace(/"\\\/(Date\([0-9-]+\))\\\/"/gi, 'new $1');
                },
                success: function(response) {
                    var msg = response.d.Msg;
                    _alertsOn = (response.d.Preferences & 1) == 1;
                    _alertsFrequency = response.d.Alerts;
                    if (msg === 1)
                        onRegister(email);
                    else {
                        switch (msg) {
                            case 0:
                                displayFormError(form, "There was a problem completing your registration.");
                                break;
                            case -1:
                                displayFormError(form, "The email address you entered is already in our system.");
                                break;
                            case -2:
                                displayFormError(form, "You have already registered. Please sign in.");
                                break;
                            case -3:
                                displayFormError(form, "Invalid registration data. Please try again.");
                                break;
                            case -4:
                                displayFormError(form, "Your passwords did not match. Please try again.");
                                break;
                            case -5:
                                displayConfirmationText(email, true);
                                break;
                        }

                    }
                },
                error: function() {
                    displayFormError(form, "There was a problem completing your registration.");
                }
            });
        }

    }

    function displayConfirmationText(email, alreadySent) {
        if (!$j("#registrationConfirmation").length) {
            var rt = document.createElement("div");
            rt.setAttribute("id", "registrationConfirmation");
            rt.setAttribute("class", "dialogBox resizable");
            rt.setAttribute("title", "Registration Confirmation");
            document.body.appendChild(rt);
            $j("#registrationConfirmation").dialog({
                bgiframe: true,
                modal: true,
                autoOpen: false,
                width: 390,
                maxWidth: 390,
                minWidth: 390
            });
        }
        $j(".dialogBox:visible input").val("");
        $j(".dialogBox:visible").dialog('close');
        $j("#registrationConfirmation").dialog('open');
        followUpText = "<p>A confirmation email";
        followUpText += alreadySent ? " was previously" : " has been";
        followUpText += " sent to <b>" + email + "</b>. Please click the link in the email to validate your registration.</p><br/>";
        followUpText += "<p><a href='#' onclick='Sawbuck.UserManager.resendConfirmationEmail(); return false;'>Re-Send Email</a>";
        followUpText += " &#160;or&#160; ";
        followUpText += "<a href='#' onclick=\"$j('.updatedEmailSection').fadeIn(); return false;\">Update Email Address</a></p>";
        followUpText += "<div class='updatedEmailSection' style='display: none'><br/><div class='error'></div>";
        followUpText += "<input type='text' style='width: 250px; margin-right: 5px;' value='" + email + "' size='40' id='updatedEmailField' name='email'/>"
        followUpText += "<a class='s_button' style='float: left; clear: none;' onclick='Sawbuck.UserManager.updateUnconfirmedEmail(); return false;'><span class='s_button'>Update</span></a></div>"

        $j("#registrationConfirmation").html(followUpText);
        // $j(".ui-dialog-title:visible").text("Registration Confirmation");
        // $j(".dialogBox:visible").html(followUpText);
    }

    function updateUnconfirmedEmail(email) {
        $j.ajax({
            type: "POST",
            url: "/service/WebService.asmx/UpdateAccountInfo",
            data: Sawbuck.Utilities.toJson({ Email: email, FirstName: "", LastName: "" }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            processData: false,
            success: function(response) {
                if (response.d == true) {
                    resendConfirmationEmail(email);
                    displayConfirmationText(email);
                }
                else {
                    $j(".updatedEmailSection .error").text("The email address you entered is already in use.");
                }
            }
            , error: function() {
                // There was a problem sending this invitation
            }
        });

    }

    function signIn(form) {
        email = $j(form).find("input[name=email_address]").val();
        pw = $j(form).find("input[name=password]").val();

        if (Sawbuck.Utilities.trim(email).length < 2 || Sawbuck.Utilities.trim(pw).length < 2) {
            displayFormError(form, 'Must enter your email address and password');
        }
        else if (!_emailRegEx.test(email)) {
            displayFormError(form, 'Not a valid email address');
        }
        else {
            data = { Email: email, Password: pw, Url: window.location.toString() };
            $j.ajax({
                type: "POST",
                url: "/service/WebService.asmx/Login",
                data: Sawbuck.Utilities.toJson(data),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processData: false,
                dataFilter: function(data, type) {
                    //Turns ASP.NET dates into Javascript readable dates
                    return data.replace(/"\\\/(Date\([0-9-]+\))\\\/"/gi, 'new $1');
                },
                success: function(response) {
                    var msg = response.d.Msg;
                    _alertsOn = (response.d.Preferences & 1) == 1;
                    _alertsFrequency = response.d.Alerts;
                    if (msg == 1)
                        onLogin();
                    else if (msg == 2048)
                        displayConfirmationText(email, true);
                    else
                        displayFormError(form, "Invalid credentials.");
                },
                error: function() {
                    displayFormError(form, "There was a problem signing you in.");
                }
            });
        }

    }

    function addUser(email) {
        $j.ajax({
            type: "POST",
            url: "/service/WebService.asmx/InviteUser",
            data: Sawbuck.Utilities.toJson({ Email: email }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            processData: false,
            success: function(response) {
                $j("#addUserForm").dialog('close');
                $j("#addUserInviteSent").show();
                setTimeout(function() { $j("#addUserInviteSent").fadeOut('slow') }, _successFade);
            }
            , error: function() {
                // There was a problem sending this invitation
            }
        });
    }

    function changePassword(ePass, nPass, cPass) {
        form = $j("#changePasswordForm").children("form");

        ePass = Sawbuck.Utilities.trim(ePass);
        pw = Sawbuck.Utilities.trim(nPass);
        pw2 = Sawbuck.Utilities.trim(cPass);

        if (!ePass || !pw || !pw2) {
            displayFormError(form, "All fields are required");
            return false;
        }
        if (pw.length < 5) {
            displayFormError(form, 'Password must be at least 5 characters long');
            return false;
        }
        if (pw != pw2) {
            displayFormError(form, "Passwords do not match");
            return false;
        }

        $j.ajax({
            type: "POST",
            url: "/service/WebService.asmx/ChangePassword",
            data: Sawbuck.Utilities.toJson({ OldPassword: ePass, NewPassword: pw, NewPasswordConfirm: pw2 }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            processData: false,
            success: function(response) {
                $j(form).children("input").val("");
                if (response.d == true) {
                    $j("#changePasswordForm").dialog('close');
                    $j("#passwordChangeSuccess").show();
                    setTimeout(function() { $j("#passwordChangeSuccess").fadeOut('slow') }, _successFade);
                }
                else {
                    displayFormError(form, "Invalid credentials. Please try again.");
                }
            }
            , error: function() {
                // There was a problem sending this invitation
            }
        });

    }

    function deleteAccount() {
        $j.ajax({
            type: "POST",
            url: "/service/WebService.asmx/DeleteAccount",
            data: Sawbuck.Utilities.toJson({}),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            processData: false,
            success: function(response) {
                window.location = '/logout';
            }
            , error: function() {
                // There was a problem sending this invitation
            }
        });
    }

    function forgotPassword(form) {
        email = form["email"].value.trim();

        if (!_emailRegEx.test(email)) {
            displayFormError(form, 'Not a valid email address');
            return false;
        }

        $j.ajax({
            type: "POST",
            url: "/service/WebService.asmx/RetrievePassword",
            data: Sawbuck.Utilities.toJson({ Email: email }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            processData: false,
            success: function(response) {
                if (response.d == true) {
                    $j(".dialogBox").dialog('close');
                    alert("An email has been sent with instructions on resetting your password");
                }
                else {
                    displayFormError(form, "That email address is not in our system.");
                }
            }
            , error: function() {
                // There was a problem sending this invitation
            }
        });

    }

    loadUserID();

    // Makes enter key work for registration and sign-in
    try {
        $j(".registrationForm").keyup(function(event) {
            if (window.event && event.keyCode && event.keyCode == 13) {
                register(this);
            }
            else if (event.which == 13) {
                register(this);
            }
        });
        $j(".signInForm").keyup(function(event) {
            if (window.event && event.keyCode && event.keyCode == 13) {
                signIn(this);
            }
            else if (event.which == 13) {
                signIn(this);
            }
        });
    } catch (e) { console.log(e); }

    return {

        init: function(opts) {
            _userID = opts.userID || _userID;
            _partnerID = opts.partnerID || _partnerID;
            _loggedIn = opts.loggedIn || _loggedIn;
            _alertsOn = opts.emailAlertsOn || _alertsOn;
            _alertsFrequency = opts.emailAlertsFrequency || _alertsFrequency;
            if (_loggedIn) updateRSSLinks();
        },

        addListener: function(event, listener) {
            _listeners[event] = _listeners[event] || [];
            _listeners[event].push(listener);
        },


        isLoggedIn: function() {
            return _loggedIn;
        },

        alertsOn: function() {
            return _alertsOn;
        },

        getAlertsFrequency: function() {
            return _alertsFrequency;
        },

        logout: function() {
            Sawbuck.Utilities.deleteCookie("User");
            _alertsOn = false;
            _loggedIn = false;
            _userID = null;
            onLogout();
        },

        register: function(form) {
            return register(form);
        },

        resendConfirmationEmail: function() {
            return resendConfirmationEmail();
        },

        signIn: function(form) {
            return signIn(form);
        },

        updateInfo: function(firstName, lastName, email) {
            updateInfo(firstName, lastName, email);
        },

        updateUnconfirmedEmail: function() {
            updateUnconfirmedEmail($j("#updatedEmailField").val());
        },

        changePassword: function(ePass, nPass, cPass) {
            changePassword(ePass, nPass, cPass);
        },

        addUser: function(email) {
            addUser(email);
        },

        deleteAccount: function() {
            deleteAccount();
        },

        forgotPassword: function(form) {
            forgotPassword(form);
        },

        showForgotPassword: function() {
            $j(".dialogBox").dialog('close');
            $j("#forgotPasswordWindow").dialog('open');
        },

        modo: function(name) {
            if (!_loggedIn)
                $j("#" + name).dialog('open');
            return false;
        },

        getUserID: function() {
            return _userID;
        },

        getPartnerID: function() {
            return _partnerID;
        },

        emailAlertsOn: function(frequency) {
            _alertsOn = true;
            _alertsFrequency = frequency;
        },

        emailAlertsOff: function(frequency) {
            _alertsOn = false;
            _alertsFrequency = 2;
        }

    };

})();