﻿// Login-related code

// These are used by the popup functions
var delayedPopup = null;
var delayedPopupFunc = null;

// Determines if the skip showing the Test Drive popup.
// This is set to true if the user opts out
var skipTestDrivePopup = false;

// Cookie name
var SKIP_TEST_DRIVE_COOKIE = "SKIP_TEST_DRIVE";

/////////////////////////////////////////////////////////////////////////////////
// Shows a popup.  If a popup requires login and the user is not logged in, 
// the requested popup is stored and the login popup is shown instead.  Upon 
// logging in the requested popup is then displayed.
//
// If mustBeLoggedIn is true, it will prompt the user to login if needed
// If supplied, populateFunc is called after successful login
function showPopup(popup, mustBeLoggedIn, populateFunc){
    
    var showLoginPopup = false;
    if (mustBeLoggedIn) {
        showLoginPopup = !isLoggedIn();
    }
    
    if(showLoginPopup) {
        delayedPopup = popup;
        delayedPopupFunc = populateFunc;
        showLoginDivertPopup();
    } else {
        delayedPopup = null;
        delayedPopupFunc = null;

        if (populateFunc){
            var args = new Array();
            for(var i=3;i<arguments.length;i++){
                args.push(arguments[i]);
            }
            populateFunc.call(this, popup, args);
        }

        displayPopupAsModal(popup);
    }
}

/////////////////////////////////////////////////////////////////////////////////
// Shows a popup.  If the user isn't logged in, display the Test Drive popup
// to ask them to login or register.  Either of these can be skipped and the
// user is able to click through to the popup without logging in/registering.
//
// If supplied, populateFunc is called after successful login
function showLoginOptionalPopup(popup, populateFunc){

    var loggedIn = isLoggedIn();
    
    if (!loggedIn && !skipTestDrivePopup) {
        delayedPopup = popup;
        delayedPopupFunc = populateFunc;
        showTestDrivePopup();
    } else {
        delayedPopup = null;
        delayedPopupFunc = null;
        
        if (populateFunc){
            var args = new Array();
            for(var i=3;i<arguments.length;i++){
                args.push(arguments[i]);
            }
            populateFunc.call(this, popup, args);
        }        
        
        displayPopupAsModal(popup);        
    }
}

/////////////////////////////////////////////////////////////////////////////////
// Find all <INPUT /> elements and bind a keypress event that looks for the 
// enter key.  If found, clickItem.click()
function registerInputClick(popup, clickItem){

    popup
        // Allow user to submit by pressing enter
        .find("input[type=text]").unbind("keypress").keypress(function(e){
            var key = (e.charCode ? e.charCode : e.keyCode);
            if (key==13) {
                // Return - click and prevent event bubbling
                clickItem.click();
                return false;
            }
            // Not our key - allow to bubble up
            return true;
        }).end()
}

/////////////////////////////////////////////////////////////////////////////////
// Set up common options for form validation
function setupValidationForm(options){
    var form = $(options.form);
    var validator = form.validate({
//debug: true,
        onsubmit: false,
        onfocusout: false,
        onkeyup: false,
        errorClass: options.errorClass,
        errorContainer: options.errorContainer,
		success: function(label) {
		    label.parent("li").removeClass(options.errorClass);
		},
        showErrors: function(errorMap, errorList) {
            // Highlight invalid inputs
            $.each(this.invalidElements(), function(i, element) {
    			$(element).parent("li").addClass(options.errorClass);
            });
		    this.defaultShowErrors();
            // Clear out server errors
            $(options.serverErrorContainer).hide();
	    },
        rules: options.rules,
        messages: options.messages
    });

    // Clear error states
    form.find("li." + options.errorClass).removeClass(options.errorClass);
    validator.resetForm();

    return form;
}

