
/*jslint devel: false, browser: true, undef: true, unparam: true, sloppy: true, vars: true, white: true, nomen: true, plusplus: true, maxerr: 50, indent: 4 */
/*global $, Element, Event, Tx, SSDialog, SSApp, SSData, Store, SSDialog, alert */

var SSUser = {};

// support various user operations - signin/out, profile editing, email list signup, upload of images

function MUserProfileContext(firstField)
{
    if (firstField) {
        this._firstTextField = document.getElementById(firstField);
    }
    this._bigButtonImage = document.getElementById("bigButtonImg");
    this._userButtonPathField = document.getElementById("userButtonPath");
    // setup selections
    if (this._bigButtonImage) {
        this.selectButtonDiv();
    }
    this.selectFirstTextField();
}

MUserProfileContext.prototype.handleUserProfileOKClicked = function(event)
{
    if (document.userProfileForm.agreeTerms && !document.userProfileForm.agreeTerms.checked) {
        Element.show('agreeTermsError');
        Event.stop(event);
        return;
    }

    SSApp.trimTextArea('userDescription', 2000);
    // Set the pending url to the users stylebook page
    if (document.UseHandleForPendingOperation) {
        var handleField = document.getElementById('handle');
        var handleString = handleField.value;
        var activeDialog = SSDialog.dialogContext.getActiveDialog();
        activeDialog.pendingOperationUrl = "/users/" + encodeURIComponent(handleString);
    }
    SSUser.doSecureUserOperation('userProfileForm');
    Event.stop(event);
};

MUserProfileContext.prototype.handleUserProfileCancelClicked = function(event)
{
    document.UseHandleForPendingOperation = false;
    Event.stop(event);
    SSDialog.closeDialog();
};

MUserProfileContext.prototype.handleCheckboxClicked = function(checkbox)
{
    var hiddenFieldName = checkbox.name.replace(/-visible$/, '');
    checkbox.form.elements[hiddenFieldName].value = checkbox.checked ? 'on' : 'off';
};

MUserProfileContext.prototype.handleUserProfileFormKeyPress = function(event)
{
    if (event.keyCode === Event.KEY_RETURN && !this.formIgnoreCR) {
        this.handleUserProfileOKClicked(event);
    }
    this.formIgnoreCR = false;
};

MUserProfileContext.prototype.smallToBigImageName = function(imageNameString)
{
    return imageNameString.replace(/_small/, '');
};

MUserProfileContext.prototype.bigToSmallImageName = function(imageNameString)
{
    return imageNameString.replace(/\.png/, "_small.png");
};

MUserProfileContext.prototype.getImageNameString = function(imgElement)
{
    return Tx.isIE6() ? imgElement.style.filter : imgElement.src;
};

MUserProfileContext.prototype.setBigButtonImage = function(imgElement)
{
    if (Tx.isIE6()) {
        var imageFilter = imgElement.style.filter;
        imageFilter = this.smallToBigImageName(imageFilter);
        this._bigButtonImage.style.filter = imageFilter;
    }
    else {
        var imageName = imgElement.src;
        imageName = this.smallToBigImageName(imageName);
        this._bigButtonImage.src = imageName;
    }
};

MUserProfileContext.prototype.handleMouseOverButton = function(imgElement, event)
{
    this.setBigButtonImage(imgElement);
    Event.stop(event);
};

MUserProfileContext.prototype.handleMouseClickButton = function(imgElement, event)
{
    this.selectImage(imgElement);
    Event.stop(event);

    if (event.shiftKey) {
        var userType = document.getElementById('userType');
        if (this.getImageNameString(imgElement).indexOf('button55') > -1) {
            userType.value = "1";
        }
        if (this.getImageNameString(imgElement).indexOf('button56') > -1) {
            userType.value = "2";
        }
        if (this.getImageNameString(imgElement).indexOf('button57') > -1) {
            userType.value = "3";
        }
        if (this.getImageNameString(imgElement).indexOf('button58') > -1) {
            userType.value = "4";
        }
    }
};

