
/**
*  This supports UserProfile.html
*/

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

MUserProfileContext.prototype.handleUserProfileOKClicked = function(event)
{
    if (document.userProfileForm.agreeTerms != null && !document.userProfileForm.agreeTerms.checked) {
        Element.show('agreeTermsError');
        Event.stop(event);
        return;
    }
    
    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 = document.dialogContext.getActiveDialog();
        activeDialog.pendingOperationUrl = "/users/" + encodeURIComponent(handleString);
    }
    doSecureUserOperation('userProfileForm');
    Event.stop(event);
}

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

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 isIE6() ? imgElement.style.filter : imgElement.src;
}

MUserProfileContext.prototype.setBigButtonImage = function(imgElement)
{
    if (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 != null) {
        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;
    for (var 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 != null) {
        selectTextField(this._firstTextField);
    }
}

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

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

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

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

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

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

    Event.stop(event);
}

function handleSignoutClicked(event, href, redirect, partnerUserId)
{
    clearCookie("sc1", store_cookieDomain); 
    if (href != null) {
        if (redirect == null) {
            // sugar approach - queue logout notification
            // signout notification includes the partner id
            setCookie('sc17', '1.' + partnerUserId, 0, store_cookieDomain);
            window.location = "/home";
        }
        else {
            // partner approach - redirect
            window.location = href;
        }
    }
    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 = document.dialogContext.getActiveDialog();
    var pendingOperationUrl = activeDialog.pendingOperationUrl;
    var isPendingUrlForDialog = activeDialog.isPendingUrlForDialog;
    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);
    }
    openDialog(linkElement, url, pendingOperationUrl, null, isPendingUrlForDialog);
    return false;
}

MSignInContext.prototype.forgotPasswordClicked = function(linkElement,event)
{
    var activeDialog = document.dialogContext.getActiveDialog();
    closeDialog();
    openDialog(linkElement, linkElement.href, "");
    return false;
}

function doSecureUserOperation(formName)
{
    try {
        openDialogForForm(formName, true); 
    }
    catch (e) {
        if (isIE6()) {
            alert(store_getMessage("ie6SecureOperationError"));
        }
        throw e;
    }
}

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

function MJoinMailingListContext()
{
    this._textField = document.getElementById('joinListField');
    if (this._textField) {
        this._initalTextFieldValue = store_joinListValue;
        this._textField.value = this._initalTextFieldValue;
        this._initialTextFieldClassName = this._textField.className;
        this._linkElement = document.getElementById('joinListLink');
        this._successDiv = document.getElementById('joinListSuccessDiv');
        this._errorDiv = document.getElementById('joinListErrorDiv');
        this._hideOnSuccessDiv = document.getElementById('joinListPromptDiv');
    }
}

MJoinMailingListContext.prototype.submitRequest = function()
{
    var textField = this._textField;
    var parameterValue = textField.value;
    if (parameterValue != this._initalTextFieldValue) {
        var parameterName = textField.name;
        var href = this._linkElement.href;
        var separator = href.indexOf('?') != -1 ? "&" : "?";
        var url = href + separator + parameterName + '=' + parameterValue;
        var successDiv = this._successDiv;
        var hideOnSuccessDiv = this._hideOnSuccessDiv;
        var hideSuccessFunction = function() {
            successDiv.style.display = "none";
            document.joinListContext.restoreTextField();
        }
        var handleAjaxResponseFunction = function(xmlhttp) {
            var dialogContents = getResponseText(xmlhttp);
            if (handleAjaxExceptionPage(dialogContents)) {
                return;
            }
            else if (dialogContents.indexOf('success') != -1) {
                successDiv.style.display = '';
                if (hideOnSuccessDiv == null) {
                    window.setTimeout(hideSuccessFunction, 4000);
                } else {
                    hideOnSuccessDiv.style.display = "none";
                }
            }
            else {
                var errorDiv = document.joinListContext._errorDiv;
                errorDiv.style.display = '';
            }
        };
        var optionsDict = {
                method: 'get',
                onSuccess: handleAjaxResponseFunction
        };
        new Ajax.Request(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);
}

// added curly braces here to create a temp scope so that initContext is not globally defined
{
    var initContext = function() {
        document.joinListContext = new MJoinMailingListContext();
    }
    tx_addEventListenerToElement(window, 'load', initContext, false);
}

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

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

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

MForgotPasswordContext.prototype.handleOKClicked = function(event)
{
    openDialogForForm('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) {
        selectTextField(this._firstTextField);
    }
}

MResetPasswordContext.prototype.handleOKClicked = function(event)
{
    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 = document.dialogContext.getActiveDialog();
    var pendingOperationUrl = activeDialog.pendingOperationUrl;
    closeDialog();
    openDialog(linkElement, linkElement.href, pendingOperationUrl);
    return false;
}

//////////////////
// Unsubscribe
//////////////////

function handleUnsubscribeOKClicked(event)
{
    closeDialog();
    window.location.replace('/home');
    Event.stop(event);
}

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

function upload_okClicked(event)
{
    var controls = $('uploadControl');
    if (controls != null) {
        controls.style.visibility = 'hidden';
        $('uploadMessage').style.visibility = 'visible';
        store_disableButton('clearButton');
    }
    store_disableButton('okButton');
    store_disableButton('cancelButton');
    
    document.uploadForm.submit();
    Event.stop(event);
    return false;
}

function upload_clearImageClicked()
{
    store_disableButton('okButton');
    store_disableButton('cancelButton');
    store_disableButton('clearButton');
    $('cleared').value = "1";
    $('uploadControl').value = "";
    document.uploadForm.submit();
}

////////////////////
// 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)
{
    trimTextArea('description', 2000);
    // Refresh to the new or edited group page
    if (this.isGroup) {
        var nameString = this._firstTextField.value;
        var activeDialog = document.dialogContext.getActiveDialog();
        activeDialog.pendingOperationUrl = "/groups/" + encodeURIComponent(nameString);
    } else {
        window.location.reload(); // make sure we see page 1 of topics on group page
    }

    openDialogForForm('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()
{
    selectTextField(this._firstTextField);
}
