


// ItemCollection.js

/// <reference path="../mootools.d.ts" />
var ItemCollection = (function () {
    function ItemCollection() {
    }
    // applies to "gray_shadow" styles only for now
    // these can resize to go to the bottom of the page
    ItemCollection.setSize = function () {
        var b = q$(document.body);
        var cb = $$('.bg_grayShadow .collectionBottom');
        if (cb && cb.length > 0) {
            cb[0].setStyle('height', 'auto');
            var cbPosition = cb[0].getPosition(b);
            var fw = q$('footerWrapper');
            var fwPosition = fw.getPosition(b);
            var desiredHeight = (fwPosition.y - cbPosition.y - 60) + 'px';
            cb[0].setStyle('height', desiredHeight);
        }
    };
    return ItemCollection;
}());




// RegDlgBase.js

///<reference path="Ajax.d.ts"/>
///<reference path="mootools.d.ts" />
///<reference path="CommonWeb.ts" />
/// <reference path="AccountUtil.ts" />
/// <reference path="ActivityMonitor.ts" />
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var RegDlgBase = (function () {
    function RegDlgBase(defValues) {
        if (defValues)
            this._defaultValues = defValues;
        else
            this.clearDefaults();
        this._errors = [];
        this._postRegistrationCallback = null;
        this._afterLoginUrl = null;
        this._pageLinkUrl = null;
        this.setupRequiredRegistrationVariables();
    }
    RegDlgBase.prototype.clearDefaults = function () {
        this._defaultValues = {
            firstName: "",
            lastName: "",
            officeZip: "",
            countryOfPractice: "",
            specialty: "",
            credentials: ""
        };
    };
    /**
     * This tells us if the register/login dialog should start immedialtly after page loading
     * The rules :
     *  1- if query parameter reg=1 is given => auto launch
     *
     *
     * @returns {boolean}  true is it should start, no otherwise
     */
    RegDlgBase.prototype.shouldAutoLaunch = function () {
        return this._autoLaunch;
    };
    RegDlgBase.prototype.setupRequiredRegistrationVariables = function () {
        var u = queryString("u");
        if (this._referrer == null) {
            this._referrer = this.setValueFromUrlOrCookie("referrer", u);
        }
        if (this._registrationDFID == null) {
            this._registrationDFID = RegDlgBase.getSignupDFID();
            if (this._registrationDFID) {
                this.setValueFromUrlOrCookie("signupDFID", this._registrationDFID);
            }
        }
        if (this._signupURI == null) {
            this._signupURI = RegDlgBase.getSignupURI();
            if (this._signupURI) {
                this.setValueFromUrlOrCookie("referralURI", this._signupURI);
            }
        }
        if (this._regid == null) {
            var r = queryString("rgid");
            this._regid = this.setValueFromUrlOrCookie("joinquantiamd", r);
        }
        if (this._autoLaunch == null) {
            this._autoLaunch = queryString("reg") == "1";
        }
        // preserve URL Args from PI_Player
        var strUid = queryString("UID");
        if (strUid) {
            createCookie("joinquantiamd", "");
            for (var i = 0; i < RegDlgBase.piplayer_values.length; i++) {
                var name_1 = RegDlgBase.piplayer_values[i];
                var val = queryString(name_1);
                createCookie(name_1, val, RegDlgBase.ONE_HOUR_AS_DAY);
            }
        }
    };
    RegDlgBase.prototype.doAfterRegistration = function () {
        if (this._postRegistrationCallback)
            this._postRegistrationCallback();
    };
    RegDlgBase.prototype.clearAllErrors = function () {
        this._errors = [];
    };
    RegDlgBase.prototype.getValue = function (e) {
        if (e == null)
            return "";
        if ((typeof e.defaultText != "undefined") && (e.value == e.defaultText))
            return "";
        if ((typeof e.attributes != "undefined") && (e.attributes["defaultText"] != null) && (e.value == e.attributes["defaultText"].value))
            return "";
        if (e.nodeName.toLowerCase() == 'select' && e.selectedIndex > -1) {
            e = e.options[e.selectedIndex];
            if (e != null)
                return e.value;
        }
        else if (e.nodeName.toLowerCase() == 'input') {
            if (e.type.toLowerCase() == 'radio') {
                return e.checked ? "true" : "false";
            }
            if (e.type.toLowerCase() == 'checkbox') {
                return e.checked ? "true" : "false";
            }
        }
        else if (typeof e.value == 'undefined' || e.value == null)
            return null;
        return e.value.trim();
    };
    RegDlgBase.prototype.showErrors = function () {
        var errorMessage;
        var errorContainer = q$('createNewAccountErrorMessage');
        if (errorContainer != null) {
            errorMessage = "<p><img src='/images/icons/icon_warning_on_blue.png'>&nbsp;" +
                QSTR.correctRequiredInformation + "</p><ul>";
            for (var i = 0; i < this._errors.length; i++) {
                errorMessage += "<li>" + this._errors[i] + "</li>";
            }
            errorMessage += "</ul>";
            Common.cshow(errorContainer);
            errorContainer.innerHTML = errorMessage;
        }
        else {
            errorMessage = QSTR.correctRequiredInformation;
            for (var i = 0; i < this._errors.length; ++i) {
                errorMessage += '\n\n' + this._errors[i];
            }
            alert(errorMessage);
        }
    };
    RegDlgBase.containsBadCharacters = function (str) {
        return str.match(/(<)|(>)|(\{)|(})|(\\)/);
    };
    RegDlgBase.prototype.clearSignupURI = function () {
        this.setValueFromUrlOrCookie("referralURI", '');
    };
    RegDlgBase.prototype.setValueFromUrlOrCookie = function (key, value) {
        if (value != null && value != '' && value != 'false') {
            createCookie(key, value);
        }
        else {
            value = readCookie(key);
        }
        if (value != null && value != '') {
            return value;
        }
        return null;
    };
    RegDlgBase.getSignupDFID = function () {
        if (Pageparams.dataformID != null) {
            return ScreenDoor.To(Pageparams.dataformID);
        }
        var dfId = null;
        var screenDoorKey = queryString("c");
        var dfKey = queryString("df");
        if (screenDoorKey) {
            dfId = ScreenDoor.From(screenDoorKey);
        }
        else if (dfKey) {
            dfId = dfKey;
        }
        else {
            var url = location.href;
            var pattern = /^(\w+):\/\/([\w.]+)\/player\/(\w*)/;
            var result = url.match(pattern);
            if (result != null) {
                dfId = result[3];
            }
        }
        if (!dfId) {
            dfId = readCookie('signupDFID');
        }
        return dfId;
    };
    RegDlgBase.getSignupURI = function () {
        var signupURI = null;
        var referrer = queryString("u");
        if (referrer != null) {
            // current URL is one to remember if "u" is set
            signupURI = location.pathname;
        }
        else {
            // otherwise, user may have navigated to another page
            // before joining.  Check for a cookie
            signupURI = readCookie('referralURI');
        }
        if (signupURI == null || signupURI == '') {
            signupURI = location.pathname;
        }
        return signupURI;
    };
    RegDlgBase.requestPassword = function (emailAddress, onSuccess, onFailure) {
        Ajax.post("/q-webclient/?cmd=sendpass&email=" + encodeURIComponent(emailAddress), "", "text/plain", function (results) {
            var resultDocument = XML.CreateDocument(results);
            if (XML.findAndFillValue(resultDocument, "status") == "Success") {
                onSuccess();
            }
            else {
                onFailure(XML.findAndFillValue(resultDocument, "message"));
            }
        }, function (errorMessage) {
            if (onFailure)
                onFailure();
        });
    };
    RegDlgBase.getSignupChallengeScreen = function () {
        var signupChallengeScreen = queryString("cs");
        if (signupChallengeScreen != null)
            signupChallengeScreen = ScreenDoor.unscrambleScreenName(signupChallengeScreen);
        return signupChallengeScreen;
    };
    /**
     * Returns true if a register on page process is planned. this is used in Media player pages whether to show or not the registration screen.
     *
     * @returns {boolean}
     */
    RegDlgBase.prototype.hasRegOnPage = function () {
        return !!q$('signInOrRegFirstTab');
    };
    RegDlgBase.getUserEnteredEmailAddr = function () {
        var emailAddr = q$('usersSignInEmail').value;
        if (emailAddr == QSTR.emailAddressShortLabel)
            emailAddr = '';
        return emailAddr;
    };
    RegDlgBase.getUserEnteredPwd = function () {
        var pwd = q$('usersSignInPassword').value;
        if (pwd == QSTR.passwordLabel)
            pwd = '';
        return pwd;
    };
    RegDlgBase.setFirstDlgTabVisiblity = function (bShow) {
        if (bShow) {
            Common.cshow('signInOrRegFirstTab');
            Common.chide('signInOrRegSubmittingTab');
            Common.cshow('registerOnPage');
        }
        else {
            Common.chide('signInOrRegFirstTab');
            Common.cshow('signInOrRegSubmittingTab');
            Common.chide('registerOnPage');
        }
    };
    RegDlgBase.attemptLoginFromLoginOrReg = function () {
        var emailAddr = RegDlgBase.getUserEnteredEmailAddr();
        var pwd = RegDlgBase.getUserEnteredPwd();
        if (!emailAddr || !pwd)
            return;
        RegDlgBase.setFirstDlgTabVisiblity(false);
        setTimeout(function () {
            gQCredentials.AttemptLogin(emailAddr, pwd, function (result, message) {
                if (result) {
                    Common.chide('signInOrRegSubmittingTab');
                    Common.cshow('signInOrRegPostLoginTab');
                    Pageparams.exitCondition = "register";
                    createCookie("resumeAfterLogin", 'true', Common.ONE_MINUTE_IN_DAYS);
                    Common.attemptWindowQuit();
                    Common.quickReload();
                }
                else {
                    RegDlgBase.setFirstDlgTabVisiblity(true);
                    alert(message);
                }
            });
        }, 1000);
    };
    RegDlgBase.prototype.dologinAfterRegister = function (emailArg, passArg) {
        if (!emailArg) {
            emailArg = q$('usersEmail');
            passArg = q$('usersPassword');
            if (emailArg.value.search(/^Email address:$/) != -1) {
                emailArg = q$('registrationUsersEmail');
                passArg = q$('registrationUsersPassword');
            }
        }
        ActivityMonitor.cancelTimerOnly();
        this.attemptLogin(emailArg.value.trim(), passArg.value.trim(), true);
    };
    RegDlgBase.isIPad = function () {
        return (navigator.userAgent.toLowerCase().indexOf("ipad") != -1);
    };
    RegDlgBase.prototype.attemptLogin = function (username, password, rememberMe) {
        if (RegDlgBase.isIPad()) {
            var url = "playqmd:?";
            // if we're ipad, we need to try to launch the app...
            if (this._afterLoginUrl != null) {
                url = this._afterLoginUrl;
            }
            url = url + "&password=" + encodeURIComponent(password);
            url = url + "&user=" + encodeURIComponent(username);
            document.location.href = url;
            return;
        }
        if (this._afterLoginUrl == null) {
            this._afterLoginUrl = this._pageLinkUrl;
        }
        if (this._afterLoginUrl == null) {
            this._afterLoginUrl = document.location.href;
        }
        if (username == null) {
            username = q$('loginUsername').value;
            this._afterLoginUrl = null; // pageLinkUrl should only be used from registration... not from signups.
        }
        if (password == null) {
            password = q$('loginPassword').value;
        }
        // strip trailing # - bug 7268
        if (this._afterLoginUrl != null)
            this._afterLoginUrl = this._afterLoginUrl.replace(/#$/, '');
        var self = this;
        setTimeout(function () {
            gQCredentials.AttemptLogin(username, password, function (result, message) {
                if (result) {
                    Pageparams.exitCondition = "register";
                    createCookie("resumeAfterLogin", 'true', Common.ONE_MINUTE_IN_DAYS);
                    Common.attemptWindowQuit();
                    var loc = window.location.href;
                    if (self._afterLoginUrl) {
                        if (self._afterLoginUrl == window.location.href) {
                            window.location.reload();
                        }
                        else {
                            window.location.href = self._afterLoginUrl;
                        }
                    }
                    else if (queryString("user")) {
                        loc = loc.replace("user=" + queryString("user"), "");
                        window.location.href = loc;
                    }
                    else {
                        Pageparams.location = window.location.href;
                    }
                }
                else {
                    var msg = QSTR.loginInvalidEmail;
                    var errorMsgElt = q$('errorMessage');
                    if (message && message.indexOf('invalid password') > -1) {
                        msg = QSTR.loginInvalidPassword;
                    }
                    Common.cshow(errorMsgElt);
                    errorMsgElt.innerHTML = msg;
                    q$('headerNav').addClass('errorHeaderNav');
                }
            }, rememberMe);
        }, 200);
    };
    RegDlgBase.finddfid = function () {
        var dfId = null;
        var screenDoorKey = queryString("c");
        var dfKey = queryString("df");
        if (Pageparams.dataformID) {
            dfId = ScreenDoor.To(Pageparams.dataformID);
        }
        else if (screenDoorKey) {
            dfId = ScreenDoor.From(screenDoorKey);
        }
        else if (dfKey) {
            dfId = dfKey;
        }
        else {
            var url = location.href;
            var pattern = /^(\w+):\/\/([\w.]+)\/player\/(\w*)/;
            var result = url.match(pattern);
            if (result) {
                dfId = result[3];
            }
        }
        return dfId;
    };
    RegDlgBase.prototype.setGlobalRegisterActive = function (isActive) {
        var docBody = q$(document.body);
        docBody.toggleClass('registerActive', isActive);
    };
    RegDlgBase.MinPwdLen = 6; // See also Password.ts
    RegDlgBase.piplayer_values = ["X", "UID", "RID", "redirectURL"];
    RegDlgBase.ONE_HOUR_AS_DAY = 1 / 24;
    return RegDlgBase;
}());
var RegDlgEltsBase = (function () {
    function RegDlgEltsBase() {
    }
    RegDlgEltsBase.prototype.addLoginUserElts = function (loginuser) {
        // to override}
    };
    RegDlgEltsBase.validateEmailRegex = function (elem) {
        var emailAddress = elem.value.trim();
        if (!emailAddress)
            return QSTR.enterValidEmail;
        var ematch = emailAddress.match(Common.validEmailAddressRegEx);
        if (!ematch)
            return QSTR.enterValidEmail;
        return null;
    };
    RegDlgEltsBase.validatePassword = function (elem) {
        //do not use getValue here as it does a trim and we don't want to alter the password at all
        var password = elem.value;
        if (!password)
            return QSTR.registerPasswordTooShort;
        if (password.length < RegDlgBase.MinPwdLen)
            return QSTR.registerPasswordTooShort;
        return null;
    };
    return RegDlgEltsBase;
}());
var RegDlgElts2 = (function (_super) {
    __extends(RegDlgElts2, _super);
    function RegDlgElts2() {
        var _this = _super.call(this) || this;
        _this.initialize();
        return _this;
    }
    RegDlgElts2.prototype.validateName = function (elem) {
        var val = elem.value.trim();
        if (!val)
            return QSTR.required;
        if (RegDlgBase.containsBadCharacters(val))
            return QSTR.badChars;
        return null;
    };
    RegDlgElts2.prototype.validateCountryOfPractice = function (copelem, countryelem) {
        var copIndex = copelem.selectedIndex;
        if (copIndex >= 0) {
            countryelem.value = copelem.options[copIndex].value;
        }
        if (copIndex < 0) {
            return QSTR.required;
        }
        return null;
    };
    RegDlgElts2.prototype.validateZipCode = function (zipelem, copelem) {
        var zipval = zipelem.value.trim();
        var copval;
        var copIndex = copelem.selectedIndex;
        if (copIndex >= 0) {
            copval = this.countryOfPractice.options[copIndex].value;
        }
        if (!zipval)
            return QSTR.enterValidZip;
        if (copval == 'US') {
            if (zipval.length < 5)
                return QSTR.enterValidZip;
            if (!zipval.match(/^\d{5}(-?\d{4})?$/))
                return QSTR.enterValidZip;
        }
        else {
            //if (BaseRegisterDialog.containsBadCharacters(zipval))
            //    return QSTR.enterValidZip;
        }
        return null;
    };
    RegDlgElts2.prototype.validateCredentials = function (credElem, credOther) {
        var val = credElem.value.trim();
        if (!val || val.toLowerCase() === QSTR.other.toLowerCase())
            return QSTR.required;
        else
            return null;
    };
    RegDlgElts2.prototype.validateSpecialty = function (elem) {
        var index = elem.selectedIndex;
        if (index <= 0)
            return QSTR.required;
        else
            return null;
    };
    RegDlgElts2.prototype.validateConfirmPassword = function (elem1, elem2) {
        //do not use getValue here as it does a trim and we don't want to alter the password at all
        var confirmPassword = elem2.value;
        var password = elem1.value;
        if (!password && !confirmPassword)
            return null;
        if (password != confirmPassword)
            return QSTR.mismatch;
        else
            return null;
    };
    RegDlgElts2.prototype.validateTerms = function (elem) {
        var val = elem.checked;
        if (val)
            return null;
        else
            return QSTR.required;
    };
    // should be called by RegisterDialog.js or similar Registration regime.
    RegDlgElts2.prototype.initialize = function () {
        var self = this;
        self.firstName = q$('registrationFirstName');
        self.firstName.valfun = function () {
            return self.validateName(self.firstName);
        };
        self.lastName = q$('registrationLastName');
        self.lastName.valfun = function () {
            return self.validateName(self.lastName);
        };
        self.officeZip = q$('registrationOfficeZip');
        self.country = q$('registrationCountry');
        self.countryOfPractice = q$('registrationCountryOfPractice');
        self.officeZip.valfun = function () {
            return self.validateZipCode(self.officeZip, self.countryOfPractice);
        };
        self.countryOfPractice.valfun = function () {
            return self.validateCountryOfPractice(self.countryOfPractice, self.country);
        };
        self.credMD = q$('registrationCredentialsMD');
        self.credDO = q$('registrationCredentialsDO');
        self.credPA = q$('registrationCredentialsPA');
        self.credNP = q$('registrationCredentialsNP');
        self.credOther = q$('registrationCredentialsOther');
        self.credentials = q$('registrationCredentials');
        self.credentials.valfun = function () {
            return self.validateCredentials(self.credentials, self.credOther);
        };
        self.specialty = q$('registrationSpecialty');
        self.specialty.valfun = function () {
            return self.validateSpecialty(self.specialty);
        };
        self.usersEmail = q$('registrationUsersEmail');
        self.usersEmail.valfun = function () {
            return RegDlgEltsBase.validateEmailRegex(self.usersEmail);
        };
        self.usersPassword = q$('registrationUsersPassword');
        self.usersPassword.valfun = function () {
            return RegDlgEltsBase.validatePassword(self.usersPassword);
        };
        self.confirmPassword = q$('registrationConfirmPassword');
        self.confirmPassword.valfun = function () {
            return self.validateConfirmPassword(self.usersPassword, self.confirmPassword);
        };
        self.optInAgreeToTerms = q$('registrationOptInAgreeToTerms');
        if (self.optInAgreeToTerms) {
            // this is an optionnal field not used in all implementations
            self.optInAgreeToTerms.valfun = function () {
                return self.validateTerms(self.optInAgreeToTerms);
            };
        }
        self.joinQuantia = q$('joinQuantia');
        self.joinQuantiaButtonLabel = q$('registerJoinButtonLabel');
        self.usersPassword1 = q$('registrationUsersPassword1');
        self.credMD.captureSpacebarOrEnter = true;
        self.credOther.captureSpacebarOrEnter = true;
        var onlyMdElt = q$('onlyMDFlagForJavascript');
        if (!onlyMdElt) {
            self.credDO.captureSpacebarOrEnter = true;
            self.credPA.captureSpacebarOrEnter = true;
            self.credNP.captureSpacebarOrEnter = true;
        }
        self.joinQuantia.captureSpacebarOrEnter = true;
        self.allElements = {
            'tabElements': [
                self.firstName,
                self.lastName,
                self.officeZip,
                self.countryOfPractice,
                self.credMD,
                self.credDO,
                self.credPA,
                self.credNP,
                self.credOther,
                self.credentials,
                self.specialty,
                self.usersEmail,
                self.usersPassword,
                self.confirmPassword,
                self.optInAgreeToTerms,
                self.joinQuantia
            ],
            'submitButton': self.joinQuantia
        };
        if (self.optInAgreeToTerms) {
            // this is an optionnal field not used in all implementations
            self.allElements['tabElements'].push(self.optInAgreeToTerms);
        }
        if (onlyMdElt) {
            var itemsToRemove = [self.credDO, self.credPA, self.credNP];
            itemsToRemove.each(function (item) {
                var itemIndex = self.allElements['tabElements'].indexOf(item);
                self.allElements['tabElements'].splice(itemIndex, 1);
                "";
            });
        }
    };
    RegDlgElts2.prototype.addLoginUserElts = function (loginuser) {
        this.allElements.tabElements.push(loginuser);
        this.allElements.tabElements.push(q$('loginpwd_prompt'));
        this.allElements.tabElements.push(q$('loginButton'));
        this.allElements.tabElements.push(q$('forgotPassword'));
    };
    return RegDlgElts2;
}(RegDlgEltsBase));
/**
 * RegDlgEltsUnivStyle handles the dialogs used for Univadis like design registration screens
 */
var RegDlgEltsUnivStyle = (function (_super) {
    __extends(RegDlgEltsUnivStyle, _super);
    function RegDlgEltsUnivStyle() {
        var _this = _super.call(this) || this;
        _this.initialize();
        return _this;
    }
    /**
     * returns the back button dom element for the dialog
     * @returns {any}
     */
    RegDlgEltsUnivStyle.prototype.getBackButton = function () {
        return this._backButton;
    };
    RegDlgEltsUnivStyle.prototype.validateName = function (elem) {
        var val = elem.value.trim();
        var defaultText = elem.getAttribute("defaulttext") || null;
        if (!val || val == defaultText)
            return QSTR.required;
        if (RegDlgBase.containsBadCharacters(val))
            return QSTR.badChars;
        return null;
    };
    RegDlgEltsUnivStyle.prototype.validatePassword = function (elem) {
        //do not use getValue here as it does a trim and we don't want to alter the password at all
        var defaultText = elem.getAttribute("defaulttext") || null;
        var password = elem.value;
        if (!password || password == defaultText)
            return QSTR.registerPasswordTooShort;
        if (password.length < RegDlgBase.MinPwdLen)
            return QSTR.registerPasswordTooShort;
        return null;
    };
    RegDlgEltsUnivStyle.prototype.validateCountryOfPractice = function (copelem, countryelem) {
        var copIndex = copelem.selectedIndex;
        if (copIndex >= 0) {
            countryelem.value = copelem.options[copIndex].value;
        }
        if (copIndex < 0) {
            return QSTR.required;
        }
        return null;
    };
    RegDlgEltsUnivStyle.prototype.validateZipCode = function (zipelem, copelem) {
        var zipval = zipelem.value.trim();
        var copval;
        var copIndex = copelem.selectedIndex;
        if (copIndex >= 0) {
            copval = this.countryOfPractice.options[copIndex].value;
        }
        if (!zipval)
            return QSTR.enterValidZip;
        if (copval == 'US') {
            if (zipval.length < 5)
                return QSTR.enterValidZip;
            if (!zipval.match(/^\d{5}(-?\d{4})?$/))
                return QSTR.enterValidZip;
        }
        else {
            //if (BaseRegisterDialog.containsBadCharacters(zipval))
            //    return QSTR.enterValidZip;
        }
        return null;
    };
    RegDlgEltsUnivStyle.prototype.validateCredentials = function (credElem, credOther) {
        var val = credElem.value.trim();
        var defaultText = credElem.getAttribute("defaulttext") || null;
        if (!val || val.toLowerCase() === QSTR.other.toLowerCase() || val == defaultText)
            return QSTR.required;
        else
            return null;
    };
    RegDlgEltsUnivStyle.prototype.validateSpecialty = function (elem) {
        var index = elem.selectedIndex;
        if (index <= 0)
            return QSTR.required;
        else
            return null;
    };
    RegDlgEltsUnivStyle.prototype.validateConfirmPassword = function (elem1, elem2) {
        //do not use getValue here as it does a trim and we don't want to alter the password at all
        var confirmPassword = elem2.value;
        var password = elem1.value;
        if (!password && !confirmPassword)
            return null;
        if (password != confirmPassword)
            return QSTR.mismatch;
        else
            return null;
    };
    RegDlgEltsUnivStyle.prototype.validateTerms = function (elem) {
        var val = elem.checked;
        if (val)
            return null;
        else
            return QSTR.required;
    };
    // should be called by RegisterDialog.js or similar Registration regime.
    RegDlgEltsUnivStyle.prototype.initialize = function () {
        var self = this;
        self._backButton = q$('registerDialogBackButton');
        self.firstName = q$('registrationFirstName');
        self.firstName.valfun = function () {
            return self.validateName(self.firstName);
        };
        self.lastName = q$('registrationLastName');
        self.lastName.valfun = function () {
            return self.validateName(self.lastName);
        };
        self.officeZip = q$('registrationOfficeZip');
        self.country = q$('registrationCountry');
        self.countryOfPractice = q$('registrationCountryOfPractice');
        self.officeZip.valfun = function () {
            return self.validateZipCode(self.officeZip, self.countryOfPractice);
        };
        self.countryOfPractice.valfun = function () {
            return self.validateCountryOfPractice(self.countryOfPractice, self.country);
        };
        self.credMD = q$('registrationCredentialsMD');
        self.credDO = q$('registrationCredentialsDO');
        self.credPA = q$('registrationCredentialsPA');
        self.credNP = q$('registrationCredentialsNP');
        self.credOther = q$('registrationCredentialsOther');
        self.credentials = q$('registrationCredentials');
        self.credentials.valfun = function () {
            return self.validateCredentials(self.credentials, self.credOther);
        };
        self.specialty = q$('registrationSpecialty');
        self.specialty.valfun = function () {
            return self.validateSpecialty(self.specialty);
        };
        self.usersEmail = q$('registrationUsersEmail');
        self.usersEmail.valfun = function () {
            return RegDlgEltsBase.validateEmailRegex(self.usersEmail);
        };
        self.usersPassword = q$('registrationUsersPassword');
        self.usersPassword.valfun = function () {
            return self.validatePassword(self.usersPassword);
        };
        self.confirmPassword = q$('registrationConfirmPassword');
        self.confirmPassword.valfun = function () {
            return self.validateConfirmPassword(self.usersPassword, self.confirmPassword);
        };
        self.joinQuantia = q$('joinQuantia');
        self.joinQuantiaButtonLabel = q$('registerJoinButtonLabel');
        self.usersPassword1 = q$('registrationUsersPassword1');
        self.loginButtonOnRegPage = q$('signInButton1');
        self.credMD.captureSpacebarOrEnter = true;
        self.credOther.captureSpacebarOrEnter = true;
        var onlyMdElt = q$('onlyMDFlagForJavascript');
        if (!onlyMdElt) {
            self.credDO.captureSpacebarOrEnter = true;
            self.credPA.captureSpacebarOrEnter = true;
            self.credNP.captureSpacebarOrEnter = true;
        }
        self.joinQuantia.captureSpacebarOrEnter = true;
        /*Add the onlyPwd registration paeg elements*/
        self.onlyPwdRegistrationEmail = q$('onlyPwdRegistrationUsersEmail');
        self.onlyPwdRegistrationEmail.valfun = function () {
            return RegDlgEltsBase.validateEmailRegex(self.onlyPwdRegistrationEmail);
        };
        self.onlyPwdRegistrationPassword = q$('onlyPwdRegistrationUsersPassword');
        self.onlyPwdRegistrationPassword.valfun = function () {
            return self.validatePassword(self.onlyPwdRegistrationPassword);
        };
        self.onlyPwdJoinQuantiaButton = q$('onlyPwdJoinQuantia');
        self.onlyPwdLoginButton = q$('signInButton3');
        /* Add Login page elemets*/
        self.loginEmail = q$('loginEmail');
        self.loginEmail.valfun = function () {
            return self.validateName(self.loginEmail);
        };
        self.loginPassword = q$('loginPassword');
        self.loginButton = q$('signInButton2');
        /* Add reset password page   elemets*/
        self.resetPasswordEmail = q$('resetPasswordEmail');
        self.resetPasswordEmail.valfun = function () {
            return RegDlgEltsBase.validateEmailRegex(self.resetPasswordEmail);
        };
        self.resetPasswordButton = q$('resetPasswordButton');
        self.allElements = {
            'tabElements': [
                self.firstName,
                self.lastName,
                self.credMD,
                self.credDO,
                self.credPA,
                self.credNP,
                self.credOther,
                self.credentials,
                self.specialty,
                self.countryOfPractice,
                self.officeZip,
                self.usersEmail,
                self.usersPassword,
                self.confirmPassword,
                self.joinQuantia,
                self.loginButtonOnRegPage,
                self.onlyPwdRegistrationEmail,
                self.onlyPwdRegistrationPassword,
                self.onlyPwdJoinQuantiaButton,
                self.onlyPwdLoginButton,
                self.loginEmail,
                self.loginPassword,
                self.loginButton,
                self.resetPasswordEmail,
                self.resetPasswordButton
            ],
            'registerPage_tabElements': [
                self.firstName,
                self.lastName,
                self.credMD,
                self.credDO,
                self.credPA,
                self.credNP,
                self.credOther,
                self.credentials,
                self.specialty,
                self.countryOfPractice,
                self.officeZip,
                self.usersEmail,
                self.usersPassword,
                self.confirmPassword,
                self.joinQuantia,
                self.loginButtonOnRegPage
            ],
            'passwordOnlyRegisterPage_tabElements': [
                self.onlyPwdRegistrationEmail,
                self.onlyPwdRegistrationPassword,
                self.onlyPwdJoinQuantiaButton,
                self.onlyPwdLoginButton
            ],
            'loginPage_tabElements': [
                self.loginEmail,
                self.loginPassword,
                self.loginButton
            ],
            'resetPasswordPage_tabElements': [
                self.resetPasswordEmail,
                self.resetPasswordButton
            ],
            'registerPage_submitButton': self.joinQuantia,
            'passwordOnlyRegisterPage_submitButton': self.onlyPwdJoinQuantiaButton,
            'loginPage_submitButton': self.loginButton,
            'resetPasswordPage_submitButton': self.resetPasswordButton,
            'loginButton': self.loginButton,
            'resetPasswordButton': self.resetPasswordButton
        };
        if (onlyMdElt) {
            var itemsToRemove = [self.credDO, self.credPA, self.credNP];
            itemsToRemove.each(function (item) {
                // remove from general tabElements list
                var itemIndex = self.allElements['tabElements'].indexOf(item);
                self.allElements['tabElements'].splice(itemIndex, 1);
                // remove from registerPage tabElements list
                itemIndex = self.allElements['registerPage_tabElements'].indexOf(item);
                self.allElements['registerPage_tabElements'].splice(itemIndex, 1);
            });
        }
    };
    return RegDlgEltsUnivStyle;
}(RegDlgElts2));
/**
 * ProfileRegDlgElts is used for Edit profile page screens
 */
var ProfileRegDlgElts = (function (_super) {
    __extends(ProfileRegDlgElts, _super);
    function ProfileRegDlgElts() {
        var _this = _super.call(this) || this;
        _this.initialize();
        return _this;
    }
    /**
     * returns the dialog container dom element
     * @returns {any}
     */
    ProfileRegDlgElts.prototype.getDialogContainer = function () {
        return this._dialogContainer;
    };
    /**
     * returns the close button dom element for the dialog
     * @returns {any}
     */
    ProfileRegDlgElts.prototype.getCloseButton = function () {
        return this._closeButton;
    };
    /**
     * returns the back button dom element for the dialog
     * @returns {any}
     */
    ProfileRegDlgElts.prototype.getBackButton = function () {
        return this._backButton;
    };
    /**
     * returns the body dom elementof the dialog
     * @returns {any}
     */
    ProfileRegDlgElts.prototype.getInnerDialog = function () {
        return this._innerDialog;
    };
    /**
     * return the background dom element for the dialog
     * @returns {any}
     */
    ProfileRegDlgElts.prototype.getDialogBackground = function () {
        return this._dialogBackground;
    };
    ProfileRegDlgElts.prototype.validateName = function (elem) {
        var val = elem.value.trim();
        var defaultText = elem.getAttribute("defaulttext") || null;
        if (!val || val == defaultText)
            return QSTR.required;
        if (RegDlgBase.containsBadCharacters(val))
            return QSTR.badChars;
        return null;
    };
    ProfileRegDlgElts.prototype.validatePassword = function (elem) {
        //do not use getValue here as it does a trim and we don't want to alter the password at all
        var defaultText = elem.getAttribute("defaulttext") || null;
        var password = elem.value;
        if (!password || password == defaultText)
            return QSTR.registerPasswordTooShort;
        if (password.length < RegDlgBase.MinPwdLen)
            return QSTR.registerPasswordTooShort;
        return null;
    };
    ProfileRegDlgElts.prototype.validateConfirmValue = function (elem1, elem2) {
        //do not use getValue here as it does a trim and we don't want to alter the field's value at all
        var confirmValue = elem2.value;
        var value = elem1.value;
        if (!value && !confirmValue) {
            return null;
        }
        if (value != confirmValue) {
            return QSTR.mismatch;
        }
        else {
            return null;
        }
    };
    // should be called by RegisterDialog.js or similar Registration regime.
    ProfileRegDlgElts.prototype.initialize = function () {
        var self = this;
        self._dialogContainer = q$('profileDialog');
        self._closeButton = self._dialogContainer.getElements('.closeButton');
        self._backButton = q$('dialogBackButton');
        self._innerDialog = q$('innerDialog');
        self._dialogBackground = q$('dialogBackground');
        /* Add changeUserName page elemets*/
        self.username = q$('username');
        self.username.valfun = function () {
            return RegDlgEltsBase.validateEmailRegex(self.username);
        };
        self.confirmUsername = q$('confirmUsername');
        self.confirmUsername.valfun = function () {
            return self.validateConfirmValue(self.username, self.confirmUsername);
        };
        self.changeUsernameButton = q$('changeUsernameButton');
        self.changeUsernameCancelButton = q$('changeUsernameCancelButton');
        /* Add changePassword page elemets*/
        self.password = q$('password');
        self.password.valfun = function () {
            return self.validatePassword(self.password);
        };
        self.confirmPassword = q$('confirmPassword');
        self.confirmPassword.valfun = function () {
            return self.validateConfirmValue(self.password, self.confirmPassword);
        };
        self.changePasswordButton = q$('changePasswordButton');
        self.changePasswordCancelButton = q$('changePasswordCancelButton');
        /* Add Do It For Me page elemets*/
        self.businessCity = q$('Business_City');
        self.businessState = q$('Business_State');
        self.currentInstitution = q$('Current_Institution_1');
        self.meId = q$('MEID');
        self.notes = q$('Notes');
        self.doItForMeSubmitButton = q$('doItForMeButton');
        self.doItForMeCancelButton = q$('doItForMeCancelButton');
        self.allElements = {
            'tabElements': [
                self.username,
                self.confirmUsername,
                self.changeUsernameButton,
                self.changeUsernameCancelButton,
                self.password,
                self.confirmPassword,
                self.changePasswordButton,
                self.changePasswordCancelButton,
                self.businessCity,
                self.businessState,
                self.currentInstitution,
                self.meId,
                self.notes,
                self.doItForMeSubmitButton,
                self.doItForMeCancelButton
            ],
            'changeUserNamePage_tabElements': [
                self.username,
                self.confirmUsername,
                self.changeUsernameButton,
                self.changeUsernameCancelButton
            ],
            'changePasswordPage_tabElements': [
                self.password,
                self.confirmPassword,
                self.changePasswordButton,
                self.changePasswordCancelButton
            ],
            'doItForMePage_tabElements': [
                self.businessCity,
                self.businessState,
                self.currentInstitution,
                self.meId,
                self.notes,
                self.doItForMeSubmitButton,
                self.doItForMeCancelButton
            ]
        };
    };
    return ProfileRegDlgElts;
}(RegDlgElts2));




// AccountUtil.js

//xnclude "AccountInfoBase.js"
/// <reference path="XML.ts"/>
var AccountUtil = (function () {
    function AccountUtil() {
    }
    AccountUtil.docFromProps = function (props) {
        var i;
        var xmlDoc = XML.CreateDocument("<createUser></createUser>");
        var cuElt = xmlDoc.documentElement;
        var element;
        XML.addXmlChild(cuElt, xmlDoc, "firstName", props.firstName);
        XML.addXmlChild(cuElt, xmlDoc, "lastName", props.lastName);
        XML.addXmlChild(cuElt, xmlDoc, "suffix", props.suffix);
        XML.addXmlChild(cuElt, xmlDoc, "credentials", props.credentials);
        XML.addXmlChild(cuElt, xmlDoc, "email", props.email);
        XML.addXmlChild(cuElt, xmlDoc, "password", props.password);
        XML.addXmlChild(cuElt, xmlDoc, "faxnumber", props.faxnumber);
        XML.addXmlChild(cuElt, xmlDoc, "officeZip", props.officeZip);
        XML.addXmlChild(cuElt, xmlDoc, "locale", props.locale);
        XML.addXmlChild(cuElt, xmlDoc, "partner", props.partner);
        XML.addXmlChild(cuElt, xmlDoc, "signupDFID", props.signupDFID);
        XML.addXmlChild(cuElt, xmlDoc, "signupURI", props.signupURI);
        XML.addXmlChild(cuElt, xmlDoc, "signupChallengeScreen", props.signupChallengeScreen);
        XML.addXmlChild(cuElt, xmlDoc, "signupReferrer", props.signupReferrer);
        XML.addXmlChild(cuElt, xmlDoc, "signupReferFromURL", props.signupReferFromURL);
        XML.addXmlChild(cuElt, xmlDoc, "marketingCampaignCode", props.marketingCampaignCode);
        XML.addXmlChild(cuElt, xmlDoc, "country", props.country);
        XML.addXmlChild(cuElt, xmlDoc, "primary_language", props.primaryLanguage);
        if ((props.languages) && (props.languages.length != 0)) {
            element = xmlDoc.createElement("languages");
            for (i = 0; i < props.languages.length; ++i) {
                var lang = xmlDoc.createElement("language");
                lang.appendChild(XML.CreateTextNode(xmlDoc, props.languages[i]));
                element.appendChild(lang);
            }
            cuElt.appendChild(element);
        }
        if (props.allowContact) {
            cuElt.setAttribute("contactOptIn", "true");
        }
        if (props.specialties) {
            element = xmlDoc.createElement("specialties");
            for (i = 0; i < props.specialties.length; ++i) {
                var spec = xmlDoc.createElement("specialty");
                spec.appendChild(XML.CreateTextNode(xmlDoc, props.specialties[i]));
                element.appendChild(spec);
            }
            cuElt.appendChild(element);
        }
        var regid = readCookie("joinquantiamd");
        if (!regid)
            regid = props.userEnteredRegId;
        XML.addXmlChild(cuElt, xmlDoc, "regid", regid);
        var trackingid = readCookie("com.quantia.session");
        XML.addXmlChild(cuElt, xmlDoc, "trackingid", trackingid);
        return xmlDoc;
    };
    AccountUtil.pwdOnlyDocFromProps = function (props) {
        var xmlDoc = XML.CreateDocument("<createUserPwdOnly></createUserPwdOnly>");
        var cuElt = xmlDoc.documentElement;
        XML.addXmlChild(cuElt, xmlDoc, "email", props.email);
        XML.addXmlChild(cuElt, xmlDoc, "password", props.password);
        XML.addXmlChild(cuElt, xmlDoc, "partner", props.partner);
        XML.addXmlChild(cuElt, xmlDoc, "signupDFID", props.signupDFID);
        XML.addXmlChild(cuElt, xmlDoc, "signupURI", props.signupURI);
        XML.addXmlChild(cuElt, xmlDoc, "signupChallengeScreen", props.signupChallengeScreen);
        XML.addXmlChild(cuElt, xmlDoc, "signupReferrer", props.signupReferrer);
        XML.addXmlChild(cuElt, xmlDoc, "signupReferFromURL", props.signupReferFromURL);
        XML.addXmlChild(cuElt, xmlDoc, "marketingCampaignCode", props.marketingCampaignCode);
        XML.addXmlChild(cuElt, xmlDoc, "regid", props.regid);
        var trackingid = readCookie("com.quantia.session");
        XML.addXmlChild(cuElt, xmlDoc, "trackingid", trackingid);
        return xmlDoc;
    };
    AccountUtil.CreateNewAccount = function (onSuccess, onFailure, props) {
        var xmlDoc = AccountUtil.docFromProps(props);
        AccountUtil.__createNewAccount(onSuccess, onFailure, "createuser", xmlDoc);
    };
    AccountUtil.CreateNewAccountPwdOnly = function (onSuccess, onFailure, props) {
        var xmlDoc = AccountUtil.pwdOnlyDocFromProps(props);
        AccountUtil.__createNewAccount(onSuccess, onFailure, "createuserpwdonly", xmlDoc);
    };
    AccountUtil.__createNewAccount = function (onSuccess, onFailure, whichcmd, xmlDoc) {
        var cmd = QSettings.buildUrlCmd(whichcmd);
        Ajax.postAsXml(cmd, xmlDoc, function (results) {
            var resultDocument = XML.CreateDocument(results);
            if (resultDocument.documentElement.getAttribute("status") == "success") {
                Common.addDataLayerEvent({ 'event': 'registerSuccess' });
                onSuccess(XML.findAndFillValue(resultDocument, "username"));
            }
            else {
                Common.addDataLayerEvent({ 'event': 'registerFails' });
                onFailure(XML.findAndFillValue(resultDocument, "errorMessage"));
            }
        }, function (errorMessage) {
            onFailure(errorMessage);
        });
    };
    return AccountUtil;
}());

//include "AccountInfoBase.js"



// RegDlgMultiPage.js

///<reference path="Ajax.d.ts"/>
/// <reference path="mootools.d.ts" />
/// <reference path="CommonWeb.ts" />
/// <reference path="RegDlgBase.ts" />
/// <reference path="AccountUtil.ts" />
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var RegDlgMultiPage = (function (_super) {
    __extends(RegDlgMultiPage, _super);
    function RegDlgMultiPage(afterLoginUrl, defVals) {
        var _this = _super.call(this, defVals) || this;
        _this.isElementFocusable = function (element) {
            var isFocusable = true;
            if (element.hasClass('disabledButton')) {
                isFocusable = false;
            }
            else if (element.hasClass('hiddenDialog')) {
                isFocusable = false;
            }
            else if (element.hasClass('cHidden')) {
                isFocusable = false;
            }
            return isFocusable;
        };
        _this._submitted = false;
        _this._allPageIds = [
            'registerPage',
            'reLoginPage',
            'alreadyRegisteredErrorPage',
            'forgotPasswordPage',
            'successPage'
        ];
        _this._eventsHaveBeenAdded = false;
        _this._postRegistrationCallback = _this.loginAfterRegister.bind(_this);
        _this._afterLoginUrl = afterLoginUrl;
        _this._lastAttempted = 0;
        return _this;
    }
    // subclasses may override
    RegDlgMultiPage.prototype.initPage = function () {
        this._dlgElts = new RegDlgElts2();
        this.handleResize();
        this.resetAllFields(false);
        this.addEvents();
    };
    // subclasses may override
    RegDlgMultiPage.prototype.handleResize = function () {
        DialogUtils.handleDialogResize(q$('innerDialog'), q$('dialogBackground'));
    };
    RegDlgMultiPage.prototype.personalizeTitle = function (shouldClearRegid) {
        var gTitle = q$('generalTitle');
        if (!(gTitle))
            return;
        var pTitle = q$('personalizedTitle');
        if (this._defaultValues.firstName) {
            q$('welcomeUser').innerHTML = sprintf(QSTR.welcomeUser, this._defaultValues.firstName, this._defaultValues.lastName);
            q$('confirmUser').innerHTML = sprintf(QSTR.notYou, this._defaultValues.firstName) +
                '<a href="#" onclick="Pageparams.registerDialog.notMe();">' +
                QSTR.clickHere + '</a>';
            Common.cshow(pTitle);
            Common.chide(gTitle);
        }
        else {
            if (shouldClearRegid) {
                createCookie('joinquantiamd', '', -1);
            }
            Common.chide(pTitle);
            Common.cshow(gTitle);
        }
    };
    RegDlgMultiPage.prototype.resetAllFields = function (shouldClearRegid) {
        var i, o;
        var credOuterDiv = q$('registrationCredentialsOtherOuterDiv');
        credOuterDiv.addClass('hiddenDialog');
        this.personalizeTitle(shouldClearRegid);
        if (this._selectedCredential) {
            this._selectedCredential.removeClass('selected');
        }
        // protect against call made before _dlgElts are created
        if (!this._dlgElts)
            return;
        var tempThis = this;
        this._dlgElts.allElements.tabElements.each(function (item) {
            if (item.value) {
                item.value = '';
            }
            tempThis.clearError(item, false);
        });
        var elem;
        for (elem in this._defaultValues) {
            if (this._defaultValues.hasOwnProperty(elem)) {
                var tmpDlgElt = this._dlgElts[elem];
                if (tmpDlgElt)
                    tmpDlgElt.value = this._defaultValues[elem];
            }
        }
        var co = this._defaultValues.countryOfPractice;
        if (typeof co == "undefined" || co == '') {
            co = q$('defaultCountry').value;
        }
        if (typeof co !== "undefined" && co != '') {
            for (i = 0; i < this._dlgElts.countryOfPractice.options.length; ++i) {
                o = this._dlgElts.countryOfPractice.options[i].value;
                if (o == co) {
                    this._dlgElts.countryOfPractice.selectedIndex = i;
                    q$('registrationCountry').value = co;
                    break;
                }
            }
        }
        this._dlgElts.specialty.selectedIndex = 0;
        var rs = this._defaultValues.specialty;
        if (rs != '') {
            for (i = 0; i < this._dlgElts.specialty.options.length; ++i) {
                o = this._dlgElts.specialty.options[i].value;
                if (o == rs) {
                    this._dlgElts.specialty.selectedIndex = i;
                    break;
                }
            }
        }
        var rc = this._defaultValues.credentials;
        if (typeof rc != 'undefined' && rc != '') {
            if (rc == 'MD')
                this._selectedCredential = this._dlgElts.credMD;
            else if (rc == 'DO')
                this._selectedCredential = this._dlgElts.credDO;
            else if (rc == 'PA')
                this._selectedCredential = this._dlgElts.credPA;
            else if (rc == 'NP')
                this._selectedCredential = this._dlgElts.credNP;
            else {
                this._selectedCredential = this._dlgElts.credOther;
                this._dlgElts.credentials.value = rc;
                this._dlgElts.credentials.removeClass('hiddenDialog');
                credOuterDiv.removeClass('hiddenDialog');
            }
            this._selectedCredential.addClass('selected');
        }
        this._dlgElts.optInAgreeToTerms.checked = true;
    };
    RegDlgMultiPage.prototype.setCurrentItemAndFocus = function (item) {
        this.setCurrentItem(item);
        try {
            item.focus();
        }
        catch (e) { }
    };
    RegDlgMultiPage.prototype.setCurrentItem = function (item) {
        $$('.hasFocus').removeClass('hasFocus');
        q$('checkBoxContainer').toggleClass('highlight', (item.id == 'registrationOptInAgreeToTerms'));
        this._currentItem = item;
        this._currentItem.addClass('hasFocus');
        $$('.trackFocusEvents').each(function (item) {
            item.removeClass('childElementHasFocus');
            item.addClass('childElementDoesNotHaveFocus');
        });
        var rents = this._currentItem.getParents('.trackFocusEvents');
        rents.each(function (item) {
            item.addClass('childElementHasFocus');
            item.removeClass('childElementDoesNotHaveFocus');
        });
    };
    RegDlgMultiPage.prototype.onCredentialsClick = function (evt) {
        // convert credentials to MD from registrationCredentialsMD
        // when called from space key, evt is an element, otherwise it's a mootools event object
        var target = (evt.target) ? evt.target : evt;
        var cred = target.id.substring(RegDlgMultiPage._strRegistrationCredentials.length);
        // var nextElementToFocus = RegDlgElts.specialty;
        var credElem = this._dlgElts.credentials;
        if (cred == 'Other') {
            this._dlgElts.credentials.removeClass('hiddenDialog');
            q$('registrationCredentialsOtherOuterDiv').removeClass('hiddenDialog');
            credElem.value = '';
            // nextElementToFocus = RegDlgElts.credentials;
        }
        else {
            q$('registrationCredentialsOtherOuterDiv').addClass('hiddenDialog');
            this._dlgElts.credentials.addClass('hiddenDialog');
            credElem.value = cred;
        }
        // finally, record current selection
        if (this._selectedCredential) {
            this._selectedCredential.removeClass('selected');
        }
        target.addClass('selected');
        this._selectedCredential = target;
        this.clearError(q$('registrationCredentials'), false);
        return false;
    };
    RegDlgMultiPage.prototype.onFocus = function (evt) {
        this.clearError(evt.target, false);
    };
    RegDlgMultiPage.prototype.createUpdateCurrentItem = function (item) {
        var tempThis = this;
        return function () {
            tempThis.setCurrentItem(item);
        };
    };
    RegDlgMultiPage.prototype.manageTabOrEnterKeyDown = function (keyDownEvent) {
        if (keyDownEvent.key == 'tab') {
            var pageTabElements = this._dlgElts.allElements.tabElements;
            var currentIndex = pageTabElements.indexOf(this._currentItem);
            var nextIndex = this.getNextIndex(pageTabElements, keyDownEvent, currentIndex);
            while (!this.isElementFocusable(q$(pageTabElements[nextIndex].id))) {
                nextIndex = this.getNextIndex(pageTabElements, keyDownEvent, nextIndex);
            }
            this.setCurrentItemAndFocus(pageTabElements[nextIndex]);
            keyDownEvent.stop();
        }
        else if (keyDownEvent.key == 'enter') {
            var submitBtn = this._dlgElts.allElements.submitButton;
            submitBtn.fireEvent('click', submitBtn);
            keyDownEvent.stop();
        }
    };
    RegDlgMultiPage.prototype.manageSpaceKeyDown = function (keyDownEvent) {
        if (keyDownEvent.key == 'space') {
            var clickedElement = q$(keyDownEvent.target.id);
            if (clickedElement.captureSpacebarOrEnter) {
                clickedElement.fireEvent('click', clickedElement);
                keyDownEvent.stop();
            }
        }
    };
    RegDlgMultiPage.prototype.getNextIndex = function (page, event, index) {
        var nextIndex = (event.shift) ? index - 1 : index + 1;
        if (nextIndex < 0)
            nextIndex = page.length - 1;
        else if (nextIndex > page.length - 1)
            nextIndex = 0;
        return nextIndex;
    };
    RegDlgMultiPage.prototype.addEvents = function () {
        if (this._eventsHaveBeenAdded)
            return;
        this._eventsHaveBeenAdded = true;
        window.addEvent('resize', this.handleResize);
        $$('.closeButton').addEvent('click', this.hide.bind(this));
        this._dlgElts.joinQuantia.addEvent('click', this.register.bind(this));
        var tempThis = this;
        $$('#registerDialog input').forEach(function (elem) {
            elem.addEvent('focus', tempThis.onFocus.bind(tempThis));
        });
        $$('#registerDialog select').forEach(function (elem) {
            elem.addEvent('focus', tempThis.onFocus.bind(tempThis));
        });
        $$('#registerDialog .credentials').forEach(function (elem) {
            elem.addEvent('click', tempThis.onCredentialsClick.bind(tempThis));
            elem.addEvent('keydown', tempThis.manageSpaceKeyDown.bind(tempThis));
            //elem.addEvent('touchstart', tempThis.manageSpaceKeyDown.bind(tempThis));
        });
        var docBody = q$(document.body);
        docBody.addEvent('keydown', this.manageTabOrEnterKeyDown.bind(this));
        //docBody.addEvent('touchstart', this.manageTabOrEnterKeyDown.bind(this));
        this._dlgElts.allElements.tabElements.each(function (item) {
            if (!item.hasClass('credentials') &&
                !item.hasClass('smallRoundButton') &&
                !item.hasClass('blueButton')) {
                item.addEvent('click', tempThis.createUpdateCurrentItem(item));
            }
        });
    };
    RegDlgMultiPage.prototype.showPage = function (pageID) {
        if (pageID)
            q$(pageID).removeClass("hiddenDialog");
        for (var i = 0; i < this._allPageIds.length; i++) {
            var tmpID = this._allPageIds[i];
            if (tmpID != pageID)
                q$(tmpID).addClass("hiddenDialog");
        }
    };
    RegDlgMultiPage.prototype.showWithoutDefaults = function () {
        this.clearDefaults();
        this.show();
    };
    RegDlgMultiPage.prototype.show = function () {
        this.initPage();
        q$('registerDialog').removeClass('hiddenDialog');
        DialogUtils.removeBodyScrollBars();
        this.handleResize();
        this.setGlobalRegisterActive(true);
        // IE doesn't obey selected if the element is hidden or off the page, such as the registration overlay
        var defaultCountry = q$('defaultCountry').value;
        if (this._dlgElts.countryOfPractice.value == '') {
            this._dlgElts.countryOfPractice.set('value', defaultCountry);
            q$('registrationCountry').set('value', defaultCountry);
        }
        this.clearAllErrors();
        this.resetCursor();
    };
    RegDlgMultiPage.prototype.hide = function () {
        DialogUtils.restoreBodyScrollBars();
        q$('registerDialog').addClass('hiddenDialog');
        this.showPage('registerPage');
        window.removeEvent('resize', this.handleResize);
        this.setGlobalRegisterActive(false);
    };
    RegDlgMultiPage.prototype.resetCursor = function () {
        this.setCurrentItemAndFocus(this._dlgElts.allElements.tabElements[0]);
    };
    RegDlgMultiPage.prototype.determineSelectedSpecialties = function () {
        var specialties = [];
        var elem = this._dlgElts.specialty;
        if (elem) {
            var si = elem.selectedIndex;
            var value = elem.options[si].value;
            if (value) {
                specialties.push(value);
            }
        }
        return specialties;
    };
    RegDlgMultiPage.prototype.loginAfterRegister = function () {
        var self = this;
        setTimeout(function () {
            self.dologinAfterRegister(self._dlgElts.usersEmail, self._dlgElts.usersPassword);
        }, 1500);
    };
    RegDlgMultiPage.prototype.onSuccess = function () {
        this.clearSignupURI();
        // attempt to help google analytics track this
        try {
            pageTracker._trackPageview('/goal/registration.html');
        }
        catch (e) { }
        this.showPage('successPage');
        this.doAfterRegistration();
    };
    RegDlgMultiPage.prototype.localizeErrorMsg = function (inMsg) {
        var outMsg = inMsg;
        if (inMsg == "USER_EXISTS")
            outMsg = QSTR.registerAccountAlreadyExistsText;
        else if (inMsg == "USERNAME_IN_USE")
            outMsg = QSTR.registerAccountAlreadyExistsPasswordIncorrectText;
        else if (inMsg == "USER_NOT_VALID_FOR_THIS_DOMAIN")
            outMsg = QSTR.emailNotValidForDomain;
        else if (inMsg == 'INVALID_EMAIL')
            outMsg = QSTR.invalidEmailAddress;
        else if (inMsg == 'ACCOUNT_DISABLED')
            outMsg = inMsg;
        else
            outMsg = sprintf(QSTR.errorCreatingAccount, inMsg);
        return (outMsg);
    };
    RegDlgMultiPage.prototype.onFailure = function (errorMessage) {
        this._submitted = false;
        var regUsersEmailElt = q$('registrationUsersEmail');
        if (errorMessage == 'INVALID_EMAIL') {
            this.setError(regUsersEmailElt, this.localizeErrorMsg(errorMessage));
            return;
        }
        var nextPage = (errorMessage == 'ACCOUNT_DISABLED') ? 'alreadyRegisteredErrorPage' : 'reLoginPage';
        this._dlgElts.joinQuantiaButtonLabel.set('html', QSTR.joinQuantiaMD);
        this.showPage(nextPage);
        q$('emailAddressPage2').innerHTML = regUsersEmailElt.value;
        this.setCurrentItemAndFocus(q$('registrationUsersPassword1'));
    };
    RegDlgMultiPage.prototype.checkForErrors = function () {
        var tempThis = this; // .each() iterator establishes a new 'this', so use tempThis
        this._dlgElts.allElements.tabElements.each(function (elem) {
            var errstr = (elem.valfun) ? elem.valfun() : null;
            if (errstr)
                tempThis.setError(elem, errstr);
            else
                tempThis.clearError(elem, true);
        });
    };
    RegDlgMultiPage.prototype.register = function () {
        var now = (new Date()).getTime();
        if (now - this._lastAttempted < 2000)
            return;
        this._lastAttempted = now;
        this.checkForErrors();
        if (!this.areErrors()) {
            this._submitted = true;
            this._dlgElts.joinQuantiaButtonLabel.set('html', QSTR.submittingWithElipsis);
            var dfId = RegDlgBase.finddfid();
            var signupURI = RegDlgBase.getSignupURI();
            var signupReferFromURL = this._referrer;
            var signupChallengeScreen = RegDlgBase.getSignupChallengeScreen();
            var mcc = gQCredentials.GetMarketingCampaignCode();
            if (mcc) {
                gQCredentials.AddDfIdToMarketingCode(dfId);
            }
            var effPartnerCodes = (AccountInfo.DevicePartnerCode) ?
                AccountInfo.DevicePartnerCode + ";" + gQCredentials.GetPartner() :
                gQCredentials.GetPartner();
            var accountObject_1 = {
                partner: effPartnerCodes,
                marketingCampaignCode: mcc,
                allowContact: true,
                signupDFID: dfId,
                signupReferrer: signupReferFromURL,
                signupReferFromURL: signupReferFromURL,
                signupURI: signupURI,
                signupChallengeScreen: signupChallengeScreen,
                specialties: this.determineSelectedSpecialties(),
                primaryLanguage: AccountInfo.PrimaryLanguage,
                languages: AccountInfo.Languages
            };
            $$('#registerDialog input').forEach(function (elem) {
                var key = elem.id;
                // change registrationFirstName to firstName, etc
                if (key.search(/^registration/) != -1) {
                    key = key.substring(12, 13).toLowerCase() + key.substring(13);
                }
                // change usersEmail to email, etc
                if (key.match(/^users/)) {
                    key = key.substring(5).toLowerCase();
                }
                accountObject_1[key] = elem.value;
            });
            Common.addDataLayerEvent({ 'event': 'registerClick' });
            AccountUtil.CreateNewAccount(this.onSuccess.bind(this), this.onFailure.bind(this), accountObject_1);
        }
        this.setGlobalRegisterActive(false);
    };
    RegDlgMultiPage.prototype.login = function () {
        var pwElt = q$('registrationUsersPassword1');
        if (pwElt.value == "")
            return;
        var emval = this._dlgElts.usersEmail.value.trim();
        var pwval = pwElt.value;
        gQCredentials.AttemptLogin(emval, pwval, this.loginCallback.bind(this));
    };
    RegDlgMultiPage.prototype.loginCallback = function (result, message) {
        if (!result) {
            alert(message);
            return;
        }
        Pageparams.exitCondition = "login";
        createCookie("resumeAfterLogin", 'true', Common.ONE_MINUTE_IN_DAYS);
        Common.attemptWindowQuit();
        var loc = window.location.href;
        var u = queryString("user");
        if (u != null) {
            // FIXME:  when does this happen?
            loc = loc.replace("user=" + queryString("user"), "");
            window.location.href = loc;
        }
        else {
            if (!this._afterLoginUrl)
                Common.quickReload();
            else
                window.location.href = this._afterLoginUrl;
        }
    };
    RegDlgMultiPage.prototype.forgotPasswordSubmit = function () {
        var emailElt = q$('registrationUsersEmail');
        var emailAddress = emailElt.value.trim();
        if (emailAddress == '')
            return;
        var tempThis = this;
        function showForgetPasswordPage() {
            tempThis.showPage('forgotPasswordPage');
            q$('emailAddressPage3').innerHTML = emailElt.value.trim();
        }
        setTimeout(function () {
            RegDlgBase.requestPassword(emailAddress, showForgetPasswordPage, null);
        }, 200);
    };
    RegDlgMultiPage.prototype.notMe = function () {
        this._defaultValues = {
            firstName: "",
            lastName: "",
            officeZip: "",
            countryOfPractice: "",
            specialty: "",
            credentials: ""
        };
        this.resetAllFields(true);
    };
    RegDlgMultiPage.prototype.areErrors = function () {
        return (this._errors.length > 0);
    };
    RegDlgMultiPage.prototype.setError = function (elem, msg) {
        var status = this.getErrorFieldForElem(elem);
        status.removeClass('okField');
        status.innerHTML = '<div class="notch"> </div><div class="rounded">' + msg + '</div>';
        this.addErrorData(elem);
    };
    RegDlgMultiPage.prototype.addErrorData = function (element) {
        if (this._errors.indexOf(element.id) == -1) {
            this._errors.push(element.id);
        }
    };
    RegDlgMultiPage.prototype.clearError = function (elem, isValidated) {
        elem.removeClass('hasError');
        var status = this.getErrorFieldForElem(elem);
        if (status) {
            if (isValidated)
                status.addClass('okField');
            status.innerHTML = '';
        }
        var id = elem.id;
        var index = this._errors.indexOf(id);
        if (index > -1) {
            this._errors.splice(index, 1);
        }
    };
    RegDlgMultiPage.prototype.getErrorFieldForElem = function (elem) {
        return q$(elem.id + "Error");
    };
    RegDlgMultiPage.prototype.emailValidatedCallback = function (ok) {
        var elem = this._dlgElts.usersEmail;
        if (!ok)
            this.setError(elem, QSTR.enterValidEmail);
        else
            this.clearError(elem, true);
    };
    // part of div ID=?
    RegDlgMultiPage._strRegistrationCredentials = 'registrationCredentials';
    return RegDlgMultiPage;
}(RegDlgBase));




// RegDlgMultiPageUnivStyle.js

///<reference path="Ajax.d.ts"/>
/// <reference path="mootools.d.ts" />
/// <reference path="CommonWeb.ts" />
/// <reference path="RegDlgBase.ts" />
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var RegDlgMultiPageUnivStyle = (function (_super) {
    __extends(RegDlgMultiPageUnivStyle, _super);
    function RegDlgMultiPageUnivStyle(afterLoginUrl, defVals) {
        var _this = _super.call(this, defVals) || this;
        _this._doNotClear = false; //if set to true the dialog could not be cleared
        _this.isElementFocusable = function (element) {
            var isFocusable = true;
            if (element.hasClass('disabledButton')) {
                isFocusable = false;
            }
            else if (element.hasClass('hiddenDialog')) {
                isFocusable = false;
            }
            else if (element.hasClass('cHidden')) {
                isFocusable = false;
            }
            return isFocusable;
        };
        // FIXME:
        _this._registerOnPageEltName = 'registerOnPage';
        _this._mainEltName = 'registerDialog';
        _this._submitted = false;
        _this._allPageIds = [
            'registerPage',
            'passwordOnlyRegisterPage',
            'loginPage',
            'resetPasswordPage',
            'reLoginPage',
            'alreadyRegisteredErrorPage',
            'forgotPasswordPage',
            'successPage'
        ];
        _this._eventsHaveBeenAdded = false;
        _this._postRegistrationCallback = _this.loginAfterRegister.bind(_this);
        _this._afterLoginUrl = afterLoginUrl ? afterLoginUrl : null; // we dont't allow empty string=> In case afterLoginUrl is an empty string then we set a null value for it
        _this._lastAttempted = 0;
        _this._currentPageId = null;
        _this._previousPageIds = [];
        doOnPageReady(_this.onInit.bind(_this));
        return _this;
    }
    /**
     * Initialization callback
     * Should be overwritten  if custom behaviour is needed
     * @returns {boolean}
     */
    RegDlgMultiPageUnivStyle.prototype.onInit = function () {
        /* if (this.hasOnlyPwdRegId())
             this.showOnlyPasswordRegistrationPage.bind(this);
         */
        var self = this;
        setTimeout(function () {
            if (self.shouldAutoLaunch()) {
                self.show();
            }
        }, 50);
    };
    /**
     * returns the back button dom element for the dialog
     * @returns {any}
     */
    RegDlgMultiPageUnivStyle.prototype.getBackButton = function () {
        var btn = null;
        if (this._dlgElts) {
            btn = this._dlgElts.getBackButton();
        }
        if (!btn) {
            btn = q$('registerDialogBackButton'); // Safer in case this._dlgElts is not initialized yet
        }
        return btn;
    };
    /**
     * Deny clearing the dialog
     * @param doNotClear
     */
    RegDlgMultiPageUnivStyle.prototype.setDoNotClear = function (doNotClear) {
        this._doNotClear = doNotClear;
        this.updateBackButton();
    };
    /**
     * Hide or show the back button
     * @param hide
     */
    RegDlgMultiPageUnivStyle.prototype.hideBackButton = function (hide) {
        var btn = this.getBackButton();
        if (!btn)
            return;
        Common.cShowOrHide(btn, !hide);
    };
    /**
     * Allows to show either the close button or the go back button
     * @param {boolean} showClose if true the close button is shown, Go back otherwise
     */
    RegDlgMultiPageUnivStyle.prototype.showCloseOrGoBack = function (showClose) {
        var btn = this.getBackButton();
        if (!btn)
            return;
        btn.removeClass('cHidden');
    };
    /**
     * Updates the display of GoBakc and  Close button
     *   - If there is  no previous page and do not clear is set to true then the button is hidden
     *   - If there is no previous page and do not close is set to false the the close button is shown
     *   - if there is previous page then the go back button is shown
     */
    RegDlgMultiPageUnivStyle.prototype.updateBackButton = function () {
        var btn = this.getBackButton();
        if (!btn)
            return;
        if (this._previousPageIds.length == 0) {
            if (this._doNotClear) {
                this.hideBackButton(true);
            }
            else {
                this.hideBackButton(false);
                this.showCloseOrGoBack(true);
            }
        }
        else {
            this.hideBackButton(false);
            this.showCloseOrGoBack(false);
        }
    };
    /* Returns true if there is a known only password registration rgid (rgid=8__) */
    RegDlgMultiPageUnivStyle.prototype.hasOnlyPwdRegId = function () {
        return this._regid && this._regid.search(/^8/) == 0;
    };
    /* Returns true if there is a known auto registration rgid (rgid=7__)    */
    RegDlgMultiPageUnivStyle.prototype.hasAutoRegId = function () {
        return this._regid && this._regid.search(/^7/) == 0;
    };
    /*  Returns true if there is a known auto-login  rgid (rgid=5__) */
    RegDlgMultiPageUnivStyle.prototype.hasAutoLoginRegId = function () {
        return this._regid && this._regid.search(/^5/) == 0;
    };
    // subclasses may override
    RegDlgMultiPageUnivStyle.prototype.initPage = function () {
        // show container that contains all possible regDlg forms.
        Common.cshow(this._registerOnPageEltName);
        this._dlgElts = new RegDlgEltsUnivStyle();
        this.handleResize();
        this.resetAllFields(false);
        this.addEvents();
    };
    // subclasses may override
    RegDlgMultiPageUnivStyle.prototype.handleResize = function () {
        var innerDialog = q$('innerDialog');
        var bg = q$('dialogBackground');
        DialogUtils.handleDialogResize(innerDialog, bg);
    };
    RegDlgMultiPageUnivStyle.prototype.personalizeTitle = function (shouldClearRegid) {
        var gTitle = q$('generalTitle');
        if (!(gTitle))
            return;
        var pTitle = q$('personalizedTitle');
        if (this._defaultValues.firstName) {
            q$('welcomeUser').innerHTML = sprintf(QSTR.welcomeUser, this._defaultValues.firstName, this._defaultValues.lastName);
            q$('confirmUser').innerHTML = sprintf(QSTR.notYou, this._defaultValues.firstName) +
                '<a href="#" onclick="Pageparams.registerDialog.notMe();">' +
                QSTR.clickHere + '</a>';
            Common.cshow(pTitle);
            Common.chide(gTitle);
        }
        else {
            if (shouldClearRegid) {
                createCookie('joinquantiamd', '', -1);
            }
            Common.chide(pTitle);
            Common.cshow(gTitle);
        }
    };
    RegDlgMultiPageUnivStyle.prototype.resetAllFields = function (shouldClearRegid) {
        var i, o;
        this.personalizeTitle(shouldClearRegid);
        // protect against call made before _dlgElts are created
        if (!this._dlgElts)
            return;
        var tempThis = this;
        this._dlgElts.allElements.tabElements.each(function (item) {
            if (item) {
                tempThis.clearError(item, false);
            }
        });
        var elem;
        for (elem in this._defaultValues) {
            if (this._defaultValues.hasOwnProperty(elem)) {
                var tmpDlgElt = this._dlgElts[elem];
                if (tmpDlgElt && this._defaultValues[elem])
                    tmpDlgElt.value = this._defaultValues[elem];
            }
        }
        var co = this._defaultValues.countryOfPractice;
        if (typeof co == "undefined" || co == '') {
            co = q$('defaultCountry').value;
        }
        if (this._dlgElts.countryOfPractice.selectedIndex <= 0) {
            /* When there is no country selected yet then put the default country */
            if (typeof co !== "undefined" && co != '') {
                for (i = 0; i < this._dlgElts.countryOfPractice.options.length; ++i) {
                    o = this._dlgElts.countryOfPractice.options[i].value;
                    if (o == co) {
                        this._dlgElts.countryOfPractice.selectedIndex = i;
                        q$('registrationCountry').value = co;
                        break;
                    }
                }
            }
        }
        /* Browser should keep the selected value for when eventually the user returns
           this._dlgElts.specialty.selectedIndex = 0;
        */
        var rs = this._defaultValues.specialty;
        if (this._dlgElts.specialty.selectedIndex <= 0) {
            if (this._dlgElts.specialty.selectedIndex < 0) {
                // put at least the indication text
                this._dlgElts.specialty.selectedIndex = 0;
            }
            /* When there is no speciality  selected yet  then put the default speciality if defined */
            if (rs != '') {
                for (i = 0; i < this._dlgElts.specialty.options.length; ++i) {
                    o = this._dlgElts.specialty.options[i].value;
                    if (o == rs) {
                        this._dlgElts.specialty.selectedIndex = i;
                        break;
                    }
                }
            }
        }
        var credOuterDiv = q$('registrationCredentialsOtherOuterDiv');
        if (this._selectedCredential) {
            if (this._selectedCredential != this._dlgElts.credOther) {
                credOuterDiv.addClass('hiddenDialog');
            }
            /* Browser should keep the selected value for when eventually the user returns
             this._selectedCredential.removeClass('selected');
             */
        }
        var rc = this._defaultValues.credentials;
        if (!this._selectedCredential && typeof rc != 'undefined' && rc != '') {
            /*   in case  no credentials are selected then put the default values if defined */
            if (rc == 'MD')
                this._selectedCredential = this._dlgElts.credMD;
            else if (rc == 'DO')
                this._selectedCredential = this._dlgElts.credDO;
            else if (rc == 'PA')
                this._selectedCredential = this._dlgElts.credPA;
            else if (rc == 'NP')
                this._selectedCredential = this._dlgElts.credNP;
            else {
                this._selectedCredential = this._dlgElts.credOther;
                this._dlgElts.credentials.value = rc;
                this._dlgElts.credentials.removeClass('hiddenDialog');
                credOuterDiv.removeClass('hiddenDialog');
            }
            this._selectedCredential.addClass('selected');
        }
    };
    RegDlgMultiPageUnivStyle.prototype.setCurrentItemAndFocus = function (item, focus) {
        this.setCurrentItem(item);
        if (focus) {
            try {
                item.focus();
            }
            catch (e) { }
        }
    };
    RegDlgMultiPageUnivStyle.prototype.setCurrentItem = function (item) {
        $$('.hasFocus').removeClass('hasFocus');
        this._currentItem = item;
        this._currentItem.addClass('hasFocus');
        $$('.trackFocusEvents').each(function (item) {
            item.removeClass('childElementHasFocus');
            item.addClass('childElementDoesNotHaveFocus');
        });
        var rents = this._currentItem.getParents('.trackFocusEvents');
        rents.each(function (item) {
            item.addClass('childElementHasFocus');
            item.removeClass('childElementDoesNotHaveFocus');
        });
    };
    RegDlgMultiPageUnivStyle.prototype.onCredentialsClick = function (evt) {
        // convert credentials to MD from registrationCredentialsMD
        // when called from space key, evt is an element, otherwise it's a mootools event object
        var target = (evt.target) ? evt.target : evt;
        var cred = target.id.substring(RegDlgMultiPageUnivStyle._strRegistrationCredentials.length);
        // var nextElementToFocus = RegDlgElts.specialty;
        var credElem = this._dlgElts.credentials;
        if (cred == 'Other') {
            this._dlgElts.credentials.removeClass('hiddenDialog');
            q$('registrationCredentialsOtherOuterDiv').removeClass('hiddenDialog');
            credElem.value = credElem.getAttribute('defaulttext') || '';
            // nextElementToFocus = RegDlgElts.credentials;
        }
        else {
            q$('registrationCredentialsOtherOuterDiv').addClass('hiddenDialog');
            this._dlgElts.credentials.addClass('hiddenDialog');
            credElem.value = cred;
        }
        // finally, record current selection
        if (this._selectedCredential) {
            this._selectedCredential.removeClass('selected');
        }
        target.addClass('selected');
        this._selectedCredential = target;
        this.clearError(q$('registrationCredentials'), false);
        return false;
    };
    RegDlgMultiPageUnivStyle.prototype.onFocus = function (evt) {
        this.clearError(evt.target, false);
    };
    RegDlgMultiPageUnivStyle.prototype.createUpdateCurrentItem = function (item) {
        var tempThis = this;
        return function () {
            tempThis.setCurrentItem(item);
        };
    };
    RegDlgMultiPageUnivStyle.prototype.manageTabOrEnterKeyDown = function (keyDownEvent) {
        if (keyDownEvent.key == 'tab') {
            var pageTabElements = this._dlgElts.allElements.tabElements;
            var currentIndex = pageTabElements.indexOf(this._currentItem);
            var nextIndex = this.getNextIndex(pageTabElements, keyDownEvent, currentIndex);
            while (!this.isElementFocusable(q$(pageTabElements[nextIndex].id))) {
                nextIndex = this.getNextIndex(pageTabElements, keyDownEvent, nextIndex);
            }
            this.setCurrentItemAndFocus(pageTabElements[nextIndex], true);
            keyDownEvent.stop();
        }
        else if (keyDownEvent.key == 'enter') {
            var submitBtn = this._dlgElts.allElements[this._currentPageId + '_submitButton'];
            submitBtn.fireEvent('click', submitBtn);
            keyDownEvent.stop();
        }
    };
    RegDlgMultiPageUnivStyle.prototype.manageSpaceKeyDown = function (keyDownEvent) {
        if (keyDownEvent.key == 'space') {
            var clickedElement = q$(keyDownEvent.target.id);
            if (clickedElement.captureSpacebarOrEnter) {
                clickedElement.fireEvent('click', clickedElement);
                keyDownEvent.stop();
            }
        }
    };
    RegDlgMultiPageUnivStyle.prototype.getNextIndex = function (page, event, index) {
        var nextIndex = (event.shift) ? index - 1 : index + 1;
        if (nextIndex < 0)
            nextIndex = page.length - 1;
        else if (nextIndex > page.length - 1)
            nextIndex = 0;
        return nextIndex;
    };
    RegDlgMultiPageUnivStyle.prototype.addEvents = function () {
        if (this._eventsHaveBeenAdded)
            return;
        this._eventsHaveBeenAdded = true;
        q$(this._mainEltName).addEvent('scroll', function (event) { Common.preventDefault(event); });
        window.addEvent('resize', this.handleResize);
        $$('.closeButton').addEvent('click', this.hide.bind(this));
        $$('.goBackBtn').addEvent('click', this.goBack.bind(this));
        this._dlgElts.joinQuantia.addEvent('click', this.register.bind(this));
        this._dlgElts.onlyPwdJoinQuantiaButton.addEvent('click', this.pwdOnlyRegister.bind(this));
        var tempThis = this;
        $$('#registerDialog input').forEach(function (elem) {
            elem.addEvent('focus', tempThis.onFocus.bind(tempThis));
        });
        $$('#registerDialog select').forEach(function (elem) {
            elem.addEvent('focus', tempThis.onFocus.bind(tempThis));
        });
        $$('#registerDialog .credentials').forEach(function (elem) {
            elem.addEvent('click', tempThis.onCredentialsClick.bind(tempThis));
            elem.addEvent('keydown', tempThis.manageSpaceKeyDown.bind(tempThis));
            //elem.addEvent('touchstart', tempThis.manageSpaceKeyDown.bind(tempThis));
        });
        /*Fix password input placeholder*/
        $$('.passwordPlaceHolder').forEach(function (elem) {
            elem.addEvent('focus', function () {
                elem.type = "password";
                try {
                    elem.click(); // fixes the issue of focus on input type change
                }
                catch (e) { }
            });
            elem.addEvent('blur', function () {
                var defaultText = elem.getAttribute('defaulttext') || '';
                if (!elem.value || elem.value == defaultText) {
                    elem.type = "text";
                }
            });
        });
        var docBody = q$(document.body);
        docBody.addEvent('keydown', this.manageTabOrEnterKeyDown.bind(this));
        //docBody.addEvent('touchstart', this.manageTabOrEnterKeyDown.bind(this));
        this._dlgElts.allElements.tabElements.each(function (item) {
            if (item && !item.hasClass('credentials') &&
                !item.hasClass('smallRoundButton') &&
                !item.hasClass('blueButton')) {
                item.addEvent('click', tempThis.createUpdateCurrentItem(item));
            }
        });
        /*Add login buttons actions*/
        this._dlgElts.loginButton.addEvent('click', function () {
            tempThis.checkForErrors();
            if (!tempThis.areErrors()) {
                var emval = tempThis._dlgElts.loginEmail.value.trim();
                var pwval = tempThis._dlgElts.loginPassword.value;
                gQCredentials.AttemptLogin(emval, pwval, tempThis.loginCallback.bind(tempThis));
            }
        });
        /*Add login buttons actions*/
        this._dlgElts.resetPasswordButton.addEvent('click', function () {
            tempThis.checkForErrors();
            if (!tempThis.areErrors()) {
                var emailAddress_1 = tempThis._dlgElts.resetPasswordEmail.value.trim();
                var showForgetPwFunc_1 = function () {
                    tempThis.goToPage('forgotPasswordPage');
                    q$('emailAddressPage3').innerHTML = emailAddress_1;
                };
                var showErrors_1 = function () {
                    tempThis.showPageErrorBlock(true, null);
                };
                setTimeout(function () {
                    RegDlgBase.requestPassword(emailAddress_1, showForgetPwFunc_1, showErrors_1);
                }, 200);
            }
        });
    };
    RegDlgMultiPageUnivStyle.prototype.showPage = function (pageID) {
        this.initPage();
        var dlgElt = q$(this._mainEltName);
        // try both cshow (class cHidden) and remove Class('hiddenDialog')
        Common.cshow(dlgElt);
        dlgElt.removeClass('hiddenDialog');
        this.goToPage(pageID);
        DialogUtils.removeBodyScrollBars();
        this.handleResize();
        this.setGlobalRegisterActive(true);
        this.clearAllErrors();
    };
    /**
     * When the dialog is already open, it allows to switch to another page
     * @param pageID
     */
    RegDlgMultiPageUnivStyle.prototype.goToPage = function (pageID) {
        if (this._currentPageId) {
            this._previousPageIds.push(this._currentPageId);
        }
        this.updateBackButton();
        this._currentPageId = pageID;
        if (pageID)
            q$(pageID).removeClass("hiddenDialog");
        for (var i = 0; i < this._allPageIds.length; i++) {
            var tmpID = this._allPageIds[i];
            if (tmpID != pageID)
                q$(tmpID).addClass("hiddenDialog");
        }
        this.resetCursor();
    };
    /**
     * Displays the registration page
     */
    RegDlgMultiPageUnivStyle.prototype.showRegistrationPage = function () {
        this.showPage('registerPage');
        // IE doesn't obey selected if the element is hidden or off the page, such as the registration overlay
        var defaultCountry = q$('defaultCountry').value;
        if (this._dlgElts.countryOfPractice.value == '') {
            this._dlgElts.countryOfPractice.set('value', defaultCountry);
            q$('registrationCountry').set('value', defaultCountry);
        }
    };
    /**
     * Displays the password only registration page
     */
    RegDlgMultiPageUnivStyle.prototype.showOnlyPasswordRegistrationPage = function () {
        this.showPage('passwordOnlyRegisterPage');
    };
    /**
     * Displays the login page
     */
    RegDlgMultiPageUnivStyle.prototype.showLoginPage = function () {
        this.showPage('loginPage');
    };
    /**
     * Displays the reset password  page
     */
    RegDlgMultiPageUnivStyle.prototype.showResetPasswordPage = function () {
        this.showPage('resetPasswordPage');
    };
    RegDlgMultiPageUnivStyle.prototype.showWithoutDefaults = function () {
        this.clearDefaults();
        this.show();
    };
    /**
     * Default display method : it displays the registration dialog page according to the current regid
     */
    RegDlgMultiPageUnivStyle.prototype.show = function () {
        if (this.hasOnlyPwdRegId())
            this.showOnlyPasswordRegistrationPage();
        else if (this.hasAutoRegId())
            this.showRegistrationPage();
        else if (this.hasAutoLoginRegId())
            this.showRegistrationPage();
        else
            this.showRegistrationPage();
    };
    RegDlgMultiPageUnivStyle.prototype.goBack = function () {
        var previousPageId = this._previousPageIds.pop();
        if (previousPageId) {
            this.updateBackButton();
            this._currentPageId = null; // this._currentPageId is set to null to avoid the previous page ids stack to go in loop
            this.goToPage(previousPageId);
            this.handleResize(); //
        }
        else {
            if (!this._doNotClear) {
                this.hide();
            }
        }
    };
    RegDlgMultiPageUnivStyle.prototype.hide = function () {
        DialogUtils.restoreBodyScrollBars();
        q$(this._mainEltName).addClass('hiddenDialog');
        this.goToPage('registerPage');
        window.removeEvent('resize', this.handleResize);
        this.setGlobalRegisterActive(false);
        this._currentPageId = null; // reset the current page id
        this._previousPageIds = [];
    };
    RegDlgMultiPageUnivStyle.prototype.resetCursor = function () {
        var currentPageElements = this._dlgElts.allElements[this._currentPageId + '_tabElements'];
        if (currentPageElements && currentPageElements.length > 0) {
            var firstElem = currentPageElements[0];
            if (firstElem) {
                this.setCurrentItemAndFocus(firstElem, false);
            }
        }
    };
    RegDlgMultiPageUnivStyle.prototype.determineSelectedSpecialties = function () {
        var specialties = [];
        var elem = this._dlgElts.specialty;
        if (elem) {
            var si = elem.selectedIndex;
            var value = elem.options[si].value;
            if (value) {
                specialties.push(value);
            }
        }
        return specialties;
    };
    RegDlgMultiPageUnivStyle.prototype.loginAfterRegister = function () {
        var self = this;
        setTimeout(function () {
            self.dologinAfterRegister(self._dlgElts.usersEmail, self._dlgElts.usersPassword);
        }, 1500);
    };
    /* onSuccess is called when the register request succeeds */
    RegDlgMultiPageUnivStyle.prototype.onSuccess = function () {
        this.clearSignupURI();
        // attempt to help google analytics track this
        try {
            pageTracker._trackPageview('/goal/registration.html');
        }
        catch (e) { }
        this.goToPage('successPage');
        this.doAfterRegistration();
    };
    RegDlgMultiPageUnivStyle.prototype.localizeErrorMsg = function (inMsg) {
        var outMsg = inMsg;
        if (inMsg == "USER_EXISTS")
            outMsg = QSTR.registerAccountAlreadyExistsText;
        else if (inMsg == "USERNAME_IN_USE")
            outMsg = QSTR.registerAccountAlreadyExistsPasswordIncorrectText;
        else if (inMsg == "USER_NOT_VALID_FOR_THIS_DOMAIN")
            outMsg = QSTR.emailNotValidForDomain;
        else if (inMsg == 'INVALID_EMAIL')
            outMsg = QSTR.invalidEmailAddress;
        else if (inMsg == 'ACCOUNT_DISABLED')
            outMsg = inMsg;
        else
            outMsg = sprintf(QSTR.errorCreatingAccount, inMsg);
        return (outMsg);
    };
    /**
     *  * onFailure ius called when the register requester fails
     * @param {string} errorMessage
     */
    RegDlgMultiPageUnivStyle.prototype.onFailure = function (errorMessage) {
        this._submitted = false;
        if (errorMessage == 'INVALID_EMAIL') {
            this.setError(this._dlgElts.usersEmail, this.localizeErrorMsg(errorMessage));
            return;
        }
        if (errorMessage == 'USER_EXISTS') {
            gQCredentials.AttemptLogin(this._dlgElts.usersEmail.value.trim(), this._dlgElts.usersPassword.value, this.loginCallback.bind(this));
            return;
        }
        var nextPage = (errorMessage == 'ACCOUNT_DISABLED') ? 'alreadyRegisteredErrorPage' : 'reLoginPage';
        this._dlgElts.joinQuantiaButtonLabel.set('html', QSTR.joinQuantiaMD);
        this.showPage(nextPage);
        q$('emailAddressPage2').innerHTML = this._dlgElts.usersEmail.value;
        this.setCurrentItemAndFocus(q$('registrationUsersPassword1'), true);
    };
    RegDlgMultiPageUnivStyle.prototype.checkForErrors = function () {
        var tempThis = this; // .each() iterator establishes a new 'this', so use tempThis
        var inputs = this._dlgElts.allElements[this._currentPageId + '_tabElements'];
        inputs.each(function (elem) {
            if (!elem)
                return;
            var errstr = (elem.valfun) ? elem.valfun() : null;
            if (errstr)
                tempThis.setError(elem, errstr);
            else
                tempThis.clearError(elem, true);
        });
        this.showPageErrorBlock(this.areErrors(), null);
    };
    RegDlgMultiPageUnivStyle.prototype.register = function () {
        var now = (new Date()).getTime();
        if (now - this._lastAttempted < 2000)
            return;
        this._lastAttempted = now;
        this.checkForErrors();
        if (!this.areErrors()) {
            this._submitted = true;
            this._dlgElts.joinQuantiaButtonLabel.set('html', QSTR.submittingWithElipsis);
            var dfId = RegDlgBase.finddfid();
            var signupURI = RegDlgBase.getSignupURI();
            var signupReferFromURL = this._referrer;
            var signupChallengeScreen = RegDlgBase.getSignupChallengeScreen();
            var mcc = gQCredentials.GetMarketingCampaignCode();
            if (mcc) {
                gQCredentials.AddDfIdToMarketingCode(dfId);
            }
            var effPartnerCodes = (AccountInfo.DevicePartnerCode) ?
                AccountInfo.DevicePartnerCode + ";" + gQCredentials.GetPartner() :
                gQCredentials.GetPartner();
            var accountObject_1 = {
                partner: effPartnerCodes,
                marketingCampaignCode: mcc,
                allowContact: true,
                signupDFID: dfId,
                signupReferrer: signupReferFromURL,
                signupReferFromURL: signupReferFromURL,
                signupURI: signupURI,
                signupChallengeScreen: signupChallengeScreen,
                specialties: this.determineSelectedSpecialties(),
                primaryLanguage: AccountInfo.PrimaryLanguage,
                languages: AccountInfo.Languages
            };
            $$('#registerPage input').forEach(function (elem) {
                var key = elem.id;
                // change registrationFirstName to firstName, etc
                if (key.search(/^registration/) != -1) {
                    key = key.substring(12, 13).toLowerCase() + key.substring(13);
                }
                // change usersEmail to email, etc
                if (key.match(/^users/)) {
                    key = key.substring(5).toLowerCase();
                }
                accountObject_1[key] = elem.value;
            });
            AccountUtil.CreateNewAccount(this.onSuccess.bind(this), this.onFailure.bind(this), accountObject_1);
        }
        this.setGlobalRegisterActive(false);
    };
    RegDlgMultiPageUnivStyle.prototype.pwdOnlyRegister = function () {
        var now = (new Date()).getTime();
        if (now - this._lastAttempted < 2000)
            return;
        this._lastAttempted = now;
        this.checkForErrors();
        if (!this.areErrors()) {
            this._submitted = true;
            this._dlgElts.joinQuantiaButtonLabel.set('html', QSTR.submittingWithElipsis);
            var dfId = RegDlgBase.finddfid();
            var signupURI = RegDlgBase.getSignupURI();
            var signupReferFromURL = this._referrer;
            var signupChallengeScreen = RegDlgBase.getSignupChallengeScreen();
            var mcc = gQCredentials.GetMarketingCampaignCode();
            if (mcc) {
                gQCredentials.AddDfIdToMarketingCode(dfId);
            }
            var effPartnerCodes = (AccountInfo.DevicePartnerCode) ?
                AccountInfo.DevicePartnerCode + ";" + gQCredentials.GetPartner() :
                gQCredentials.GetPartner();
            var accountObject_2 = {
                allowContact: true,
                partner: effPartnerCodes,
                marketingCampaignCode: mcc,
                signupDFID: dfId,
                signupReferrer: signupReferFromURL,
                signupReferFromURL: signupReferFromURL,
                signupURI: signupURI,
                signupChallengeScreen: signupChallengeScreen,
                regid: this._regid
            };
            $$('#passwordOnlyRegisterPage input').forEach(function (elem) {
                var key = elem.id;
                // change onlyPwdRegistrationFirstName to firstName, etc
                if (key.search(/^onlyPwdRegistration/) != -1) {
                    key = key.substring(19, 20).toLowerCase() + key.substring(20);
                }
                // change usersEmail to email, etc
                if (key.match(/^users/)) {
                    key = key.substring(5).toLowerCase();
                }
                accountObject_2[key] = elem.value;
            });
            AccountUtil.CreateNewAccountPwdOnly(this.onlyPwdSuccess.bind(this), this.onlyPwdFailure.bind(this), accountObject_2);
        }
        this.setGlobalRegisterActive(false);
    };
    /**
     * This method is called when only password register request succeeds
     */
    RegDlgMultiPageUnivStyle.prototype.onlyPwdSuccess = function () {
        ActivityMonitor.cancelTimerOnly();
        var emval = this._dlgElts.onlyPwdRegistrationEmail.value.trim();
        var pwval = this._dlgElts.onlyPwdRegistrationPassword.value;
        gQCredentials.AttemptLogin(emval, pwval, function (result, message) {
            if (result) {
                createCookie("resumeAfterLogin", 'true', Common.ONE_MINUTE_IN_DAYS);
                Pageparams.exitCondition = "register";
                Common.attemptWindowQuit();
                Common.quickReload();
            }
            else {
                this.showPageErrorBlock(true, this.localizeErrorMsg(message));
            }
        });
    };
    /**
     * This methos is called when  only password register request fails
     * @param {string} errorMessage
     */
    RegDlgMultiPageUnivStyle.prototype.onlyPwdFailure = function (errorMessage) {
        this.showPageErrorBlock(true, this.localizeErrorMsg(errorMessage));
    };
    /**
     * login method is used to log in users from reLoginPage
     */
    RegDlgMultiPageUnivStyle.prototype.login = function () {
        var pwElt = q$('registrationUsersPassword1');
        if (pwElt.value == "")
            return;
        var emval = this._dlgElts.usersEmail.value.trim();
        var pwval = pwElt.value;
        gQCredentials.AttemptLogin(emval, pwval, this.loginCallback.bind(this));
    };
    /**
     * loginCallback is called after a login request. it handles both cases; success and failure
     * @param result:boolean, return true if the request succeeds, false, otherwise
     * @param message the error message if the request fails
     */
    RegDlgMultiPageUnivStyle.prototype.loginCallback = function (result, message) {
        if (!result) {
            this.showPageErrorBlock(true, message);
            return;
        }
        Pageparams.exitCondition = "login";
        createCookie("resumeAfterLogin", 'true', Common.ONE_MINUTE_IN_DAYS);
        Common.attemptWindowQuit();
        var loc = window.location.href;
        var u = queryString("user");
        if (u) {
            // FIXME:  when does this happen?
            loc = loc.replace("user=" + queryString("user"), "");
            window.location.href = loc;
        }
        else {
            if (!this._afterLoginUrl)
                Common.quickReload();
            else
                window.location.href = this._afterLoginUrl;
        }
    };
    RegDlgMultiPageUnivStyle.prototype.forgotPasswordSubmit = function () {
        var emailElt = q$('registrationUsersEmail');
        var emailAddress = emailElt.value.trim();
        if (emailAddress == '')
            return;
        var tempThis = this;
        function showForgetPasswordPage() {
            tempThis.goToPage('forgotPasswordPage');
            q$('emailAddressPage3').innerHTML = emailElt.value.trim();
        }
        setTimeout(function () {
            RegDlgBase.requestPassword(emailAddress, showForgetPasswordPage, null);
        }, 200);
    };
    RegDlgMultiPageUnivStyle.prototype.notMe = function () {
        this._defaultValues = {
            firstName: "",
            lastName: "",
            officeZip: "",
            countryOfPractice: "",
            specialty: "",
            credentials: ""
        };
        this.resetAllFields(true);
    };
    RegDlgMultiPageUnivStyle.prototype.areErrors = function () {
        return (this._errors.length > 0);
    };
    RegDlgMultiPageUnivStyle.prototype.setError = function (elem, msg) {
        elem.addClass("hasError");
        if (elem.id == 'registrationCredentials') {
            elem.removeClass('hiddenDialog');
            q$('registrationCredentialsOtherOuterDiv').removeClass('hiddenDialog');
        }
        this.addErrorData(elem);
    };
    /**
     * Show the error block for the current page
     * @param show  show or hide
     * @param message a custom message, if set to null, the default message will be shown
     */
    RegDlgMultiPageUnivStyle.prototype.showPageErrorBlock = function (show, message) {
        if (show) {
            $$('#' + this._currentPageId + '  .error').forEach(function (elem) {
                elem.removeClass("hiddenDialog");
                if (!message && elem.hasClass("custom")) {
                    // hide the custom error block if there is no custom error message
                    elem.addClass("hiddenDialog");
                }
                else if (message && elem.hasClass("custom")) {
                    // if we have a  custom error message then display it
                    elem.innerHTML = message;
                }
                else if (message && elem.hasClass("default")) {
                    // if we have a  custom error message hide the default error block
                    elem.addClass("hiddenDialog");
                }
            });
        }
        else {
            $$('#' + this._currentPageId + '  .error').forEach(function (elem) {
                elem.addClass("hiddenDialog");
            });
        }
    };
    RegDlgMultiPageUnivStyle.prototype.addErrorData = function (element) {
        if (this._errors.indexOf(element.id) == -1) {
            this._errors.push(element.id);
        }
    };
    RegDlgMultiPageUnivStyle.prototype.clearError = function (elem, isValidated) {
        elem.removeClass('hasError');
        var id = elem.id;
        var index = this._errors.indexOf(id);
        if (index > -1) {
            this._errors.splice(index, 1);
        }
    };
    RegDlgMultiPageUnivStyle.prototype.emailValidatedCallback = function (ok) {
        var elem = this._dlgElts.usersEmail;
        if (!ok)
            this.setError(elem, QSTR.enterValidEmail);
        else
            this.clearError(elem, true);
    };
    RegDlgMultiPageUnivStyle.prototype.makeRegistrationFormVisible = function (whatToShow) {
        // WHAT?
        if (typeof (PageLayout) != 'undefined') {
            PageLayout.moveSecondPanelOffscreen();
            PageLayout.moveExtraPanelCntOffscreen();
        }
        var pc = q$('playerContainer'); // desktop browser
        if (!pc)
            pc = q$('playerPanel'); // mobile browser
        Common.chide(pc);
        var regOnPageElt = q$('registerOnPage');
        if (whatToShow.hideOuterFrame) {
            regOnPageElt.addClass('hideOuter');
        }
        var self = this;
        setTimeout(function () {
            self.show();
        }, 10);
        var placeholderElt = q$('playerPlaceholder');
        if (placeholderElt) {
            placeholderElt.setStyle('height', '0px');
        }
    };
    // part of div ID=?
    RegDlgMultiPageUnivStyle._strRegistrationCredentials = 'registrationCredentials';
    return RegDlgMultiPageUnivStyle;
}(RegDlgBase));
/*  RegOrSigninOnPageUnivStyle
 */
var RegOrSigninOnPageUnivStyle = (function (_super) {
    __extends(RegOrSigninOnPageUnivStyle, _super);
    function RegOrSigninOnPageUnivStyle(afterLoginUrl, pageLinkUrl, defVals) {
        var _this = _super.call(this, defVals) || this;
        _this._afterLoginUrl = afterLoginUrl;
        _this._pageLinkUrl = pageLinkUrl;
        return _this;
        // doOnPageReady( this.afterLogin.bind(this));
    }
    RegOrSigninOnPageUnivStyle.prototype.afterLogin = function () {
        if (gQCredentials.isAnonymous()) {
            if ((typeof BrowserPlayer === 'undefined') || (BrowserPlayer.getDfErrorCode() != 0)) {
                this.makeRegistrationFormVisible({ hideOuterFrame: true });
            }
        }
    };
    RegOrSigninOnPageUnivStyle.prototype.displayError = function (errorElem, sourceField, errorString) {
        errorString = errorString.replace(/\r\n/, '');
        this._errors.push(errorString);
        if (sourceField) {
            if (sourceField.indexOf('Password') >= 0) {
                sourceField = (!Common.ischidden('usersPassword')) ?
                    'usersPassword' : 'usersPassword_prompt';
            }
        }
        var elem = q$(sourceField + "_container");
        if (elem)
            elem.addClass("errorField");
    };
    RegOrSigninOnPageUnivStyle.prototype.makeRegistrationFormVisible = function (whatToShow) {
        // WHAT?
        if (typeof (PageLayout) != 'undefined') {
            PageLayout.moveSecondPanelOffscreen();
            PageLayout.moveExtraPanelCntOffscreen();
        }
        var pc = q$('playerContainer'); // desktop browser
        if (!pc)
            pc = q$('playerPanel'); // mobile browser
        Common.chide(pc);
        var regOnPageElt = q$('registerOnPage');
        var regDlgElt = q$('registerDialog');
        var registerPageElt = q$('registerPage');
        if (whatToShow.hideOuterFrame) {
            regOnPageElt.addClass('hideOuter');
        }
        var self = this;
        setTimeout(function () {
            registerPageElt.removeClass("hiddenDialog");
            regOnPageElt.addClass("univStyle");
            regDlgElt.removeClass("hiddenDialog");
            Common.cshow(regOnPageElt);
        }, 10);
        var placeholderElt = q$('playerPlaceholder');
        if (placeholderElt) {
            placeholderElt.setStyle('height', '0px');
        }
    };
    RegOrSigninOnPageUnivStyle.setCredentials = function () {
        var userCredElt = q$('usersCredentials');
        var a = ['MD', 'DO', 'PA', 'NP'];
        for (var i = 0; i < 4; ++i) {
            var credID = 'credentials' + a[i];
            var credElt = q$(credID);
            if (credElt && credElt.checked) {
                userCredElt.value = a[i];
                return;
            }
        }
        if (q$('credentialsOther').checked) {
            userCredElt.value = q$('credentialsOtherValue').value;
        }
    };
    return RegOrSigninOnPageUnivStyle;
}(RegDlgBase));




// RegDlgOnePage.js

///<reference path="Ajax.d.ts"/>
/// <reference path="mootools.d.ts" />
/// <reference path="CommonWeb.ts" />
/// <reference path="RegDlgMultiPage.ts" />
/// <reference path="RegDlgMultiPageUnivStyle.ts" />
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
// RegDlgOnePage is base class for RegDlgMobileOnePage and
// for RegDlgExpress
var RegDlgOnePage = (function (_super) {
    __extends(RegDlgOnePage, _super);
    function RegDlgOnePage(postRegCallback, defVals) {
        var _this = _super.call(this, "", defVals) || this;
        // overrides for error messages for single-page style reg
        // messages are displayed farther from the entry fields in single-page reg
        _this._errorMessage = {
            'registrationFirstName': QSTR.registerEnterFirstName,
            'registrationLastName': QSTR.registerEnterLastName,
            'registrationUsersPassword': QSTR.registerPasswordTooShortFullMsg,
            'registrationConfirmPassword': QSTR.passwordMismatch,
            'registrationCountryOfPractice': QSTR.countryOfPracticeRequired,
            'registrationSpecialty': QSTR.registerEnterSpecialty,
            'registrationCredentials': QSTR.registerEnterCredentials,
            'registrationOptInAgreeToTerms': QSTR.registerAgreeToTerms
        };
        _this._postRegistrationCallback = postRegCallback; // probably launchMobileApp() in FMT
        return _this;
    }
    // override
    RegDlgOnePage.prototype.setError = function (elem, msg) {
        var status = this.getErrorFieldForElem(elem);
        var elemID = elem.id;
        if (this._errorMessage[elemID])
            msg = this._errorMessage[elemID];
        status.innerHTML = '<div>' + msg + '</div>';
        elem.addClass('hasError');
        this.addErrorData(elem);
    };
    // override
    RegDlgOnePage.prototype.handleResize = function () {
        var w = window.innerWidth;
        var h = window.innerHeight;
        var minDimension = Math.min(w, h);
        //alert('w = ' + w + ', h = ' + h);
        var dpi = 132;
        var minInches = minDimension / dpi;
        var cssSizeClass = (minInches < 4) ? 'phone' : 'tablet';
        var orientationClass = (w < h) ? 'portrait' : 'landscape';
        var formerOrientation = (w < h) ? 'landscape' : 'portrait';
        var b = q$(document.body);
        b.addClass(cssSizeClass);
        b.addClass(orientationClass);
        b.removeClass(formerOrientation);
    };
    RegDlgOnePage.prototype.onSuccess = function () {
        this.clearSignupURI();
        // attempt to help google analytics track this
        try {
            pageTracker._trackPageview('/goal/registration.html');
        }
        catch (e) { }
        this.doAfterRegistration();
    };
    RegDlgOnePage.prototype.onCredentialsClick = function (evt) {
        _super.prototype.onCredentialsClick.call(this, evt);
        // when called from space key, evt is an element, otherwise it's a mootools event object
        var evtIsAnEvent = false;
        if (evt.target)
            evtIsAnEvent = true;
        var targetID = evtIsAnEvent ? evt.target.id : evt.id; // extract element id
        setTimeout(function () { q$(targetID).checked = true; }, 50);
        return false;
    };
    RegDlgOnePage.prototype.onFailure = function (errorMessage) {
        this._submitted = false;
        this._dlgElts.joinQuantiaButtonLabel.set('html', QSTR.joinQuantiaMD);
        q$('errorFromServer').innerHTML = this.localizeErrorMsg(errorMessage);
        Common.cshow('createNewAccountErrorMessage');
    };
    RegDlgOnePage.prototype.localizeErrorMsg = function (inMsg) {
        var outMsg = inMsg;
        // override one thing because single-page form doesn't give option to reset pwd
        if (inMsg == "USER_EXISTS")
            outMsg = QSTR.registerAccountAlreadyExistsPasswordIncorrectText;
        else
            outMsg = _super.prototype.localizeErrorMsg.call(this, inMsg);
        return (outMsg);
    };
    RegDlgOnePage.prototype.checkForErrors = function () {
        q$('errorFromServer').innerHTML = ''; // clear previous error from server
        _super.prototype.checkForErrors.call(this);
        // mobile is like web except has a div where errors go
        // toggle its visibility:
        if (this.areErrors())
            Common.cshow('createNewAccountErrorMessage');
        else
            Common.chide('createNewAccountErrorMessage');
    };
    return RegDlgOnePage;
}(RegDlgMultiPage));
// RegDlgMobileOnePage:  this looks like RegDlgOnePage, but declare
// a separate class as a marker of how it is used.
var RegDlgMobileOnePage = (function (_super) {
    __extends(RegDlgMobileOnePage, _super);
    function RegDlgMobileOnePage(launchUrl, defVals, calledFromApp) {
        var _this = _super.call(this, "", defVals) || this;
        if (calledFromApp) {
            _this.launchUrl = launchUrl;
            _this._postRegistrationCallback = _this.launchMobileApp.bind(_this);
            // form will be inited and shown when page is ready
            _this.myinit();
            doOnPageReady(_this.initPage.bind(_this));
        }
        else {
            // called from player
            _this._postRegistrationCallback = _this.reloadAsUser.bind(_this);
            _this.myinit();
            _this.initPage();
        }
        return _this;
    }
    RegDlgMobileOnePage.prototype.myinit = function () {
        scrollTo(0, 1);
        $$('input.field').each(function (item) {
            item.addEvent('change', function () {
                if (item.value == '')
                    q$(item).removeClass('nonEmpty');
                else
                    q$(item).addClass('nonEmpty');
            });
        });
        $$('.hasPlaceholder').each(function (e) {
            var placeholder = e.value;
            e.addEventListener('focus', function () {
                if (e.value == placeholder)
                    q$(e).value = '';
                q$(e).removeClass('hasPlaceholder');
            });
            e.addEventListener('blur', function () {
                if (e.value == '' || e.value == placeholder) {
                    q$(e).value = placeholder;
                    q$(e).addClass('hasPlaceholder');
                }
            });
        });
        window.addEvent('domready', function () {
            $$('input.field').each(function (item) {
                item.fireEvent('change');
            });
        });
    };
    RegDlgMobileOnePage.prototype.launchMobileApp = function () {
        createCookie("hasApp", "true", 2000);
        var url = this.launchUrl;
        var pw = q$('registrationUsersPassword').value;
        var addr = q$('registrationUsersEmail').value;
        if (pw && addr) {
            if (url.indexOf('?') == -1)
                url = url + '?';
            url += '&password=' + encodeURIComponent(pw);
            url += '&user=' + encodeURIComponent(addr);
        }
        setTimeout(function () {
            document.location.href = url;
        }, 1500);
    };
    RegDlgMobileOnePage.prototype.reloadAsUser = function () {
        var pw = q$('registrationUsersPassword').value;
        var addr = q$('registrationUsersEmail').value;
        gQCredentials.AttemptLogin(addr, pw, function (result, message) {
            if (result) {
                createCookie("resumeAfterLogin", 'true', Common.ONE_MINUTE_IN_DAYS);
                Pageparams.exitCondition = "register";
                Common.attemptWindowQuit();
                Common.quickReload();
            }
            else {
                alert(message);
            }
        });
    };
    return RegDlgMobileOnePage;
}(RegDlgOnePage));
// RegDlgMobileOnePage:  this looks like RegDlgOnePage, but declare
// a separate class as a marker of how it is used.
var RegDlgMobileOnePageUnivStyle = (function (_super) {
    __extends(RegDlgMobileOnePageUnivStyle, _super);
    function RegDlgMobileOnePageUnivStyle(launchUrl, defVals, calledFromApp) {
        var _this = _super.call(this, "", defVals) || this;
        if (calledFromApp) {
            _this.launchUrl = launchUrl;
            _this._postRegistrationCallback = _this.launchMobileApp.bind(_this);
            // form will be inited and shown when page is ready
            _this.myinit();
        }
        else {
            // called from player
            _this._postRegistrationCallback = _this.reloadAsUser.bind(_this);
            _this.myinit();
        }
        return _this;
    }
    RegDlgMobileOnePageUnivStyle.prototype.myinit = function () {
    };
    RegDlgMobileOnePageUnivStyle.prototype.launchMobileApp = function () {
        createCookie("hasApp", "true", 2000);
        var url = this.launchUrl;
        var pw = q$('registrationUsersPassword').value;
        var addr = q$('registrationUsersEmail').value;
        if (pw && addr) {
            if (url.indexOf('?') == -1)
                url = url + '?';
            url += '&password=' + encodeURIComponent(pw);
            url += '&user=' + encodeURIComponent(addr);
        }
        setTimeout(function () {
            document.location.href = url;
        }, 1500);
    };
    RegDlgMobileOnePageUnivStyle.prototype.reloadAsUser = function () {
        var pw = q$('registrationUsersPassword').value;
        var addr = q$('registrationUsersEmail').value;
        gQCredentials.AttemptLogin(addr, pw, function (result, message) {
            if (result) {
                createCookie("resumeAfterLogin", 'true', Common.ONE_MINUTE_IN_DAYS);
                Pageparams.exitCondition = "register";
                Common.attemptWindowQuit();
                Common.quickReload();
            }
            else {
                alert(message);
            }
        });
    };
    return RegDlgMobileOnePageUnivStyle;
}(RegDlgMultiPageUnivStyle));




// RegDlgPwdOnly.js

///<reference path="Ajax.d.ts"/>
///<reference path="mootools.d.ts" />
///<reference path="CommonWeb.ts" />
///<reference path="RegDlgBase.ts" />
/// <reference path="AccountUtil.ts" />
/// <reference path="ActivityMonitor.ts" />
/// <reference path="Window.d.ts" />
var RegDlgPwdOnly = (function () {
    function RegDlgPwdOnly() {
    }
    RegDlgPwdOnly.attemptPwdOnlyReg = function () {
        if (RegDlgPwdOnly._clickCount > 0) {
            return;
        }
        var reg = new RegDlgPwdOnly();
        var err = reg.validate();
        if (err) {
            alert(err);
            return;
        }
        RegDlgPwdOnly._clickCount++;
        reg.register();
    };
    RegDlgPwdOnly.showFullRegForm = function () {
        // registerDialog might have PrePop values, clear them out
        Pageparams.registerDialog.clearDefaults();
        Pageparams.registerDialog.resetAllFields(true);
        if (PageFlavor.isMoBr()) {
            // switch which form is visible
            Common.chide("pwdOnlyReg");
            Common.cshow("mobileInlineReg");
        }
        else {
            Pageparams.registerDialog.show();
        }
    };
    RegDlgPwdOnly.submitForgotPassword = function () {
        if (RegDlgPwdOnly._clickCount > 0) {
            return;
        }
        var reg = new RegDlgPwdOnly();
        var err = reg.validateEmailAddr();
        if (err) {
            alert(err);
            return;
        }
        var emailAddr = q$('pwdOnlyRegEmailAddr').value;
        function forgotRequestResponse() {
            RegDlgPwdOnly._clickCount--;
            sprintf(QSTR.forgotPasswordSuccess, emailAddr);
            alert("A reset password link has been sent to the email address above.  Please check your inbox.");
        }
        RegDlgPwdOnly._clickCount++;
        RegDlgBase.requestPassword(emailAddr, forgotRequestResponse, forgotRequestResponse);
    };
    RegDlgPwdOnly.prototype.validateEmailAddr = function () {
        var emailAddrElt = q$('pwdOnlyRegEmailAddr');
        return RegDlgElts2.validateEmailRegex(emailAddrElt);
    };
    RegDlgPwdOnly.prototype.validatePassword = function () {
        var pwdElt = q$('pwdOnlyRegPassword');
        return RegDlgEltsBase.validatePassword(pwdElt);
    };
    RegDlgPwdOnly.prototype.validate = function () {
        var err = this.validateEmailAddr();
        if (err)
            return err;
        err = this.validatePassword();
        if (err)
            return err;
        return "";
    };
    RegDlgPwdOnly.prototype.register = function () {
        var dfId = RegDlgBase.finddfid();
        var signupURI = RegDlgBase.getSignupURI();
        var signupReferFromURL = null;
        var signupChallengeScreen = RegDlgBase.getSignupChallengeScreen();
        var mcc = gQCredentials.GetMarketingCampaignCode();
        if (mcc) {
            gQCredentials.AddDfIdToMarketingCode(dfId);
        }
        var effPartnerCodes = (AccountInfo.DevicePartnerCode) ?
            AccountInfo.DevicePartnerCode + ";" + gQCredentials.GetPartner() :
            gQCredentials.GetPartner();
        this._emailAddr = q$('pwdOnlyRegEmailAddr').value;
        this._pwd = q$('pwdOnlyRegPassword').value;
        var rgid = queryString("rgid");
        var accountObject = {
            partner: effPartnerCodes,
            marketingCampaignCode: mcc,
            allowContact: true,
            signupDFID: RegDlgBase.finddfid(),
            signupReferrer: signupReferFromURL,
            signupReferFromURL: signupReferFromURL,
            signupURI: signupURI,
            signupChallengeScreen: signupChallengeScreen,
            email: this._emailAddr,
            password: this._pwd,
            regid: rgid
        };
        var htmlElt = q$('pwdOnlyRegButton');
        htmlElt.disabled = true;
        //q$('pwdOnlyRegButton').disabled = true;
        AccountUtil.CreateNewAccountPwdOnly(this.onSuccess.bind(this), this.onError.bind(this), accountObject);
    };
    RegDlgPwdOnly.prototype.onSuccess = function () {
        RegDlgPwdOnly._clickCount--;
        ActivityMonitor.cancelTimerOnly();
        gQCredentials.AttemptLogin(this._emailAddr, this._pwd, function (result, message) {
            if (result) {
                createCookie("resumeAfterLogin", 'true', Common.ONE_MINUTE_IN_DAYS);
                Pageparams.exitCondition = "register";
                Common.attemptWindowQuit();
                Common.quickReload();
            }
            else {
                alert(message);
            }
        });
    };
    RegDlgPwdOnly.prototype.onError = function (errorMessage) {
        alert(errorMessage);
        RegDlgPwdOnly._clickCount--;
        var htmlElt = q$('pwdOnlyRegButton');
        htmlElt.disabled = false;
    };
    RegDlgPwdOnly._clickCount = 0;
    return RegDlgPwdOnly;
}());




// RegDlgExpress.js

///<reference path="Ajax.d.ts"/>
/// <reference path="mootools.d.ts" />
/// <reference path="CommonWeb.ts" />
/// <reference path="RegDlgOnePage.ts" />
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var RegDlgExpress = (function (_super) {
    __extends(RegDlgExpress, _super);
    function RegDlgExpress(marketingCode, parterCode, afterRegUrl, afterRegCallback, defVals) {
        var _this = this;
        if (afterRegCallback != null) {
            _this = _super.call(this, afterRegCallback, defVals) || this;
        }
        else {
            _this = _super.call(this, _this.loginAfterRegister.bind(_this), defVals) || this;
        }
        if (marketingCode)
            gQCredentials.EnsureMarketingCampaignCode(marketingCode);
        if (parterCode)
            gQCredentials.EnsurePartnerCode(parterCode);
        _this._afterLoginUrl = afterRegUrl;
        // form will be inited and shown when page is ready
        doOnPageReady(_this.initPage.bind(_this));
        return _this;
    }
    RegDlgExpress.prototype.initPage = function () {
        //This is to allow tabbing through login input fields and Sign In button on top of the screen
        this._dlgElts = new RegDlgElts2();
        var loginuser = q$('loginuser');
        if (loginuser)
            this._dlgElts.addLoginUserElts(loginuser);
        this.handleResize();
        this.resetAllFields(false);
        this.addEvents();
    };
    return RegDlgExpress;
}(RegDlgOnePage));




// Login.js

/// <reference path="mootools.d.ts" />
/// <reference path="Common.d.ts" />
var Login = (function () {
    function Login(afterLoginUrl) {
        this.afterLoginUrl = afterLoginUrl;
    }
    Login.prototype.initForHeader = function () {
        this.userEltID = 'loginuser';
        this.pwEltID = 'loginpwd';
        this.loginBtnID = 'loginButton';
        this.errMsgEltID = 'loginErrorMessage';
        this.errMsgInnerEltID = 'loginErrorMessageInner';
        this.containerID = 'loginInputContainer';
        this.topRowID = 'loginTopRow';
        doOnPageReady(this.onPageReady.bind(this));
    };
    Login.prototype.initForOnPage = function () {
        this.userEltID = 'usersSignInEmail';
        this.pwEltID = 'usersSignInPassword';
        this.loginBtnID = 'registerOnPageLoginButton';
        this.errMsgEltID = null;
        this.errMsgInnerEltID = null;
        this.containerID = null;
        this.topRowID = null;
        doOnPageReady(this.onPageReady.bind(this));
    };
    /**
     * Sets the login form  elements (login input, password input and login button  ) required  for login In the Login banner element
     */
    Login.prototype.initForLoginBanner = function () {
        this.userEltID = 'loginBannerEmail';
        this.pwEltID = 'loginBannerPass';
        this.loginBtnID = 'loginBannerSubmitBtn';
        this.errMsgEltID = 'loginBannerErrorsContainer';
        this.errMsgInnerEltID = 'loginBannerErrorsInner';
        this.containerID = 'loginBannerInputFlields';
        this.topRowID = null;
        doOnPageReady(this.onPageReady.bind(this));
    };
    Login.prototype.loginCallback = function (result, message) {
        if (result) {
            Pageparams.exitCondition = "login";
            Common.attemptWindowQuit();
            var loc = window.location.href;
            if (queryString("user")) {
                loc = loc.replace("user=" + queryString("user"), "");
                window.location.href = loc;
            }
            else {
                if (!this.afterLoginUrl)
                    Common.quickReload();
                else
                    window.location.href = this.afterLoginUrl;
            }
        }
        else {
            this.loginDisplayError(message);
        }
    };
    Login.prototype.loginOnEnter = function (e) {
        var keyPressed = e.key;
        var pwElt = q$(this.pwEltID);
        if (keyPressed == 'enter') {
            if (pwElt.value == '') {
                pwElt.focus();
                return;
            }
            this.logMeIn(null);
            return;
        }
        // Enable the 'Sign In' button?
        var unElt = q$(this.userEltID);
        /*getValue() is not necessarily defined for all elements: it's implémented by defaulttext.js api for old placeholder
        * In case, it is defined, we should use it first otherwise make sure to call the default value attribute
        * */
        var username = (typeof unElt.getValue === 'function') ? unElt.getValue() : unElt.value;
        var pwd = (typeof pwElt.getValue === 'function') ? pwElt.getValue() : pwElt.value;
        q$(this.loginBtnID).toggleClass('disabledButton', (username == '' || pwd == ''));
    };
    Login.prototype.logMeIn = function (event) {
        var loginButton = q$(this.loginBtnID);
        if (!loginButton.hasClass('disabledButton')) {
            loginButton.addClass('disabledButton');
            var emailAddr_1 = q$(this.userEltID).value;
            var pwd_1 = q$(this.pwEltID).value;
            if (emailAddr_1 == '' || pwd_1 == '') {
                this.loginDisplayError(QSTR.loginFailed);
                return;
            }
            var self_1 = this;
            var errMsgElt_1 = q$(this.errMsgEltID);
            if (errMsgElt_1) {
                Common.fadeToOpacity(errMsgElt_1, 0, 500, function () {
                    Common.chide(errMsgElt_1);
                    gQCredentials.AttemptLogin(emailAddr_1, pwd_1, self_1.loginCallback.bind(self_1));
                });
            }
            else {
                gQCredentials.AttemptLogin(emailAddr_1, pwd_1, self_1.loginCallback.bind(self_1));
            }
        }
        if (event) {
            event.stop();
        }
    };
    Login.prototype.loginDisplayError = function (msg) {
        var errMsgElt = q$(this.errMsgEltID);
        if (!errMsgElt)
            return; // this instance doesn't manage its own errors
        var containerElt = q$(this.containerID);
        if (containerElt)
            containerElt.addClass('errorField');
        q$(this.loginBtnID).removeClass('disabledButton');
        if (!Common.ischidden(this.pwEltID)) {
            containerElt.addClass('errorField');
        }
        var self = this;
        Common.fadeToOpacity(errMsgElt, 0, 10, function () {
            Common.cshow(errMsgElt);
            q$(self.errMsgInnerEltID).innerHTML = msg;
            scrollTo(0, 0);
            Common.fadeToOpacity(errMsgElt, 1, 500);
            var topRowElt = q$(self.topRowID);
            if (topRowElt)
                Common.fadeToOpacity(topRowElt, 0, 500);
        });
    };
    Login.prototype.onPageReady = function () {
        var uElt = q$(this.userEltID);
        var btnElt = q$(this.loginBtnID);
        if (uElt) {
            uElt.addEvent("keyup", this.loginOnEnter.bind(this));
            q$(this.pwEltID).addEvent("keyup", this.loginOnEnter.bind(this));
            btnElt.addEvent("click", this.logMeIn.bind(this));
            btnElt.addEvent("keydown", this.loginOnEnter.bind(this));
        }
        return false;
    };
    return Login;
}());
var gLoginHeader = new Login("");
gLoginHeader.initForHeader();
var gLoginOnPage = new Login("");
gLoginOnPage.initForOnPage();
var gLoginOnLoginBanner = new Login("");
gLoginOnLoginBanner.initForLoginBanner();