/////////////////////////////////////////////////////////////////////////////////
// Shows the login popup and wires up the register and login buttons.
function showLoginPopup(){

    getActionTag("DIHAZ_PUL81007_Pro_Login_lnk");
    getDartTagForAction("830");

    // We need to clear these out in case the user did something that 
    // required login and then cancelled
    delayedPopup = null;
    delayedPopupFunc = null;

    var form = setupValidationForm({
        form: "form#formLogin",
        errorClass: "error",
        errorContainer: "div#loginErrorHeader, div#loginServerErrors",
        serverErrorContainer: "div#loginServerErrors",
        rules: {
            loginEmail: { required: true, email: true },
            loginPassword: "required"
        },
        messages: {
            loginEmail: "The username you provided us with is not valid. Please check your information and try again. ",
            loginPassword: "The password you provided us with is not valid. Please <span class='link' onclick='showForgotPasswordPopup();return false;'>click here</span> to retrieve your password."
        }
    });

    var popup = $("div#popupLogin")
        
        // Add event handler to login button
        .find("input#popupBtnLogin").unbind("click").click(function(){
            if (form.valid()) {
                performLogin($("input#loginEmail").val(), 
                            $("input#loginPassword").val(), 
                            false,
                            $("div#loginServerErrors"));
            }            
            return false;
        }).end()
        
        // Add event handler to register button
        .find("input#popupBtnRegisterLogin").unbind("click").click(function(){
            showRegisterPopup(false);
            return false;
        }).end()
        
        // Add event handler for forgot password button
        .find("a#popupLnkLoginForgotPassword").unbind("click").click(function(){
            showForgotPasswordPopup();
            return false;
        }).end();

    // Clear form
    popup.find("form")[0].reset();
    
    // Manually submit when user presses enter in <INPUT />
    registerInputClick(popup, popup.find("input#popupBtnLogin"));

    displayPopupAsModal(popup);
}

/////////////////////////////////////////////////////////////////////////////////
// Shows the forgot password popup
function showForgotPasswordPopup(){
    
    var form = setupValidationForm({
        form: "form#formForgotPassword",
        errorClass: "error",
        errorContainer: "div#forgotPasswordErrorHeader, div#forgotPasswordServerErrors",
        serverErrorContainer: "div#forgotPasswordServerErrors",
        rules: {
            forgotPasswordEmail: {  required: true, 
                                    email: true, 
                                    registeredEmailAddress: $("input#forgotPasswordEmail")
                                 }
        },
        messages: {
            forgotPasswordEmail: {  required: "Please enter a valid e-mail address.",
                                    email: "Please enter a valid e-mail address.",
                                    registeredEmailAddress: "We're sorry, but this e-mail address is not recognized. Please check the e-mail address you've provided and try again." 
                                 }
        }
    });
                                
    var popup = $("div#popupForgotPassword")

        .find("input#popupBtnForgotPassword").unbind("click").click(function(){
            if (form.valid()) {
                sendPasswordReminder($("input#forgotPasswordEmail").val(), 
                                    $("div#forgotPasswordServerErrors"));
            }
            return false;
        }).end()
        
        .find("input#popupBtnForgotPasswordCancel").unbind("click").click(function(){
            closePopups();
            return false;
        }).end();


    // Clear form
    popup.find("form")[0].reset();
    
    // Manually submit when user presses enter in <INPUT />
    registerInputClick(popup, popup.find("input#popupBtnForgotPassword"));
    
    displayPopupAsModal(popup);

}


/////////////////////////////////////////////////////////////////////////////////
// Shows the popup as modal and wires up the container to close it when clicked
// Also puts the focus on the first visible text input
// Ultimately, all popups are displayed with this function
function displayPopupAsModal(popup){

    // Hide any visible popups
    closePopups();
    
    if (popup) {
    
        // And keypress handler for the links on this popup
        // to make navigating the popup via keyboard easier
        popup.find("a,input[type=image]").unbind("keyup").keyup(function(e){
            var allowToBubble = false;
            var key = (e.charCode ? e.charCode : e.keyCode);
            switch(key){
                case 37: // left arrow
                case 38: // up arrow
                    $(this).prev("a,input[type=image]").focus();
                    break;
                case 39: // right arrow
                case 40: // down arrow
                    $(this).next("a,input[type=image]").focus();
                    break;
                default: // We don't handle this key, so let it bubble up
                    allowToBubble = true;
            }
            return allowToBubble;
        }).end();   

        // Add click handler popup close link
        popup.find("p.closePopup").unbind("click").click(function(){
            closePopups();
            return false;
        }).end();
    
        $(popup).modal({
    		overlay:1,
            overlayId:'modalOverlay',
            containerId:'modalContainer',
            close:false, 
            persist:true, 
            onShow: function (dialog){
                
                var defaultLink = popup.find(".defaultLink");
                if (defaultLink.length > 0) {
                    //  If there's a default link, set focus to it
                    defaultLink.focus();
                } else { 
                    // Otherwise set focus to popup's first input
                    var firstInput = popup.find("input:text:first:visible");
                    createSelection(firstInput, 0, 999);
                }
                
                // Close popup when user clicks off
                $("div.modalOverlay").unbind("click").click(function(){
                    closePopups();
                    return false;
                });
            }
        });
    }
}