MUserProfileContext.prototype.selectImage = function(imgElement)
{
    var userButtonPathField = this._userButtonPathField;
    var smallButtonNameString = this.getImageNameString(imgElement);
    userButtonPathField.value = this.smallToBigImageName(smallButtonNameString);
    var divElement = imgElement.parentNode;
    var previousSelectionDiv = userButtonPathField.previousSelection;
    if (previousSelectionDiv) {
        previousSelectionDiv.style.border = "1px solid white";
    }
    divElement.style.border = "1px solid black";
    userButtonPathField.previousSelection = divElement;
};

MUserProfileContext.prototype.selectButtonDiv = function()
{
    var userButtonPathField = this._userButtonPathField;
    var targetImageName = userButtonPathField.value;
    targetImageName = this.bigToSmallImageName(targetImageName);
    var bigButtonImage = this._bigButtonImage;
    var bigButtonDiv = bigButtonImage.parentNode;
    var bigButtonTd = bigButtonDiv.parentNode;
    var imgs = bigButtonTd.getElementsByTagName("IMG");
    var imgCount = imgs.length;
    var imgIndex;
    for (imgIndex = 0; imgIndex < imgCount; imgIndex++) {
        var imgElement = imgs[imgIndex];
        var imgElementSrc = this.getImageNameString(imgElement);
        if (imgElement.id !== 'bigButtonImg' && imgElementSrc.indexOf(targetImageName) !== -1) {
            this.selectImage(imgElement);
            this.setBigButtonImage(imgElement);
            break;
        }
    }
};

MUserProfileContext.prototype.handleMouseOutButtons = function(event)
{
    this.selectButtonDiv();
    Event.stop(event);
};

MUserProfileContext.prototype.stopEvent = function(event)
{
    Event.stop(event);
};

MUserProfileContext.prototype.handleUserDescriptionTextAreaKeyPress = function(event)
{
    var eventKeyCode = event.keyCode;
    if (eventKeyCode === Event.KEY_TAB) {
        this.selectFirstTextField();
        Event.stop(event);
    }
    else if (eventKeyCode === Event.KEY_RETURN) {
        this.formIgnoreCR = true;
    }
};

MUserProfileContext.prototype.selectFirstTextField = function()
{
    if (this._firstTextField) {
        SSApp.selectTextField(this._firstTextField);
    }
};

SSUser.editProfileClicked = function(event, hyperlink)
{
    document.UseHandleForPendingOperation = true;
    Event.stop(event);
    SSDialog.openDialog(hyperlink, hyperlink.href, null);
    return false;
};

MUserProfileContext.prototype.handleFirstTextFieldKeyPress = function(event)
{
    if (event.keyCode === Event.KEY_TAB && event.shiftKey) {
        Event.stop(event);
    }
};

////////////////////
// Register User
////////////////////

function MRegisterUserContext(firstField)
{
    this._firstTextField = document.getElementById(firstField);
    SSApp.selectTextField(this._firstTextField);
}

MRegisterUserContext.prototype.handleOKClicked = function(event)
{
    Event.stop(event);
    SSDialog.postFormAndOpen('userRegisterForm', false);
};

MRegisterUserContext.prototype.handleCancelClicked = function(event)
{
    Event.stop(event);
    SSDialog.closeDialog();
};

MRegisterUserContext.prototype.handleFormKeyPress = function(event)
{
    if (event.keyCode === Event.KEY_RETURN) {
        this.handleOKClicked(event);
    }
};

MRegisterUserContext.prototype.handleFirstTextFieldKeyPress = function(event)
{
    if (event.keyCode === Event.KEY_TAB && event.shiftKey) {
        Event.stop(event);
    }
};

//////////////////
// Sign In/Out
//////////////////

