﻿var Sawbuck = window.Sawbuck || {}; Sawbuck.UserManager = (function() {
    var _loggedIn = false; var _userID, _fb_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(); _loggedIn = true; for (var l in _listeners["onLogin"]) { _listeners["onLogin"][l]({ userID: _userID }); }
        $j("#signInWindow").dialog('close'); $j("#registrationWindow").dialog('close');
    }
    function onRegister(email) { 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() { } 
        });
    }
    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() { } 
        });
    }
    function facebookRegister(r) {
        data = { Email: r.email, FirstName: r.first_name, LastName: r.last_name, FacebookID: _fb_userID, Password: "", Password1: "", Url: window.location.toString() }; $j.ajax({ type: "POST", url: "/service/WebService.asmx/RegisterTest", data: Sawbuck.Utilities.toJson(data), contentType: "application/json; charset=utf-8", dataType: "json", processData: false, success: function(response) {
            var msg = response.d.Msg; _alertsOn = (response.d.Preferences & 1) == 1; _alertsFrequency = response.d.Alerts; if (msg === 1)
                onLogin(); 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 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; 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, 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 += "  or  "; 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);
    }
    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() { } 
        });
    }
    function signInWithFacebook(r) {
        if (!r.session) return false; var uid = parseInt(r.session.uid); _fb_userID = _fb_userID || uid; data = { FacebookID: uid }; $j.ajax({ type: "POST", url: "/service/WebService.asmx/LoginFacebook", data: Sawbuck.Utilities.toJson(data), contentType: "application/json; charset=utf-8", dataType: "json", processData: false, success: function(response) {
            var msg = response.d.Msg; _alertsOn = (response.d.Preferences & 1) == 1; _alertsFrequency = response.d.Alerts; if (msg == 1)
                onLogin(); if (msg == 8) { FB.api('/me', facebookRegister) } 
        }, error: function() { displayFormError(form, "There was a problem signing you in."); } 
        });
    }
    function connectToFacebook(r) { var uid = parseInt(r.session.uid); _fb_userID = _fb_userID || uid; data = { FacebookID: uid }; $j.ajax({ type: "POST", url: "/service/WebService.asmx/ConnectToFacebook", data: Sawbuck.Utilities.toJson(data), contentType: "application/json; charset=utf-8", dataType: "json", processData: false, success: function(response) { }, error: function() { } }); }
    function detachFacebook() { $j.ajax({ type: "POST", data: "{FacebookID: null}", url: "/service/WebService.asmx/DeleteFacebookID", contentType: "application/json; charset=utf-8", dataType: "json", processData: false, success: function(response) { }, error: function() { } }); }
    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) { 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() { } }); }
    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() { } 
        });
    }
    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) {
            if (_fb_userID) { FB.api({ method: "auth.revokeAuthorization" }); FB.logout(); }
            window.location = '/logout';
        }, error: function() { } 
        });
    }
    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() { } 
        });
    }
    loadUserID(); try {
        $j(".registrationForm").keyup(function(e) {
            if (window.event && event.keyCode && event.keyCode == 13) {
                e.preventDefault(); e.stopImmediatePropagation(); e.stopPropagation()
                register(this); return false;
            }
            else if (e.which == 13) {
                register(this); e.preventDefault(); e.stopImmediatePropagation(); e.stopPropagation()
                return false;
            } 
        }); $j(".signInForm").keyup(function(e) {
            if (window.event && event.keyCode && event.keyCode == 13) {
                signIn(this); e.preventDefault(); e.stopImmediatePropagation(); e.stopPropagation()
                return false;
            }
            else if (e.which == 13) {
                signIn(this); e.preventDefault(); e.stopImmediatePropagation(); e.stopPropagation()
                return false;
            } 
        });
    } 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; try { if (_fb_userID) FB.logout() } catch (e) { }; onLogout(); }, facebookRegister: facebookRegister, register: register, resendConfirmationEmail: resendConfirmationEmail, signIn: signIn, signInWithFacebook: function() { FB.login(signInWithFacebook, { perms: 'email,publish_stream' }); }, connectToFacebook: function() { FB.login(connectToFacebook); }, detachFacebook: detachFacebook, handleFBStatus: function(res) { if (res.session && !_fb_userID) { _fb_userID = parseInt(res.session.uid); if (!_loggedIn) signInWithFacebook(res); } }, 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: addUser, deleteAccount: deleteAccount, forgotPassword: function(form) { forgotPassword(form); }, showForgotPassword: function() { $j(".dialogBox").dialog('close'); $j("#forgotPasswordWindow").dialog('open'); }, showRegistrationDialog: function(showReason) {
        showReason = (showReason === true) ? 1 : showReason; if (!_loggedIn) { $j("#registrationWindow .mlsReason1, #registrationWindow .mlsReason2").hide(); $j("#registrationWindow").dialog('open'); switch (showReason) { case 1: $j("#registrationWindow .mlsReason1").show(); break; case 2: $j("#registrationWindow .mlsReason2").show(); break; default: break; } }
        return false;
    }, showSignInDialog: function() {
        if (!_loggedIn)
            $j("#signInWindow").dialog('open'); return false;
    }, modo: function(name) {
        if (!_loggedIn)
            $j("#" + name).dialog('open'); return false;
    }, getFBUserID: function() { return _fb_userID; }, getUserID: function() { return _userID; }, getPartnerID: function() { return _partnerID; }, emailAlertsOn: function(frequency) { _alertsOn = true; _alertsFrequency = frequency; }, emailAlertsOff: function(frequency) { _alertsOn = false; _alertsFrequency = 2; } 
    };
})();