/////////////////////////////////////////////////////////////////////////////////
// Selects a portion of the input string
// input is a jQuery $("input")
function createSelection(input, start, end){
	if (input.length == 0) return;
	
    // Get a reference to the input element
	var field = input.get(0);
	
	if (field.type != "text") return;
	
	if (field.createTextRange){
        // IE
		var selRange = field.createTextRange();
		selRange.collapse(true);
		selRange.moveStart("character", start);
		selRange.moveEnd("character", end);
		selRange.select();
	} else if (field.setSelectionRange){
		field.setSelectionRange(start, end);
	} else {
		if (field.selectionStart){
			field.selectionStart = start;
			field.selectionEnd = end;
		}
	}
	field.focus();
}

/////////////////////////////////////////////////////////////////////////////////
// Saves cookies used for automatic login
function saveLoginCookies(){
    $.cookie(EMAIL_COOKIE, UserProfile.eEmail);
    $.cookie(PASSWORD_COOKIE, UserProfile.ePassword);
}

/////////////////////////////////////////////////////////////////////////////////
// Called on successful login.
function loginSuccessful(){

    // Hide any visible popups
    closePopups();

    // Save cookies used for automatic login
    saveLoginCookies();
    
    // Update login link to show logout text
    updateLoginLinks();

    // Update practice name
    updatePracticeName();
    
    // Get user's custom bundles
    getCustomBundles(UserProfile.userID);

    setAddButtonState();

    // If the user was redirected to a login popup while trying to display another 
    // popup, show them their original popup now that they're logged in
    if (delayedPopup) {
        showPopup(delayedPopup, true, delayedPopupFunc);
    }
}

/////////////////////////////////////////////////////////////////////////////////
// Called when the user is asked to register but chooses to skip ahead w/o registering
function registrationBypassed(){

    getDartTagForAction("495");

    showPopup(delayedPopup, false, delayedPopupFunc);
}

/////////////////////////////////////////////////////////////////////////////////
// Returns whether the current user is logged in
function isLoggedIn(){
    return (UserProfile != null);
}

/////////////////////////////////////////////////////////////////////////////////
// Attempt to log in using cookie values, if they exist
function attemptAutomaticLogin(){

    // Try to get values from cookies
    var eEmail = $.cookie(EMAIL_COOKIE);
    var ePassword = $.cookie(PASSWORD_COOKIE);
    var cookiesExist = ((eEmail != null) && (ePassword != null));

    // If cookies exist, try logging in
    if (cookiesExist) {
        performLogin(eEmail, ePassword, true);
    }
}

/////////////////////////////////////////////////////////////////////////////////
// Update login link text and show/hide register button according to login state
function updateLoginLinks(){
    if (isLoggedIn()) {
        $("a#lnkRegister").parent("li").hide();
        $("a#lnkProfile").parent("li").show();
        $("a#lnkLogin").parent("li").hide();
        $("a#lnkLogout").parent("li").show();
    } else {
        $("a#lnkRegister").parent("li").show();
        $("a#lnkProfile").parent("li").hide();
        $("a#lnkLogin").parent("li").show();
        $("a#lnkLogout").parent("li").hide();
    }
}