// relay a call from an iframe-in-iframe
SSUser.relaySecureCall = function(errorCode, userId, digest, expiration, omniEvent)
{
    var url = '/action/finishSecure?errorStatus=' + errorCode;
    if (userId !== null) {
        url += '&uid=' + userId + '&digest=' + digest + '&expire=' + expiration;
        if (omniEvent) {
            url += '&omniEvent=' + omniEvent;
        }
    }
    var options = {
        method: 'post',
        onSuccess: function(xmlhttp){
            var error = Tx.getResponseText(xmlhttp);
            if (error === "3") {
                // fraud - close the dialog
                SSDialog.dialogContext.close();
            }
            else {
                // normal case
                SSDialog.dialogContext.getActiveDialog().finishSecureDialog(errorCode);
            }
        }
    };
    Tx.ajax(url, options);
};

function MSignInContext()
{
    this._firstTextField = document.getElementById('handle');
    this.selectFirstTextField();
}

MSignInContext.prototype.selectFirstTextField = function()
{
    if (this._firstTextField) {
        SSApp.selectTextField(this._firstTextField);
    }
};

MSignInContext.prototype.handleOKClicked = function(event)
{
    SSUser.doSecureUserOperation('signInForm');

    Event.stop(event);
};

MSignInContext.prototype.handleFacebookSignin = function(userId, signedRequest, expiration, accessToken)
{
    // disable buttons so that user doesn't click one of these while the page is refreshing
    Store.disableButton('okButton');
    Store.disableButton('cancelButton');
    Store.disableButton('registerButton');

    // transfer arguments over to the signin form
    $('fbuid').value = userId;
    $('fbsr').value = signedRequest;
    $('fbex').value = expiration;
    $('fbat').value = accessToken;

    // does not have to be secure because all information is actually going in facebook cookies
    // need to submit the form to keep us within the standard signin dialog flow
    SSDialog.postFormAndOpen('facebookSignInForm', false);
};

MUserProfileContext.prototype.handleFacebookConnect = function(userId, signedRequest, expiration, accessToken)
{
    // transfer arguments over to the user profile form
    $('fbuid').value = userId;
    $('fbsr').value = signedRequest;
    $('fbex').value = expiration;
    $('fbat').value = accessToken;
};

SSUser.handleSignoutClicked = function(event, notificationHRef, redirect, partnerUserId, href)
{
    Tx.clearCookie("sc1", SSData.cookieDomain);
    if (notificationHRef) {
        if (!redirect) {
            // sugar approach - queue logout notification
            // signout notification includes the partner id
            Tx.setCookie('sc17', '1.' + partnerUserId, 0, SSData.cookieDomain);
            if (href === null) {
                window.location.reload();
            }
            else {
                window.location = (href !== undefined) ? href : "/home";
            }
        }
        else {
            // partner approach - redirect
            window.location = notificationHRef;
        }
    }
    else {
        window.location = "/home";
    }
    Event.stop(event);
    return false;
};

MSignInContext.prototype.handleFormKeyPress = function(event)
{
    if (event.keyCode === Event.KEY_RETURN && !event.formIgnoreCR) {
        this.handleOKClicked(event);
    }
};

MSignInContext.prototype.handlePasswordKeyPress = function(event)
{
    if (event.keyCode === Event.KEY_TAB) {
        this.selectFirstTextField();
        Event.stop(event);
    }
};

MSignInContext.prototype.signUpClicked = function(linkElement,event)
{
    var activeDialog = SSDialog.dialogContext.getActiveDialog();
    var pendingOperationUrl = activeDialog.pendingOperationUrl;
    var isPendingUrlForDialog = activeDialog.isPendingUrlForDialog;
    SSDialog.closeDialog();
    var url = linkElement.href;
    var handleElement = document.getElementById('handle');
    var handleValue = (handleElement === null) ? "" : handleElement.value.trim();
    if (handleValue.length > 0) {
        var separator = url.indexOf('?') === -1 ? "?" : "&";
        url = url + separator + "handle=" + encodeURIComponent(handleValue);
    }
    SSDialog.openDialog(linkElement, url, pendingOperationUrl, null, isPendingUrlForDialog);
    return false;
};

MSignInContext.prototype.forgotPasswordClicked = function(linkElement,event)
{
    SSDialog.closeDialog();
    SSDialog.openDialog(linkElement, linkElement.href, "");
    return false;
};

