/*
 * main.js
 *
 * Copyright (c) 2006-2009 by Goose Networks, Inc.
 *
 */

var AccessTysons = {};

/**
 * Encapsulate all logic around the login/registration panel in this
 * singleton.
 */
AccessTysons.loginPanel = function() {

    /**
     * The underlying YUI Panel.
     */
    var _panel;

    /**
     * The destination URL.
     */
    var _destURL;

    /**
     * Buttons.
     */
    var _loginButton;
    var _goToRegistrationButton;

    /**
     * The ID of the parent DOM elt.
     **/
    var _id = 'login-panel';

// Initialize the panel once the DOM is ready.
    YAHOO.util.Event.onDOMReady(function() {
        var cfg;
        cfg = {
            constraintoviewport: true,
            draggable: true,
            fixedcenter: true,
            modal: true,
            width: "30em",
            visible: false
        }
        // Instantiate the YUI panel (and hide it).
        _panel = new YAHOO.widget.Panel(_id, cfg );
        _panel.render();
        initForm();
    }, this, true);

    /**
     * Initialize the login form.
     */
    var initForm = function() {
        _loginButton = new YAHOO.widget.Button('login-button');
        _loginButton.addListener('click', function(e) {
           handleLogin();
        });

        _goToRegistrationButton = new YAHOO.widget.Button('go-to-registration-button');
        _goToRegistrationButton.addListener('click', function(e) {
            showRegisterForm();
        });
    };

    /**
     * Handle a login attempt.
     */
    var handleLogin = function() {
        var email;
        var password;
        var cb;
        var params;

        enableAllButtons(false);
        hideAllMessages();

        cb = {
            success: function(o) {
                var response;
                response = YAHOO.lang.JSON.parse(o.responseText);
                enableAllButtons(true);
                if (response.status == '0') {
                    // Success!
                    if (!_destURL) {
                        _destURL = "/";
                    }
                    window.location = _destURL;
                } else {
                    showErrorMessage(response.message);
                }
            },
            failure: function(o) {
                enableAllButtons(true);
                showErrorMessage('Sorry, but an unexpected error occurred. ' +
                                 'Please try again later');
            }
        };

        email = DOM.get('login-input-email').value;
        password = DOM.get('login-input-password').value;

        params = 'email=' + email + '&password=' + password + '&_cu_async=true';
        YAHOO.util.Connect.asyncRequest('POST',
                                        '/_cu_login',
                                        cb, params);
    };

    /**
     * Enable/disable all inputs.
     */
    var enableAllButtons = function(fEnable) {
        _loginButton.set('disabled', !fEnable);
        _goToRegistrationButton.set('disabled', !fEnable);
        DOM.get('login-wait').style.display = fEnable ? 'none' : '';
    };

    /**
     * Hide all confirmation messages and error messages.
     */
    var hideAllMessages = function() {
        DOM.get('login-status-confirm').style.display = 'none';
        DOM.get('login-status-err').style.display = 'none';
    };

    /**
     * Show an error message.
     */
    var showErrorMessage = function(msg) {
        DOM.get('login-status-err-span').innerHTML = msg;
        DOM.get('login-status-confirm').style.display = 'none';
        DOM.get('login-status-err').style.display = '';
    };

    /**
     * Show the registration form.
     */
    var showRegisterForm = function () {
        _panel.hide();
        AccessTysons.registerPanel.show(_destURL);
    }

    /**
     * The 'public' API.
     */
    return {

        /**
         * Display the login panel.
         */
        show: function(destURL) {
            _destURL = destURL;
            _panel.show();
        },

        /**
         * Hides the login panel.
         */
        hide: function() {
            _panel.hide();
        }
    };
}();


/**
 * Encapsulate all logic around the registration panel in this singleton.
 */