/////////////////////////////////////////////////////////////////////////////////
// Logs the user out
function logout(){

    getDartTagForAction("270");

    removeCustomBundles();
    
    UserProfile = null;
    $.cookie(EMAIL_COOKIE, null);
    $.cookie(PASSWORD_COOKIE, null);

    // Wipe out test drive cookie
    saveTestDriveCookie(null);

    // Update login link to show login text
    updateLoginLinks();   
    
    // Update practice name
    updatePracticeName();
    
    // If we find no predefined bundles, they were probably removed because the 
    // "premade bundle template user" logged in, and the premade bundles were 
    // replaced with their custom equivalents (and removed when they logged out).  
    // In this case, we'll reload the page to get them back.
    var predefinedBundles = $("div#productsList").find("input.hidType[value=" + TYPE_BUNDLE + "]").parent("li");
    if (predefinedBundles.length == 0) {
        // Reload from the server, not the cache!
        location.reload(true);
    }
}

/////////////////////////////////////////////////////////////////////////////////
// Determines if the passed in email address has already been registered
// Returns whether email address is registered
function registeredEmailAddress(email){
    
    var success = false;
    var emailParam = {
        'email':email
    };
    
    var um = new UserManager();
    var result = um.registeredEmailAddress(emailParam);
    if (ajaxSuccess(result)) {
    
        // Extract result from return value
        result = extractAjaxResult(result);
        success = (result > 0);
    
    }
    return success;
}

/////////////////////////////////////////////////////////////////////////////////
// Determines if the passed in email address has already been registered
// errorDiv is a jQuery $(div) where any error text will be displayed
// Returns whether email address is registered
function sendPasswordReminder(email, errorDiv){
    
    var success = false;
    var emailParam = {
        'email':email
    };
    
    var um = new UserManager();
    var result = um.sendPasswordReminder(emailParam);
    
    success = ajaxSuccess(result);
    if (success) {
        closePopups();
        alert("Your password will be sent to you shortly.");
    } else {
        // Show any error
        if(errorDiv) {
            // If there's an error div, display an error message
            if (!result) result = "Action Failed";
            errorDiv.html(result).show();
        } else {
            // Otherwise alert() it
            alert("Action failed: " + result);
        }
    }
    return success;
}

/////////////////////////////////////////////////////////////////////////////////
// Performs the actual login
// errorDiv is a jQuery $(div) where any error text will be displayed
// Returns whether login was successful
function performLogin(email, password, encrypted, errorDiv){
    
    var success = false;
    var loginCredentials = {
        'email':email, 
        'password':password,
        'encrypted':encrypted
    }; 
    var um = new UserManager();
    var result = um.login(loginCredentials);
    if (ajaxSuccess(result)) {
        
        // Extract result from return value
        result = extractAjaxResult(result);
        
        // eval() will create a local variable "ajaxResult" with a JSON object 
        // containing this user's profile
        try {
            eval(result);
        } catch (e) {
            result = "eval() failed[" + e + "]: " + result;
            success = false;
        }

        // Make sure everything went ok
        if (ajaxResult) {
            UserProfile = ajaxResult.items[0];
        
            if (UserProfile) {
                loginSuccessful();
                success = true;
            }
        }
    }

    // Show any error
    if (!success) {
        if(errorDiv) {
            // If there's an error div, display an error message
            if (!result) result = "Login Failed";
            errorDiv.html(result).show();
        } else {
            // Otherwise alert() it
            alert("Login failed: " + result);
        }
    }
    return success;
}