SSUser.doSecureUserOperation = function(formName)
{
    try {
        SSDialog.postFormAndOpen(formName, true);
    }
    catch (e) {
        if (Tx.isIE6()) {
            alert(Store.getMessage("ie6SecureOperationError"));
        }
        throw e;
    }
};

//////////////////////////////
// Join Mailing List Support
//////////////////////////////

function MJoinMailingListContext(name, mayAddToFashionNewsletter, mayAddToSaleAlerts, forDialog, forPopunder)
{
    this._textField = document.getElementById(name + 'Field');
    if (this._textField) {
        this._initalTextFieldValue = Store.joinListValue;
        this._textField.value = this._initalTextFieldValue;
        this._initialTextFieldClassName = this._textField.className;
        this._linkElement = document.getElementById(name + 'Link');
        this._successDiv = document.getElementById(name + 'SuccessDiv');
        this._errorDiv = document.getElementById(name + 'ErrorDiv');
        this._hideOnSuccessDiv = document.getElementById(name + 'PromptDiv');
        this._mayAddToFashionNewsletter = mayAddToFashionNewsletter;
        this._mayAddToSaleAlerts = mayAddToSaleAlerts;
        this._forDialog = forDialog;
        this._forPopunder = forPopunder;
    }
}

//in the email list signup dialog check to ensure that at least one check box is checked
MJoinMailingListContext.prototype.validateCheckBoxes = function()
{
    this._mayAddToSaleAlerts = document.getElementById("saleAlertCBox").checked;
    this._mayAddToFashionNewsletter = document.getElementById("fashionNewsletterCBox").checked;
    var checkOneErrorDiv = document.getElementById("checkOneErrorDiv");
    var disabledButtonImage = document.getElementById("disabledButtonImage");
    if (!this._mayAddToSaleAlerts && !this._mayAddToFashionNewsletter) {
        checkOneErrorDiv.style.visibility = 'visible';
        disabledButtonImage.style.display = '';
    }
    else {
        checkOneErrorDiv.style.visibility = 'hidden';
        disabledButtonImage.style.display = 'none';
    }
};

MJoinMailingListContext.prototype.submitRequest = function()
{
    var joinListContext = this;
    var textField = this._textField;
    var parameterValue = textField.value;
    if (parameterValue !== this._initalTextFieldValue || this._forDialog) {
        var parameterName = textField.name;
        var href = this._linkElement.href;
        var separator = href.indexOf('?') !== -1 ? "&" : "?";
        var url = href + separator + parameterName + '=' + parameterValue;
        if (this._mayAddToFashionNewsletter) {
            url = url + "&addToFashionNewsletter=true";
        }
        if (this._mayAddToSaleAlerts) {
            url = url + "&addToPriceAlerts=true";
        }
        var successDiv = this._successDiv;
        var hideOnSuccessDiv = this._hideOnSuccessDiv;
        var hideSuccessFunction = function() {
            if (successDiv) {
                successDiv.style.display = "none";
                joinListContext.restoreTextField();
            }
        };
        var handleAjaxResponseFunction = function(xmlhttp) {
            var dialogContents = Tx.getResponseText(xmlhttp);
            if (Tx.handleAjaxExceptionPage(dialogContents)) {
                return;
            }
            else if (dialogContents.indexOf('success') !== -1) {
                if (successDiv) {
                    successDiv.style.display = '';
                }
                if (!hideOnSuccessDiv) {
                    window.setTimeout(hideSuccessFunction, 4000);
                } else {
                    hideOnSuccessDiv.style.display = "none";
                }

                // If this is in the popunder, close it after a time
                if (joinListContext._forPopunder) {
                    window.setTimeout(window.close, 3000);
                }
                // If this is in the home page dialog, close the dialog after a time
                if (joinListContext._forDialog && !joinListContext._forPopunder) {
                    window.setTimeout(SSDialog.closeDialogIfExists, 3000);
                }
            }
            else {
                var errorDiv = joinListContext._errorDiv;
                errorDiv.style.display = '';
            }
        };
        var optionsDict = {
                method: 'get',
                onSuccess: handleAjaxResponseFunction
        };
        Tx.ajax(url, optionsDict);
    }
    return false;
};