AccessTysons.registerPanel = function() {

    /**
     * The underlying YUI Panel.
     */
    var _panel;

    /**
     * The destination URL.
     */
    var _destURL;

    /**
     * Buttons.
     */
    var _registerButton;

    /**
     * The ID of the parent DOM elt.
     **/
    var _id = 'register-panel';

    // Initialize the panel once the DOM is ready.
    YAHOO.util.Event.onDOMReady(function() {
        var cfg;

        cfg = {
            constraintoviewport: true,
            draggable: true,
            fixedcenter: true,
            modal: true,
            width: '30em',
            visible: false
        }

        // Instantiate the YUI panel (and hide it).
        _panel = new YAHOO.widget.Panel(_id, cfg );
        _panel.render();
        initForm();
    }, this, true);

    /**
     * Initialize the register form.
     */
    var initForm = function() {
        var ageCheckbox;
        var tosCheckbox;
        var updateRegisterButton;

        _registerButton = new YAHOO.widget.Button('register-button');
        _registerButton.addListener('click', function(e) {
           handleRegister();
        });

        ageCheckbox = DOM.get('register-input-age');
        tosCheckbox = DOM.get('register-input-terms-of-service');
        updateRegisterButton = function() {
            _registerButton.set('disabled',
                                !ageCheckbox.checked || !tosCheckbox.checked);
        }
        YAHOO.util.Event.addListener(ageCheckbox, 'click', updateRegisterButton);
        YAHOO.util.Event.addListener(tosCheckbox, 'click', updateRegisterButton);
        updateRegisterButton();
    };

    /**
     * Handle a registration attempt.
     */
    var handleRegister = function() {
        var firstName;
        var lastName;
        var email;
        var password;
        var passwordConfirm;
        var ouID;
        var emailOptIn;
        var tosAgree;

        var employerInput;

        var cb;
        var params;

        enableAllButtons(false);
        hideAllMessages();

        cb = {
            success: function(o) {
                var response;
                response = YAHOO.lang.JSON.parse(o.responseText);
                enableAllButtons(true);
                if (response.status == '0') {
                    // Success!
                    if (!_destURL) {
                        _destURL = "/";
                    }
                    window.location = _destURL;
                } else {
                    showErrorMessage(response.message);
                }
            },
            failure: function(o) {
                enableAllButtons(true);
                showErrorMessage('Sorry, but an unexpected error occurred. ' +
                                 'Please try again later');
            }
        };

        firstName = DOM.get('register-input-first-name').value;
        lastName = DOM.get('register-input-last-name').value;
        email = DOM.get('register-input-email').value;
        password = DOM.get('register-input-password').value;
        passwordConfirm = DOM.get('register-input-password-confirm').value;
        employerInput = DOM.get('register-input-employer');
        ouID = employerInput.options[employerInput.selectedIndex].value
        emailOptIn = true;
        tosAgree = DOM.get('register-input-terms-of-service').checked;

        params = 'firstName=' + firstName +
            '&lastName=' + lastName + 
            '&email=' + email +
            '&password=' + password +
            '&passwordConfirm=' + passwordConfirm +
            '&ouID=' + ouID +
            '&emailOptIn=' + emailOptIn +
            '&tosAgree=' + tosAgree +
            '&_cu_async=true';

        YAHOO.util.Connect.asyncRequest('POST',
                                        '/_cu_register',
                                        cb, params);
    };

    /**
     * Enable/disable all inputs.
     */
    var enableAllButtons = function(fEnable) {
        _registerButton.set('disabled', !fEnable);
        DOM.get('register-wait').style.display = fEnable ? 'none' : '';
    };

    /**
     * Hide all confirmation messages and error messages.
     */
    var hideAllMessages = function() {
        DOM.get('register-status-confirm').style.display = 'none';
        DOM.get('register-status-err').style.display = 'none';
    };

    /**
     * Show an error message.
     */
    var showErrorMessage = function(msg) {
        DOM.get('register-status-err-span').innerHTML = msg;
        DOM.get('register-status-confirm').style.display = 'none';
        DOM.get('register-status-err').style.display = '';
    };

    /**
     * The 'public' API.
     */
    return {

        /**
         * Display the login panel.
         */
        show: function(destURL) {
            _destURL = destURL;
            _panel.show();
        }
    };
}();