/////////////////////////////////////////////////////////////////////////////////
// Shows the login divert popup and wires up the register and login buttons.
// 
// This login popup will be shown when the user tries to perform
// and action that requires logging in
function showLoginDivertPopup(){

    //getActionTag("DIHAZ_PUL81007_Pro_Login_lnk");
    //getDartTagForAction("830");

    var form = setupValidationForm({
        form: "form#formLoginDivert",
        errorClass: "error",
        errorContainer: "div#loginDivertErrorHeader, div#loginDivertServerErrors",
        serverErrorContainer: "div#loginDivertServerErrors",
        rules: {
            loginDivertEmail: { required: true, email: true },
            loginDivertPassword: "required"
        },
        messages: {
            loginDivertEmail: "The username you provided us with is not valid. Please check your information and try again. ",
            loginDivertPassword: "The password you provided us with is not valid. Please <span class='link' onclick='showForgotPasswordPopup();return false;'>click here</span> to retrieve your password."
        }
    });
    
    var popup = $("div#popupLoginDivert")

        // Add event handler to login button
        .find("input#popupBtnLoginDivert").unbind("click").click(function(){
            if (form.valid()) {
                performLogin($("input#loginDivertEmail").val(), 
                            $("input#loginDivertPassword").val(), 
                            false,
                            $("div#loginDivertServerErrors"));
            }            
            return false;
        }).end()
      
        // Add event handler to register button
        .find("input#popupBtnRegisterLoginDivert").unbind("click").click(function(){
            showRegisterPopup(true);
            return false;
        }).end()
        
        // Add event handler for forgot password button
        .find("a#popupLnkLoginDivertForgotPassword").unbind("click").click(function(){
            showForgotPasswordPopup();
            return false;
        }).end();

    // Clear form
    popup.find("form")[0].reset();
    
    // Manually submit when user presses enter in <INPUT />
    registerInputClick(popup, popup.find("input#popupBtnLoginDivert"));

    displayPopupAsModal(popup);
}

/////////////////////////////////////////////////////////////////////////////////
// Shows the login popup and wires up the register, bypass, and login buttons
//
// This popup can be used anywhere you want an option to login without requiring 
// a login to present the popup.
function showTestDrivePopup(){

    //getActionTag("DIHAZ_PUL81007_Pro_Login_lnk");
    //getDartTagForAction("830");

    var form = setupValidationForm({
        form: "form#formLoginTestDrive",
        errorClass: "error",
        errorContainer: "div#loginTestDriveErrorHeader, div#loginTestDriveServerErrors",
        serverErrorContainer: "div#loginTestDriveServerErrors",
        rules: {
            loginTestDriveEmail: { required: true, email: true },
            loginTestDrivePassword: "required"
        },
        messages: {
            loginTestDriveEmail: "The username you provided us with is not valid. Please check your information and try again. ",
            loginTestDrivePassword: "The password you provided us with is not valid. Please <span class='link' onclick='showForgotPasswordPopup();return false;'>click here</span> to retrieve your password."
        }
    });
    
    var popup = $("div#popupLoginTestDrive")

        // Add event handler to login button
        .find("input#popupBtnLoginTestDrive").unbind("click").click(function(){
            if (form.valid()) {
                performLogin($("input#loginTestDriveEmail").val(), 
                            $("input#loginTestDrivePassword").val(), 
                            false,
                            $("div#loginTestDriveServerErrors"));
            }            
            return false;
        }).end()

        // Add event handler to register button
        .find("input#popupBtnRegisterTestDrive").unbind("click").click(function(){
            showRegisterPopup(false);
            return false;
        }).end()
    
        // Skips logging in but shows the popup
        .find("input#popupBtnSkipTestDrive").unbind("click").click(function(){
            // Save skip checkbox state
            var checkState = $("input#chkDontShowAgain").get(0).checked;
            saveTestDriveCookie(checkState);
            registrationBypassed();
            return false;
        }).end()
        
        // Add event handler for forgot password button
        .find("a#popupLnkTestDriveForgotPassword").unbind("click").click(function(){
            showForgotPasswordPopup();
            return false;
        }).end();

    // Clear form
    popup.find("form")[0].reset();
    
    // Manually submit when user presses enter in <INPUT />
    registerInputClick(popup, popup.find("input#popupBtnLoginTestDrive"));
    
    displayPopupAsModal(popup);
}

/////////////////////////////////////////////////////////////////////////////////
// Loads the "skip test drive" cookie value if available
function loadTestDriveCookie(){
    var cookieVal = $.cookie(SKIP_TEST_DRIVE_COOKIE);
    if (cookieVal) {
        skipTestDrivePopup = $.cookie(SKIP_TEST_DRIVE_COOKIE);
    }
}

/////////////////////////////////////////////////////////////////////////////////
// Saves the "skip test drive" cookie value
function saveTestDriveCookie(value){
    skipTestDrivePopup = value;
    $.cookie(SKIP_TEST_DRIVE_COOKIE, value);

    // Set checkbox state to value
    $("input#chkDontShowAgain").get(0).checked = value;
}