MJoinMailingListContext.prototype.handleKeyDown = function(event)
{
    if (event.keyCode === Event.KEY_RETURN) {
        this.submitRequest();
        Event.stop(event);
    }
    var errorDiv = this._errorDiv;
    if (errorDiv.style.display !== 'none') {
        errorDiv.style.display = 'none';
    }
};

MJoinMailingListContext.prototype.handleJoinClicked = function(event)
{
    this.submitRequest();
    Event.stop(event);
    return false;
};

MJoinMailingListContext.prototype.handleFocus = function()
{
    if (this._textField.value === this._initalTextFieldValue) {
        this._textField.value = '';
        this._textField.className = this._initialTextFieldClassName + ' hilite';
    }
};

MJoinMailingListContext.prototype.restoreTextField = function()
{
    this._textField.value = this._initalTextFieldValue;
    this._textField.className = this._initialTextFieldClassName;
};

MJoinMailingListContext.prototype.handleBlur = function(event)
{
    if (this._textField.value === '') {
        this.restoreTextField();
    }
    Event.stop(event);
};


Tx.addEventListenerToElement(window,
        'load',
        function() {MJoinMailingListContext.singleton = new MJoinMailingListContext('joinList', true, false, false);},
        false);

////////////////////
// Forgot Password
////////////////////

function MForgotPasswordContext()
{
    this._firstTextField = document.getElementById('email');
    this.selectFirstTextField();
}

MForgotPasswordContext.prototype.selectFirstTextField = function()
{
    if (this._firstTextField !== null) {
        SSApp.selectTextField(this._firstTextField);
    }
};

MForgotPasswordContext.prototype.handleOKClicked = function(event)
{
    SSDialog.postFormAndOpen('forgotPasswordForm');
    Event.stop(event);
};

MForgotPasswordContext.prototype.handleFormKeyPress = function(event)
{
    if (event.keyCode === Event.KEY_RETURN) {
        this.handleOKClicked(event);
    }
};

////////////////////
// Reset Password
////////////////////

// XXX There is a lot of duplicated code (albeit short functions) acrss these
// XXX various "context" objects.  Need to find some way to rationalize this.

function MResetPasswordContext()
{
    this._firstTextField = document.getElementById('password');
    this.selectFirstTextField();
}

MResetPasswordContext.prototype.selectFirstTextField = function()
{
    if (this._firstTextField !== null) {
        SSApp.selectTextField(this._firstTextField);
    }
};

MResetPasswordContext.prototype.handleOKClicked = function(event)
{
    SSUser.doSecureUserOperation('resetPasswordForm');
    Event.stop(event);
};

MResetPasswordContext.prototype.handleFormKeyPress = function(event)
{
    if (event.keyCode === Event.KEY_RETURN) {
        this.handleOKClicked(event);
    }
};

MResetPasswordContext.prototype.handlePasswordConfirmKeyPress = function(event)
{
    if (event.keyCode === Event.KEY_TAB) {
        this.selectFirstTextField();
        Event.stop(event);
    }
};

MResetPasswordContext.prototype.forgotPasswordClicked = function(linkElement,event)
{
    var activeDialog = SSDialog.dialogContext.getActiveDialog();
    var pendingOperationUrl = activeDialog.pendingOperationUrl;
    SSDialog.closeDialog();
    SSDialog.openDialog(linkElement, linkElement.href, pendingOperationUrl);
    return false;
};

//////////////////
// Upload images
//////////////////

var SSUpload = {};

// for keeping track of the attempted saves, so that we can ignore cancelled saves
SSUpload.postId = 3;
SSUpload.postTimeout = null;

SSUpload.okClicked = function(event)
{
    SSUpload.setupUI(false, null);

    // if the upload takes too long we want to renable the user's ui so that they can try again
    var handleTimeout = function()
    {
        SSUpload.setupUI(true, $('serverErrorMessage').firstChild.data);
        SSUpload.postTimeout = null;
        // so that we ignore any late responses from the server:
        SSUpload.postId++;
    };
    SSUpload.postTimeout = setTimeout(handleTimeout, 10*1000);

    SSUpload.postId++;
    $('postId').value = SSUpload.postId;

    document.uploadForm.submit();
    Event.stop(event);
    return false;
};