/**
 * Encapsulate all logic around the mailing list UI in this singleton.
 */
AccessTysons.mailingListUI = function() {

    /**
     * The button div.
     */
    var _buttonContainerDiv;

    /**
     * The input div.
     */
    var _inputContainerDiv;

    /**
     */
    var _errMsgDiv;
    var _errMsgSpan;

    /**
     */
    var _successMsgDiv;

    /**
     * The sign up button.
     */
    var _signUpButton;

    /**
     * The terms and age checkboxes.
     */
    var _termsCB;
    var _ageCB;

    /**
     * The complete registration button.
     */
    var _confirmButton;

    /**
     * Show the registration inputs.
     */
    var handleSignUp = function() {
        DOM.setStyle(_buttonContainerDiv, 'display', 'none');
        DOM.setStyle(_inputContainerDiv, 'display', '');
        DOM.setStyle(_successMsgDiv, 'display', 'none');
        DOM.setStyle(_errMsgDiv, 'display', 'none');
    };

    /**
     * Handle a registration attempt.
     */
    var handleConfirm = function() {
        var firstName;
        var lastName;
        var email;

        var cb;
        var params;

        enableConfirmButton(false);

        cb = {
            success: function(o) {
                var response;
                response = YAHOO.lang.JSON.parse(o.responseText);
                if (response.status == '0') {
                    showSuccess();
                } else {
                    enableConfirmButton(true);
                    showError(response.message);
                }
            },
            failure: function(o) {
                enableConfirmButton(true);
                showErrorMessage('Sorry, but an unexpected error occurred. ' +
                                 'Please try again later');
            }
        };

        firstName = DOM.get('mailing-list-first-name-input').value;
        lastName = DOM.get('mailing-list-last-name-input').value;
        email = DOM.get('mailing-list-email-input').value;

        params = 'firstName=' + firstName +
            '&lastName=' + lastName +
            '&email=' + email;

        YAHOO.util.Connect.asyncRequest('POST',
                                        '/_cu/registerForMailingList',
                                        cb, params);
    };

    /**
     * Enable or disable the 'confirm' button.
     */
    var enableConfirmButton = function(fEnable) {
        _confirmButton.set('disabled', !fEnable);
        _confirmButton.set('label', fEnable ? 'Complete Registration' : 'Please wait...');
    };

    /**
     * Show a success message.
     */
    var showSuccess = function() {
        DOM.setStyle(_buttonContainerDiv, 'display', 'none');
        DOM.setStyle(_inputContainerDiv, 'display', 'none');
        DOM.setStyle(_errMsgDiv, 'display', 'none');
        DOM.setStyle(_successMsgDiv, 'display', '');
    };

    /**
     * Show an error message.
     */
    var showError = function(msg) {
        DOM.setStyle(_buttonContainerDiv, 'display', 'none');
        DOM.setStyle(_inputContainerDiv, 'display', '');
        DOM.setStyle(_successMsgDiv, 'display', 'none');
        DOM.setStyle(_errMsgDiv, 'display', '');
        _errMsgSpan.innerHTML = msg;
    };

    /**
     * Update the status of the 'confirm' button.
     */
    var _updateConfirmButton = function() {
        var fEnable;
        fEnable = _termsCB.checked && _ageCB.checked;
        _confirmButton.set('disabled', !fEnable);
    };

    /**
     * The 'public' API.
     */
    return {

        /**
         * Display the login panel.
         */
        init: function() {
            _buttonContainerDiv = DOM.get('mailing-list-button-container');
            _inputContainerDiv = DOM.get('mailing-list-input-container');
            _errMsgDiv = DOM.get('mailing-list-status-err');
            _errMsgSpan = DOM.get('mailing-list-status-err-span');
            _successMsgDiv = DOM.get('mailing-list-status-success');
            _signUpButton = new YAHOO.widget.Button('mailing-list-button');
            _signUpButton.addListener('click', function(e) {
               handleSignUp();
            });
            _termsCB = DOM.get('mailing-list-terms-of-service-checkbox');
            _ageCB = DOM.get('mailing-list-age-checkbox');
            YAHOO.util.Event.addListener(_termsCB, 'click', _updateConfirmButton);
            YAHOO.util.Event.addListener(_ageCB, 'click', _updateConfirmButton);
            _confirmButton = new YAHOO.widget.Button('mailing-list-confirm-button',
                                                     { disabled: true });
            _confirmButton.addListener('click', function(e) {
               handleConfirm();
            });

            YAHOO.util.Event.addListener('mailing-list-type-input-employee', 'click', function() {
                AccessTysons.registerPanel.show('/');
                DOM.get('mailing-list-type-input-shopper').checked = true;
            });
        }
    };
}();