/////////////////////////////////////////////////////////////////////////////////
// Performs the actual registration
// errorDiv is a jQuery $(div) where any error text will be displayed
// Returns whether registration was successful
function performRegistration(firstName, lastName, email, password, 
                             optinProduct, optinBrand, optinContact, 
                             errorDiv)
{
    var success = false;
    var registrationInfo = {
        'firstName':firstName,
        'lastName':lastName,
        'email':email, 
        'password':password,
        'optinProduct':optinProduct, 
        'optinBrand':optinBrand, 
        'optinContact':optinContact
    };

    var um = new UserManager();
    var result = um.register(registrationInfo);
    if (ajaxSuccess(result)) {
        
        // Extract result from return value
        result = extractAjaxResult(result);
        
        // eval() will create a local variable "ajaxResult" with a JSON object 
        // containing this user's profile
        try {
            eval(result);
        } catch (e) {
            result = "eval() failed[" + e + "]: " + result;
            success = false;
        }

        // Make sure everything went ok
        if (ajaxResult) {
            UserProfile = ajaxResult.items[0];
        
            if (UserProfile) {
                loginSuccessful();
                success = true;
            }
        }
    }

    // Show any error
    if (!success) {
        if(errorDiv) {
            // If there's an error div, display an error message
            if (!result) result = "Registration Failed";
            errorDiv.html(result).show();
        } else {
            // Otherwise alert() it
            alert("Registration failed: " + result);
        }
    }
    return success;
}

/////////////////////////////////////////////////////////////////////////////////
// Shows the registration popup
function showRegisterPopup(delayedPopupMustBeLoggedIn){

    getDartTagForAction("030");

    var form = setupValidationForm({
        form: "form#formRegister",
        errorClass: "error",
        errorContainer: "div#registerErrorHeader, div#registerServerErrors",
        serverErrorContainer: "div#registerServerErrors",
        rules: {
            registerFirstname: "required",
            registerLastname: "required",
            registerEmail: { required: true, email: true },
            registerEmailConfirm: { required: true, email: true, equalTo: "#registerEmail" },
            registerPassword: { required: true, minlength: 5, maxlength: 8, strongPassword: true },
            registerPasswordConfirm: { required: true, equalTo: "#registerPassword" }
        },
        messages: {
            registerFirstname: "Please enter your first name.",
            registerLastname: "Please enter your last name.",
            registerEmail: "Please enter a valid e-mail address.",
            registerEmailConfirm: "E-mail addresses must match.",         
            registerPassword: { required:"Please enter a password.", 
                                minlength: "Passwords must be between 5-8 characters.", 
                                maxlength: "Passwords must be between 5-8 characters.", 
                                strongPassword: "Please enter a valid password." },
            registerPasswordConfirm: "Passwords must match."
        }
    });
    
    var popup = $("div#popupRegister")
        
        // Cancel button
        .find("input#popupBtnRegisterCancel").unbind("click").click(function(){
            closePopups();
            return false;
        }).end()
        
        // Submit button
        .find("input#popupBtnRegisterSubmit").unbind("click").click(function(){

            if (form.valid()) {
                var success = performRegistration($("input#registerFirstname").val(),
                            $("input#registerLastname").val(),
                            $("input#registerEmail").val(),
                            $("input#registerPassword").val(),
                            $("input#chkProduct")[0].checked,
                            $("input#chkBrand")[0].checked,
                            $("input#chkContact")[0].checked,
                            $("div#registerServerErrors"));

                if (success) {
                    getActionTag("DIHAZ_PUL81007_Pro_Register_Submit_btn");
                    getDartTagForAction("094");
                
                    // If the user came here while trying to access another popup, proceed to that popup
                    if (delayedPopup) {
                        showPopup(delayedPopup, delayedPopupMustBeLoggedIn, delayedPopupFunc);
                    }
                }
            }
            return false;
        }).end();

    // Clear form
    popup.find("form")[0].reset();
    
    // Manually submit when user presses enter in <INPUT />
    registerInputClick(popup, popup.find("input#popupBtnRegisterSubmit"));
    
    displayPopupAsModal(popup);
}