SSUpload.clearImageClicked = function(event)
{
    SSUpload.setupUI(false, null);
    $('cleared').value = "1";
    $('uploadControl').value = "";
    document.uploadForm.submit();
    Event.stop(event);
    return false;
};

SSUpload.doCrop = function(imageUrl, refreshAfterDialog, postId)
{
    if (postId !== SSUpload.postId) {
        // this is a save that we cancelled - ignore it
        return;
    }
    clearTimeout(SSUpload.postTimeout);
    SSUpload.postTimeout = null;
    var url = Tx.replaceParam($('cropDialogActionLink').href, 'imageUrl', imageUrl);
    SSDialog.closeDialog();
    SSDialog.openDialog(null, url, (refreshAfterDialog ? null : ''));
};

SSUpload.uploadError = function(error, postId)
{
    if (postId !== SSUpload.postId) {
        // this is a save that we cancelled - ignore it
        return;
    }
    clearTimeout(SSUpload.postTimeout);
    SSUpload.postTimeout = null;
    SSUpload.setupUI(true, error);
};

SSUpload.setupUI = function(showControls, errorMessage)
{
    if (showControls) {
        $('uploadControl').style.visibility = 'visible';
        $('uploadMessage').style.visibility = 'hidden';
        Store.enableButton('clearButton');
        Store.enableButton('okButton');
        Store.enableButton('cancelButton');

        var errorDiv = $('errorMessage');
        errorDiv.innerHTML = (errorMessage === null) ? '' : errorMessage;
        errorDiv.style.display = 'block';
    }
    else {
        $('uploadControl').style.visibility = 'hidden';
        $('uploadMessage').style.visibility = 'visible';
        $('errorMessage').style.display = 'none';
        Store.disableButton('clearButton');
        Store.disableButton('okButton');
        Store.disableButton('cancelButton');
    }
};

SSUpload.cropOkClicked = function(event)
{
    SSDialog.postFormAndOpen('cropImageForm');
    Event.stop(event);
};

////////////////////
// Groups
////////////////////

// Used for new Group and new Topic dialogs
function MGroupDialogContext(isGroup)
{
    this._firstTextField = document.getElementById('name');
    this.selectFirstTextField();
    this.isGroup = isGroup;
}

MGroupDialogContext.prototype.handleGroupProfileOKClicked = function(event)
{
    SSApp.trimTextArea('description', 2000);
    // Refresh to the new or edited group page
    if (this.isGroup) {
        var nameString = this._firstTextField.value;
        var activeDialog = SSDialog.dialogContext.getActiveDialog();
        activeDialog.pendingOperationUrl = "/groups/" + encodeURIComponent(nameString);
    } else {
        window.location.reload(); // make sure we see page 1 of topics on group page
    }

    SSDialog.postFormAndOpen('groupDialogForm', false);
    Event.stop(event);
};

MGroupDialogContext.prototype.handleFormKeyPress = function(event)
{
    if (event.keyCode === Event.KEY_RETURN && !this.formIgnoreCR) {
        this.handleGroupProfileOKClicked(event);
    }
    this.formIgnoreCR = false;
};

MGroupDialogContext.prototype.handleFirstTextFieldKeyPress = function(event)
{
    if (event.keyCode === Event.KEY_TAB && event.shiftKey) {
        Event.stop(event);
    }
};

MGroupDialogContext.prototype.handleDescriptionTextAreaKeyPress = function(event)
{
    var eventKeyCode = event.keyCode;
    if (eventKeyCode === Event.KEY_TAB) {
        this.selectFirstTextField();
        Event.stop(event);
    }
    else if (eventKeyCode === Event.KEY_RETURN) {
        this.formIgnoreCR = true;
    }
};

MGroupDialogContext.prototype.selectFirstTextField = function()
{
    SSApp.selectTextField(this._firstTextField);
};