/**
 * Encapsulate all logic around the reset password panel in this
 * singleton.
 */
AccessTysons.resetPasswordPanel = function() {

    /**
     * The underlying YUI Panel.
     */
    var _panel;

    /**
     * Buttons.
     */
    var _resetPasswordButton;

    /**
     * The ID of the parent DOM elt.
     **/
    var _id = 'reset-password-panel';

    // Initialize the panel once the DOM is ready.
    YAHOO.util.Event.onDOMReady(function() {
        var cfg;
        cfg = {
            constraintoviewport: true,
            draggable: true,
            fixedcenter: true,
            modal: true,
            width: "30em",
            visible: false
        }
        // Instantiate the YUI panel (and hide it).
        _panel = new YAHOO.widget.Panel(_id, cfg );
        _panel.render();
        initForm();
    }, this, true);

    /**
     * Initialize the login form.
     */
    var initForm = function() {
        _resetPasswordButton = new YAHOO.widget.Button('reset-password-button');
        _resetPasswordButton.addListener('click', function(e) {
           handleResetPassword();
        });
    };

    /**
     * Handle a login attempt.
     */
    var handleResetPassword = function() {
        var email;
        var cb;
        var params;

        enableAllButtons(false);
        hideAllMessages();

        cb = {
            success: function(o) {
                var response;
                response = YAHOO.lang.JSON.parse(o.responseText);
                enableAllButtons(true);
                if (response.status == '0') {
                    showSuccessMessage();
                } else {
                    showErrorMessage(response.message);
                }
            },
            failure: function(o) {
                enableAllButtons(true);
                showErrorMessage('Sorry, but an unexpected error occurred. ' +
                                 'Please try again later');
            }
        };

        email = DOM.get('reset-password-input-email').value;

        params = 'email=' + email;
        YAHOO.util.Connect.asyncRequest('POST',
                                        '/_cu/resetPassword',
                                        cb, params);
    };

    /**
     * Enable/disable all inputs.
     */
    var enableAllButtons = function(fEnable) {
        _resetPasswordButton.set('disabled', !fEnable);
        DOM.get('reset-password-wait').style.display = fEnable ? 'none' : '';
    };

    /**
     * Hide all confirmation messages and error messages.
     */
    var hideAllMessages = function() {
        DOM.get('reset-password-status-confirm').style.display = 'none';
        DOM.get('reset-password-status-err').style.display = 'none';
    };

    /**
     * Show an error message.
     */
    var showSuccessMessage = function(msg) {
        DOM.get('reset-password-status-confirm').style.display = '';
        DOM.get('reset-password-status-err').style.display = 'none';
    };

    /**
     * Show an error message.
     */
    var showErrorMessage = function(msg) {
        DOM.get('reset-password-status-err-span').innerHTML = msg;
        DOM.get('reset-password-status-confirm').style.display = 'none';
        DOM.get('reset-password-status-err').style.display = '';
    };

    /**
     * The 'public' API.
     */
    return {

        /**
         * Display the reset password panel.
         */
        show: function() {
            _panel.show();
        },

        /**
         * Show the login form.
         */
        goToLogin: function () {
            _panel.hide();
            AccessTysons.loginPanel.show("/employee-tools/change-password");
        }
    };
}();
