


// 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();




// onhashchange.js

(function($,$$) {

    //set the events
    window.store('hashchange:interval',300);
    window.store('hashchange:implemented',!!('onhashchange' in window));
    
    Element.Events.hashchange = {
            
        onAdd: function(fn) {
            //clear the event
            Element.Events.hashchange.onAdd = Function.from;
            var hash;
            //check the element
            var self = q$(this);
            var checker = Function.from;
            if (typeOf(self) != 'window') {
                return; //the window object only supports this
            }
    
            //this will prevent the browser from firing the url when the page loads (native onhashchange doesn't do this)
            window.store('hashchange:changed',false);
    
              //this global method gets called when the hash value changes for all browsers
            var hashchanged = function(hash,tostore) {
                window.store('hashchange:current',tostore || hash);
                if (window.retrieve('hashchange:changed')) {
                    hash = hash.trim();
                    if (hash.length === 0) {
                        var url = new String(window.location);
                        if (url.indexOf('#')>=0)
                            hash = '#';
                    }
                    window.fireEvent('hashchange',[hash]);
                }
                else {
                    window.store('hashchange:changed',true);
                }
            };
    
            //this is used for when a hash change method has already been defined (futureproof)
            if (typeof window.onhashchange == 'function' && fn !== window.onhashchange) {
                //bind the method to the mootools method stack
                window.addEvent('hashchange',window.onhashchange);
    
                //remove the event
                window.onhashchange = null;
            }

            //Oldschool IE browsers
            if (Browser.name == 'ie' && Browser.version < 8) {
    
                //IE6 and IE7 require an empty frame to relay the change (back and forward buttons)
                //custom IE method
                checker = function(url,frame) {
    
                    //clear the timer
                    var checker = window.retrieve('hashchange:checker');
                    var timer = window.retrieve('hashchange:timer');
                    clearTimeout(timer); //just incase
                    timer = null;
        
                    //IE may give a hash value, a path value or a url
                    var isNull = frame && url.length === 0;
                    var isEmpty = url == '#';
                    var compare, cleanurl = unescape(new String(window.location));
        
                    if (isEmpty) {
                        compare = hash = '#';
                    } else if (isNull) {
                        compare = hash = '';	
                    }
                    else {
                        //setup the url
                        url = (url) ? url : cleanurl;
                        hash = url;
                        if (url.length > 0) { //not an empty hash
                            var index = url.indexOf('#');
                            if (index >= 0)
                                hash = url.substr(index);
                        }
        
                        //check the hash
                        compare = hash.toLowerCase();
                    }
        
                    //if the hash value is different, then it has changed
                    var current = window.retrieve('hashchange:current');
                    if (current != compare) {
                        //update the url
                        if (frame) {
                            url = cleanurl;
                            if (current) {
                                url = url.replace(current,hash);
                            } else {
                                url += hash;
                            }
                            window.location = url;
                        }
        
                        //check the flag
                        var hasChanged = !frame && window.retrieve('hashchange:changed');
        
                        //change the hash
                        hashchanged(hash,compare);
                    }
        
                    //reset the timer
                    timer = checker.delay(window.retrieve('hashchange:interval'));
                    window.store('hashchange:timer',timer);
                };
                
            } else if (window.retrieve('hashchange:implemented')) { 
                //Firefox 3.6, Chrome 5, IE8 and Safari 5 all support the event natively
    
                //check the hashcheck
                checker = window.onhashchange = function(hash) {
                    //make sure the hash is a string
                    hash = hash && typeof hash == 'string' ? hash : new String(window.location.hash);
                    //this is important so that the URL hash has changed BEFORE this is fired
                    hashchanged.delay(1,window,[hash]);
                };
            } else { 
                //Others
                //opera requires a history mode to be set so that #hash values are recorded in history (back and forward buttons)
                if (Browser.opera) {
                  history.navigationMode='compatible';
                }
    
                //set the inteval method
                checker = function(hash) {
                    //clear the timer
                    var checker = window.retrieve('hashchange:checker');
                    var timer = window.retrieve('hashchange:timer');
                    clearTimeout(timer); //just incase
                    timer = null;
                    //compare the hash
                    var hash = hash || new String(window.location.hash);
                    var compare = hash.toLowerCase();
                    if (hash.length === 0 && new String(window.location).indexOf('#') >= 0) {
                        compare = '#';
                    }
                    var current = window.retrieve('hashchange:current');
                    if (current != compare) {
                        hashchanged(hash,compare);
                    }
    
                    //reset the timer
                    timer = checker.delay(window.retrieve('hashchange:interval'));
                    window.store('hashchange:timer',timer);
                };
            }
    
            //run the loop
            window.store('hashchange:checker',checker);
            checker();
    
            //setup a custom go event
            var sethash = function(hash) {
                var current, url;
                if (hash.charAt(0)!='#')
                    hash = '#' + hash;
                if (Browser.name == 'ie' && Browser.version < 8) {
                    url = new String(window.location);
                    current = url.match(/#.*?$/);
                    current = current && current[0] ? current[0] : '';
                    if (current.length > 0) {
                        window.location = url.replace(current, hash);
                    } else {
                        window.location += hash;
                    }
                } else {
                    //other, more advanced browsers
                    window.location.hash = hash;
                }
    
                //check the hash right away
                if (!window.retrieve('hashchange:implemented')) {
                    window.retrieve('hashchange:checker')();
                }
            };
        
            //check ie browsers
            window.sethash = sethash;
        },
    
        onDelete: function() {
            if (typeOf(this) == 'window') {
                var timer = window.retrieve('hashchange:timer');
                if (timer) {
                    clearTimeout(timer); timer = null;
                    window.store('hashchange:timer',null);
                }
            }
        }
    };
})(document.id,$$);



// json-minified.js

// http://code.google.com/p/json-sans-eval
window.jsonParse=function(){var r="(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)",k='(?:[^\\0-\\x08\\x0a-\\x1f"\\\\]|\\\\(?:["/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';k='(?:"'+k+'*")';var s=new RegExp("(?:false|true|null|[\\{\\}\\[\\]]|"+r+"|"+k+")","g"),t=new RegExp("\\\\(?:([^u])|u(.{4}))","g"),u={'"':'"',"/":"/","\\":"\\",b:"\u0008",f:"\u000c",n:"\n",r:"\r",t:"\t"};function v(h,j,e){return j?u[j]:String.fromCharCode(parseInt(e,16))}var w=new String(""),x=Object.hasOwnProperty;return function(h,
j){h=h.match(s);var e,c=h[0],l=false;if("{"===c)e={};else if("["===c)e=[];else{e=[];l=true}for(var b,d=[e],m=1-l,y=h.length;m<y;++m){c=h[m];var a;switch(c.charCodeAt(0)){default:a=d[0];a[b||a.length]=+c;b=void 0;break;case 34:c=c.substring(1,c.length-1);if(c.indexOf("\\")!==-1)c=c.replace(t,v);a=d[0];if(!b)if(a instanceof Array)b=a.length;else{b=c||w;break}a[b]=c;b=void 0;break;case 91:a=d[0];d.unshift(a[b||a.length]=[]);b=void 0;break;case 93:d.shift();break;case 102:a=d[0];a[b||a.length]=false;
b=void 0;break;case 110:a=d[0];a[b||a.length]=null;b=void 0;break;case 116:a=d[0];a[b||a.length]=true;b=void 0;break;case 123:a=d[0];d.unshift(a[b||a.length]={});b=void 0;break;case 125:d.shift();break}}if(l){if(d.length!==1)throw new Error;e=e[0]}else if(d.length)throw new Error;if(j){var p=function(n,o){var f=n[o];if(f&&typeof f==="object"){var i=null;for(var g in f)if(x.call(f,g)&&f!==n){var q=p(f,g);if(q!==void 0)f[g]=q;else{i||(i=[]);i.push(g)}}if(i)for(g=i.length;--g>=0;)delete f[i[g]]}return j.call(n,
o,f)};e=p({"":e},"")}return e}}();




// SearchTerm.js

var SearchTerm = (function () {
    function SearchTerm(type, display, progid) {
        this.type = "";
        this.displayText = "";
        this.progid = "";
        this.type = type;
        this.displayText = display;
        if (progid) {
            this.progid = progid;
        }
    }
    return SearchTerm;
}());




// trimpath-template-1.0.38.js

/**
 * TrimPath Template. Release 1.0.38.
 * Copyright (C) 2004, 2005 Metaha.
 * 
 * TrimPath Template is licensed under the GNU General Public License
 * and the Apache License, Version 2.0, as follows:
 *
 * This program is free software; you can redistribute it and/or 
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed WITHOUT ANY WARRANTY; without even the 
 * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var TrimPath;

// TODO: Debugging mode vs stop-on-error mode - runtime flag.
// TODO: Handle || (or) characters and backslashes.
// TODO: Add more modifiers.

(function() {               // Using a closure to keep global namespace clean.
    if (TrimPath == null)
        TrimPath = new Object();
    if (TrimPath.evalEx == null)
        TrimPath.evalEx = function(src) { return eval(src); };

    var UNDEFINED;
    if (Array.prototype.pop == null)  // IE 5.x fix from Igor Poteryaev.
        Array.prototype.pop = function() {
            if (this.length === 0) {return UNDEFINED;}
            return this[--this.length];
        };
    if (Array.prototype.push == null) // IE 5.x fix from Igor Poteryaev.
        Array.prototype.push = function() {
            for (var i = 0; i < arguments.length; ++i) {this[this.length] = arguments[i];}
            return this.length;
        };

    TrimPath.parseTemplate = function(tmplContent, optTmplName, optEtc) {
        if (optEtc == null)
            optEtc = TrimPath.parseTemplate_etc;
        var funcSrc = parse(tmplContent, optTmplName, optEtc);
        var func = TrimPath.evalEx(funcSrc, optTmplName, 1);
        if (func != null)
            return new optEtc.Template(optTmplName, tmplContent, funcSrc, func, optEtc);
        return null;
    }
    
    try {
        String.prototype.process = function(context, optFlags) {
            var template = TrimPath.parseTemplate(this, null);
            if (template != null)
                return template.process(context, optFlags);
            return this;
        }
    } catch (e) { // Swallow exception, such as when String.prototype is sealed.
    }
    
    TrimPath.parseTemplate_etc = {};            // Exposed for extensibility.
    TrimPath.parseTemplate_etc.statementTag = "forelse|for|if|elseif|else|var|macro";
    TrimPath.parseTemplate_etc.statementDef = { // Lookup table for statement tags.
        "if"     : { delta:  1, prefix: "if (", suffix: ") {", paramMin: 1 },
        "else"   : { delta:  0, prefix: "} else {" },
        "elseif" : { delta:  0, prefix: "} else if (", suffix: ") {", paramDefault: "true" },
        "/if"    : { delta: -1, prefix: "}" },
        "for"    : { delta:  1, paramMin: 3, 
                     prefixFunc : function(stmtParts, state, tmplName, etc) {
                        if (stmtParts[2] != "in")
                            throw new etc.ParseError(tmplName, state.line, "bad for loop statement: " + stmtParts.join(' '));
                        var iterVar = stmtParts[1];
                        var listVar = "__LIST__" + iterVar;
                        return [ "var ", listVar, " = ", stmtParts[3], ";",
                             // Fix from Ross Shaull for hash looping, make sure that we have an array of loop lengths to treat like a stack.
                             "var __LENGTH_STACK__;",
                             "if (typeof(__LENGTH_STACK__) == 'undefined' || !__LENGTH_STACK__.length) __LENGTH_STACK__ = new Array();", 
                             "__LENGTH_STACK__[__LENGTH_STACK__.length] = 0;", // Push a new for-loop onto the stack of loop lengths.
                             "if ((", listVar, ") != null) { ",
                             "var ", iterVar, "_ct = 0;",       // iterVar_ct variable, added by B. Bittman     
                             listVar, ".each(function(", iterVar, ") { ",
                             
//                             "if (typeof(", listVar, "[", iterVar, "_index]) == 'function') {continue;}", // IE 5.x fix from Igor Poteryaev.
                             "__LENGTH_STACK__[__LENGTH_STACK__.length - 1]++;" ].join("");
                     } },
        "forelse" : { delta:  0, prefix: "} } if (__LENGTH_STACK__[__LENGTH_STACK__.length - 1] == 0) { if (", suffix: ") {", paramDefault: "true" },
        "/for"    : { delta: -1, prefix: "}); }; delete __LENGTH_STACK__[__LENGTH_STACK__.length - 1];" }, // Remove the just-finished for-loop from the stack of loop lengths.
        "var"     : { delta:  0, prefix: "var ", suffix: ";" },
        "macro"   : { delta:  1, 
                      prefixFunc : function(stmtParts, state, tmplName, etc) {
                          var macroName = stmtParts[1].split('(')[0];
                          return [ "var ", macroName, " = function", 
                                   stmtParts.slice(1).join(' ').substring(macroName.length),
                                   "{ var _OUT_arr = []; var _OUT = { write: function(m) { if (m) _OUT_arr.push(m); } }; " ].join('');
                     } }, 
        "/macro"  : { delta: -1, prefix: " return _OUT_arr.join(''); };" }
    }
    TrimPath.parseTemplate_etc.modifierDef = {
        "eat"        : function(v)    { return ""; },
        "escape"     : function(s)    { return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); },
        "capitalize" : function(s)    { return String(s).toUpperCase(); },
        "default"    : function(s, d) { return s != null ? s : d; }
    }
    TrimPath.parseTemplate_etc.modifierDef.h = TrimPath.parseTemplate_etc.modifierDef.escape;

    TrimPath.parseTemplate_etc.Template = function(tmplName, tmplContent, funcSrc, func, etc) {
        this.process = function(context, flags) {
            if (context == null)
                context = {};
            if (context._MODIFIERS == null)
                context._MODIFIERS = {};
            if (context.defined == null)
                context.defined = function(str) { return (context[str] != undefined); };
            for (var k in etc.modifierDef) {
                if (context._MODIFIERS[k] == null)
                    context._MODIFIERS[k] = etc.modifierDef[k];
            }
            if (flags == null)
                flags = {};
            var resultArr = [];
            var resultOut = { write: function(m) { resultArr.push(m); } };
            try {
                func(resultOut, context, flags);
            } catch (e) {
                if (flags.throwExceptions == true)
                    throw e;
                var result = new String(resultArr.join("") + "[ERROR: " + e.toString() + (e.message ? '; ' + e.message : '') + "]");
                result["exception"] = e;
                return result;
            }
            return resultArr.join("");
        }
        this.name       = tmplName;
        this.source     = tmplContent; 
        this.sourceFunc = funcSrc;
        this.toString   = function() { return "TrimPath.Template [" + tmplName + "]"; }
    }
    TrimPath.parseTemplate_etc.ParseError = function(name, line, message) {
        this.name    = name;
        this.line    = line;
        this.message = message;
    }
    TrimPath.parseTemplate_etc.ParseError.prototype.toString = function() { 
        return ("TrimPath template ParseError in " + this.name + ": line " + this.line + ", " + this.message);
    }
    
    var parse = function(body, tmplName, etc) {
        body = cleanWhiteSpace(body);
        var funcText = [ "var TrimPath_Template_TEMP = function(_OUT, _CONTEXT, _FLAGS) { with (_CONTEXT) {" ];
        var state    = { stack: [], line: 1 };                              // TODO: Fix line number counting.
        var endStmtPrev = -1;
        while (endStmtPrev + 1 < body.length) {
            var begStmt = endStmtPrev;
            // Scan until we find some statement markup.
            begStmt = body.indexOf("{", begStmt + 1);
            while (begStmt >= 0) {
                var endStmt = body.indexOf('}', begStmt + 1);
                var stmt = body.substring(begStmt, endStmt);
                var blockrx = stmt.match(/^\{(cdata|minify|eval)/); // From B. Bittman, minify/eval/cdata implementation.
                if (blockrx) {
                    var blockType = blockrx[1]; 
                    var blockMarkerBeg = begStmt + blockType.length + 1;
                    var blockMarkerEnd = body.indexOf('}', blockMarkerBeg);
                    if (blockMarkerEnd >= 0) {
                        var blockMarker;
                        if( blockMarkerEnd - blockMarkerBeg <= 0 ) {
                            blockMarker = "{/" + blockType + "}";
                        } else {
                            blockMarker = body.substring(blockMarkerBeg + 1, blockMarkerEnd);
                        }                        
                        
                        var blockEnd = body.indexOf(blockMarker, blockMarkerEnd + 1);
                        if (blockEnd >= 0) {                            
                            emitSectionText(body.substring(endStmtPrev + 1, begStmt), funcText);
                            
                            var blockText = body.substring(blockMarkerEnd + 1, blockEnd);
                            if (blockType == 'cdata') {
                                emitText(blockText, funcText);
                            } else if (blockType == 'minify') {
                                emitText(scrubWhiteSpace(blockText), funcText);
                            } else if (blockType == 'eval') {
                                if (blockText != null && blockText.length > 0) // From B. Bittman, eval should not execute until process().
                                    funcText.push('_OUT.write( (function() { ' + blockText + ' })() );');
                            }
                            begStmt = endStmtPrev = blockEnd + blockMarker.length - 1;
                        }
                    }                        
                } else if (body.charAt(begStmt - 1) != '$' &&               // Not an expression or backslashed,
                           body.charAt(begStmt - 1) != '\\') {              // so check if it is a statement tag.
                    var offset = (body.charAt(begStmt + 1) == '/' ? 2 : 1); // Close tags offset of 2 skips '/'.
                                                                            // 10 is larger than maximum statement tag length.
                    if (body.substring(begStmt + offset, begStmt + 10 + offset).search(TrimPath.parseTemplate_etc.statementTag) == 0) 
                        break;                                              // Found a match.
                }
                begStmt = body.indexOf("{", begStmt + 1);
            }
            if (begStmt < 0)                              // In "a{for}c", begStmt will be 1.
                break;
            var endStmt = body.indexOf("}", begStmt + 1); // In "a{for}c", endStmt will be 5.
            if (endStmt < 0)
                break;
            emitSectionText(body.substring(endStmtPrev + 1, begStmt), funcText);
            emitStatement(body.substring(begStmt, endStmt + 1), state, funcText, tmplName, etc);
            endStmtPrev = endStmt;
        }
        emitSectionText(body.substring(endStmtPrev + 1), funcText);
        if (state.stack.length != 0)
            throw new etc.ParseError(tmplName, state.line, "unclosed, unmatched statement(s): " + state.stack.join(","));
        funcText.push("}}; TrimPath_Template_TEMP");
        return funcText.join("");
    }
    
    var emitStatement = function(stmtStr, state, funcText, tmplName, etc) {
        var parts = stmtStr.slice(1, -1).split(' ');
        var stmt = etc.statementDef[parts[0]]; // Here, parts[0] == for/if/else/...
        if (stmt == null) {                    // Not a real statement.
            emitSectionText(stmtStr, funcText);
            return;
        }
        if (stmt.delta < 0) {
            if (state.stack.length <= 0)
                throw new etc.ParseError(tmplName, state.line, "close tag does not match any previous statement: " + stmtStr);
            state.stack.pop();
        } 
        if (stmt.delta > 0)
            state.stack.push(stmtStr);

        if (stmt.paramMin != null &&
            stmt.paramMin >= parts.length)
            throw new etc.ParseError(tmplName, state.line, "statement needs more parameters: " + stmtStr);
        if (stmt.prefixFunc != null)
            funcText.push(stmt.prefixFunc(parts, state, tmplName, etc));
        else 
            funcText.push(stmt.prefix);
        if (stmt.suffix != null) {
            if (parts.length <= 1) {
                if (stmt.paramDefault != null)
                    funcText.push(stmt.paramDefault);
            } else {
                for (var i = 1; i < parts.length; i++) {
                    if (i > 1)
                        funcText.push(' ');
                    funcText.push(parts[i]);
                }
            }
            funcText.push(stmt.suffix);
        }
    }

    var emitSectionText = function(text, funcText) {
        if (text.length <= 0)
            return;
        var nlPrefix = 0;               // Index to first non-newline in prefix.
        var nlSuffix = text.length - 1; // Index to first non-space/tab in suffix.
        while (nlPrefix < text.length && (text.charAt(nlPrefix) == '\n'))
            nlPrefix++;
        while (nlSuffix >= 0 && (text.charAt(nlSuffix) == ' ' || text.charAt(nlSuffix) == '\t'))
            nlSuffix--;
        if (nlSuffix < nlPrefix)
            nlSuffix = nlPrefix;
        if (nlPrefix > 0) {
            funcText.push('if (_FLAGS.keepWhitespace == true) _OUT.write("');
            var s = text.substring(0, nlPrefix).replace('\n', '\\n'); // A macro IE fix from BJessen.
            if (s.charAt(s.length - 1) == '\n')
            	s = s.substring(0, s.length - 1);
            funcText.push(s);
            funcText.push('");');
        }
        var lines = text.substring(nlPrefix, nlSuffix + 1).split('\n');
        for (var i = 0; i < lines.length; i++) {
            emitSectionTextLine(lines[i], funcText);
            if (i < lines.length - 1)
                funcText.push('_OUT.write("\\n");\n');
        }
        if (nlSuffix + 1 < text.length) {
            funcText.push('if (_FLAGS.keepWhitespace == true) _OUT.write("');
            var s = text.substring(nlSuffix + 1).replace('\n', '\\n');
            if (s.charAt(s.length - 1) == '\n')
            	s = s.substring(0, s.length - 1);
            funcText.push(s);
            funcText.push('");');
        }
    }
    
    var emitSectionTextLine = function(line, funcText) {
        var endMarkPrev = '}';
        var endExprPrev = -1;
        while (endExprPrev + endMarkPrev.length < line.length) {
            var begMark = "${", endMark = "}";
            var begExpr = line.indexOf(begMark, endExprPrev + endMarkPrev.length); // In "a${b}c", begExpr == 1
            if (begExpr < 0)
                break;
            if (line.charAt(begExpr + 2) == '%') {
                begMark = "${%";
                endMark = "%}";
            }
            var endExpr = line.indexOf(endMark, begExpr + begMark.length);         // In "a${b}c", endExpr == 4;
            if (endExpr < 0)
                break;
            emitText(line.substring(endExprPrev + endMarkPrev.length, begExpr), funcText);                
            // Example: exprs == 'firstName|default:"John Doe"|capitalize'.split('|')
            var exprArr = line.substring(begExpr + begMark.length, endExpr).replace(/\|\|/g, "#@@#").split('|');
            for (var k in exprArr) {
                if (exprArr[k].replace) // IE 5.x fix from Igor Poteryaev.
                    exprArr[k] = exprArr[k].replace(/#@@#/g, '||');
            }
            funcText.push('_OUT.write(');
            emitExpression(exprArr, exprArr.length - 1, funcText); 
            funcText.push(');');
            endExprPrev = endExpr;
            endMarkPrev = endMark;
        }
        emitText(line.substring(endExprPrev + endMarkPrev.length), funcText); 
    }
    
    var emitText = function(text, funcText) {
        if (text == null ||
            text.length <= 0)
            return;
        text = text.replace(/\\/g, '\\\\');
        text = text.replace(/\n/g, '\\n');
        text = text.replace(/"/g,  '\\"');
        funcText.push('_OUT.write("');
        funcText.push(text);
        funcText.push('");');
    }
    
    var emitExpression = function(exprArr, index, funcText) {
        // Ex: foo|a:x|b:y1,y2|c:z1,z2 is emitted as c(b(a(foo,x),y1,y2),z1,z2)
        var expr = exprArr[index]; // Ex: exprArr == [firstName,capitalize,default:"John Doe"]
        if (index <= 0) {          // Ex: expr    == 'default:"John Doe"'
            funcText.push(expr);
            return;
        }
        var parts = expr.split(':');
        funcText.push('_MODIFIERS["');
        funcText.push(parts[0]); // The parts[0] is a modifier function name, like capitalize.
        funcText.push('"](');
        emitExpression(exprArr, index - 1, funcText);
        if (parts.length > 1) {
            funcText.push(',');
            funcText.push(parts[1]);
        }
        funcText.push(')');
    }

    var cleanWhiteSpace = function(result) {
        result = result.replace(/\t/g,   "    ");
        result = result.replace(/\r\n/g, "\n");
        result = result.replace(/\r/g,   "\n");
        result = result.replace(/^(\s*\S*(\s+\S+)*)\s*$/, '$1'); // Right trim by Igor Poteryaev.
        return result;
    }

    var scrubWhiteSpace = function(result) {
        result = result.replace(/^\s+/g,   "");
        result = result.replace(/\s+$/g,   "");
        result = result.replace(/\s+/g,   " ");
        result = result.replace(/^(\s*\S*(\s+\S+)*)\s*$/, '$1'); // Right trim by Igor Poteryaev.
        return result;
    }

    // The DOM helper functions depend on DOM/DHTML, so they only work in a browser.
    // However, these are not considered core to the engine.
    //
    TrimPath.parseDOMTemplate = function(elementId, optDocument, optEtc) {
        if (optDocument == null)
            optDocument = document;
        var element = optDocument.getElementById(elementId);
        var content = "";
		if (element != null) 
			content = element.value;     // Like textarea.value.
        if (((content == null) || (content == "")) && (element != null))
            content = element.innerHTML; // Like textarea.innerHTML.
        if (content == "" || content == null)
        {
            content = document[elementId];
            content = content.replace(/[\r\n]/g,"");
        }
        content = content		
								.replace(/&amp;/g, '&')
								.replace(/&lt;/g, "<")
								.replace(/&gt;/g, ">");

        return TrimPath.parseTemplate(content, elementId, optEtc);
    }

    TrimPath.processDOMTemplate = function(elementId, context, optFlags, optDocument, optEtc) {
        return TrimPath.parseDOMTemplate(elementId, optDocument, optEtc).process(context, optFlags);
    }
}) ();




// SearchCmdsDesktop.js

//xnclude "../lib/trimpath/trimpath-template-1.0.38.js"
//xnclude "SearchTerm.js"
/// <reference path="../mootools.d.ts" />
/// <reference path="../Common.d.ts" />
/// <reference path="SearchTerm.ts" />
/// <reference path="../DefaultText.ts" />
/// <reference path="../feature/ItemCollection.ts" />
/// <reference path="ISearchCmds.d.ts" />
var SearchTermCollectionDesktop = (function () {
    function SearchTermCollectionDesktop(p) {
        this.termAry = [];
        this.parent = p;
    }
    SearchTermCollectionDesktop.prototype.assignTerms = function (fromJson) {
        this.termAry = fromJson;
    };
    SearchTermCollectionDesktop.prototype.clear = function () {
        this.termAry = [];
    };
    SearchTermCollectionDesktop.prototype.makeUrlArgs = function () {
        var args = '';
        for (var i = 0; i < this.termAry.length; ++i) {
            var term = this.termAry[i];
            // note: term.text is already encoded as a URI component (we're taking it off the URL)
            args = args + '&' + term.type + i + '=' + term.displayText;
        }
        return args;
    };
    SearchTermCollectionDesktop.prototype.addTerm = function (type, dispText) {
        var newTerm = new SearchTerm(type, dispText);
        this.termAry.push(newTerm);
    };
    SearchTermCollectionDesktop.prototype.updateSearchTermsDisplay = function (container) {
        if (container == null) {
            return;
        }
        container = q$(container);
        container.set('html', '');
        for (var i = 0; i < this.termAry.length; ++i) {
            var term = this.termAry[i];
            var labelElem = q$(document.createElement('span'));
            labelElem.className = 'criterion';
            labelElem.set('html', term.displayText);
            container.appendChild(labelElem);
            var xButton = q$(document.createElement('span'));
            xButton.className = 'removeKeywordButton';
            xButton.setAttribute('key', term.progid);
            xButton.setAttribute('type', term.type);
            xButton.addEvent('click', this.parent.removeTermFromCriteria.bind(this.parent));
            container.appendChild(xButton);
        }
    };
    return SearchTermCollectionDesktop;
}());
var SearchCmdsDesktop = (function () {
    function SearchCmdsDesktop() {
        this.dfgid = 0;
        this.total = 0;
        this.displayCount = 20;
        this.unloaded = false;
        this.sortColumn = 0;
        this.sortAttributes = ['relevance', 'startingTimestamp', 'rating', 'commentSort', 'lastCommentTimestamp'];
        this.searchTermColl = new SearchTermCollectionDesktop(this);
        this.searchEventID = 0;
        this.selectedScore = -1;
        this.jst = null;
        this.deviceClass = "";
        // Use 'hashchange' event as signal that search term has changed and to trigger search
        window.addEvent('hashchange', this.requestSearchResults.bind(this));
        AfterStartupEvents.registerAfterStartup(this.requestSearchResults.bind(this));
    }
    SearchCmdsDesktop.prototype.ResetState = function (url) {
        this.sortColumn = 0;
        this.searchTermColl = new SearchTermCollectionDesktop(this);
        //SearchResultsDesktop.saveSearchState(); // missing jjm
        if (url) {
            document.location.href = url;
        }
    };
    SearchCmdsDesktop.prototype.requestSearchResults = function () {
        if (typeof PageHeader != 'undefined')
            PageHeader.closeAllMenus();
        var args = this.makeArgsFromTerms();
        var url = '/searchResults?bc=' + DateUtils.msNow() + args;
        var elt = q$('drilldownResultListing');
        var self = this;
        Common.fadeToOpacity(elt, 0, 100, function () {
            self.showSpinner();
            Ajax.getText(url, self.updateContents.bind(self), Common.doNothing);
        });
    };
    SearchCmdsDesktop.prototype.makeTermsFromUrl = function () {
        var parts = [];
        var url = location.href;
        if (url.indexOf('#') > -1)
            parts = url.split('#');
        else if (url.indexOf('?') > -1)
            parts = url.split('?');
        var hash = '';
        if (parts.length > 1) {
            hash = parts[1];
        }
        this.searchTermColl.clear();
        parts = hash.split('&');
        for (var i = 0; i < parts.length; ++i) {
            // each part is like s0=term or kw1=term
            var part = parts[i];
            if (part == '') {
                continue;
            }
            var term = part.split('=');
            var termType = "";
            if (term[0].match('^s[0-9]*$') != null) {
                termType = 's';
            }
            else if (term[0].match('^kw')) {
                termType = 'kw';
            }
            else {
                continue;
            }
            this.searchTermColl.addTerm(termType, term[1]);
        }
    };
    SearchCmdsDesktop.prototype.makeArgsFromTerms = function () {
        this.makeTermsFromUrl();
        return this.searchTermColl.makeUrlArgs();
    };
    SearchCmdsDesktop.prototype.fillTable = function () {
        if (this.jst == null)
            this.jst = TrimPath.parseDOMTemplate("search_jst");
        var total = this.divs.length;
        if (total > this.displayCount)
            total = this.displayCount;
        var dataformTable = q$('tableData');
        if (dataformTable) {
            dataformTable.set('html', '');
            var tempDiv = q$(document.createElement('table'));
            for (var index = 0; index < total; ++index) {
                var model = this.divs[index];
                var html = this.jst.process(model);
                tempDiv.set('html', html);
                var newElements = tempDiv.getElementsByTagName('tr');
                if (newElements != null) {
                    for (var i = 0; i < newElements.length; ++i) {
                        dataformTable.adopt(newElements[i]);
                    }
                }
            }
        }
        var strValue;
        if (this.total == 1)
            strValue = QSTR.oneResult;
        else if (this.total <= this.displayCount)
            strValue = sprintf(QSTR.keywordCategoryResults, this.total);
        else
            strValue = sprintf(QSTR.showingNofM, this.displayCount, this.total);
        var totalElement = q$('resultsCount');
        if (totalElement)
            totalElement.innerHTML = strValue;
    };
    ;
    SearchCmdsDesktop.prototype.updateContents = function (text) {
        // get this if we navigate off the page while waiting
        if (text == '')
            return;
        var parsedData = null;
        try {
            parsedData = Common.jsonParse(text);
        }
        catch (e) {
            alert("Error parsing search results");
            return;
        }
        var seachResultsElt = q$('qSearchResults');
        if (seachResultsElt)
            seachResultsElt.set('html', parsedData.html);
        else
            alert("missing element: qSearchResults");
        this.deviceClass = parsedData.deviceClass;
        this.divs = parsedData.divs;
        this.total = this.divs.length;
        this.searchTermColl.assignTerms(parsedData.terms);
        this.searchEventID = parsedData.searchEventID;
        this.fillTable();
        this.updateMoreResultsButton();
        this.updateSearchTermsDisplay();
        this.hideSpinner();
        var dataformTable = q$('dataformTable');
        if (dataformTable && this.deviceClass == 'web') {
            PopupPreview.Update(dataformTable);
        }
        this.addHandler();
        DefaultText.addTextChangeFunctions();
        DelayedBackground.loadImages();
        if (typeof ItemCollection != 'undefined')
            ItemCollection.setSize();
        var elt = q$('drilldownResultListing');
        Common.fadeToOpacity(elt, 1.0, 250);
    };
    SearchCmdsDesktop.prototype.showSpinner = function () {
        q$('innerBodyContainer').addClass('waiting');
    };
    SearchCmdsDesktop.prototype.hideSpinner = function () {
        q$('innerBodyContainer').removeClass('waiting');
    };
    SearchCmdsDesktop.prototype.updateMoreResultsButton = function () {
        var button = document.getElementById('showMoreButton');
        Common.cShowOrHide(button, this.total > this.displayCount);
    };
    ;
    SearchCmdsDesktop.prototype.updateSearchTermsDisplay = function () {
        this.searchTermColl.updateSearchTermsDisplay(document.getElementById('criteriaList'));
    };
    SearchCmdsDesktop.prototype.addHandler = function () {
        var searchBox = q$('additionalSearchRequest');
        if (searchBox) {
            searchBox.removeEvents('keyup');
            searchBox.addEvent('keyup', this.keyHandler.bind(this));
        }
        var goSearch = q$('goSearch');
        if (goSearch) {
            goSearch.removeEvents('click');
            goSearch.addEvent('click', this.addUserEnteredTerm);
        }
    };
    SearchCmdsDesktop.prototype.keyHandler = function (evt) {
        var keyPressed = evt.key;
        if (keyPressed == 'enter') {
            this.addUserEnteredTerm(evt);
        }
    };
    SearchCmdsDesktop.prototype.showMoreResults = function () {
        this.displayCount += 20;
        this.fillTable();
        this.updateMoreResultsButton();
        var dataformTable = q$('dataformTable');
        if (dataformTable && this.deviceClass == 'web')
            PopupPreview.Update(dataformTable);
        DefaultText.addTextChangeFunctions();
        DelayedBackground.loadImages();
    };
    SearchCmdsDesktop.prototype.setDfgid = function (dfgid, score) {
        this.dfgid = dfgid;
        this.selectedScore = score;
    };
    /**
     * Some kinds of dataforms replace the search page in-situ, others
     * open a new browser tab (i.e. Urls as Dataform)
     */
    SearchCmdsDesktop.prototype.causesUnload = function (ns) {
        return (ns != 'dataform:url');
    };
    SearchCmdsDesktop.prototype.trackSearchResultClick = function (dfid, ns, goToUrl) {
        if (this.deviceClass != 'web')
            return;
        if (this.causesUnload(ns)) {
            this.unloaded = true;
        }
        var xmlDoc = XML.CreateDocument('<search_action></search_action>');
        var searchElt = xmlDoc.documentElement;
        var queryElt = xmlDoc.createElement('query');
        var url = location.href;
        var parts = url.split('#');
        var hash = '';
        if (parts.length > 1)
            hash = parts[1];
        var inner = xmlDoc.createTextNode(hash);
        queryElt.appendChild(inner);
        searchElt.appendChild(queryElt);
        searchElt.setAttribute('search_event_id', "" + this.searchEventID);
        searchElt.setAttribute('selected_score', this.selectedScore);
        searchElt.setAttribute('dfgid', "" + this.dfgid);
        searchElt.setAttribute('total_results', "" + this.total);
        /* bug 3264: Chrome doesn't let us open a new page to an external page via script from a callback.
         Touchy, touchy.  Okay...  do tracking in onbeforeuload and just go to external url not via callback.
         */
        window.addEvent('beforeunload', function () {
            Ajax.postAsXml(QSettings.postUrl(), xmlDoc, Common.doNothing, Common.doNothing);
        });
        if (goToUrl.indexOf('/player/') == 0)
            theAppIFace.viewDataform(dfid, ns, false, null, goToUrl, 'SearchResultsDesktop');
        else if (Common.isExternalUrl(goToUrl))
            Common.viewExternalPage(goToUrl, dfid, 'SearchResultsDesktop');
        else
            Common.viewInternalPage(goToUrl, 'SearchResultsDesktop');
    };
    SearchCmdsDesktop.prototype.updateHash = function (hashToSet) {
        var indexOfHash = hashToSet.indexOf('#');
        var hash = hashToSet;
        if (indexOfHash > -1) {
            hash = hashToSet.substring(indexOfHash + 1);
        }
        //
        // this is define by another class
        //
        window.sethash(hash);
    };
    SearchCmdsDesktop.prototype.addKeyword = function (keyword) {
        var url = location.href;
        var parts = url.split('#');
        var hash = '';
        if (parts.length > 1)
            hash = parts[1];
        var index = hash.split('&').length;
        var separator = '&';
        hash = hash + separator + 'kw' + index + '=' + keyword;
        this.updateHash(hash);
    };
    SearchCmdsDesktop.prototype.updateKeywords = function (eltID) {
        var selectElem = document.getElementById(eltID);
        // let dirty = SearchResultsDesktop.searchTermColl.addKeyword(selectElem);
        // if (dirty)
        this.requestSearchResults();
    };
    SearchCmdsDesktop.prototype.addUserEnteredTerm = function (evt) {
        if (evt)
            evt.stop();
        var term = q$('additionalSearchRequest').value;
        if (term == '' || term == QSTR.searchWithin || term == QSTR.headerSearchBox /* default text good as empty */)
            return;
        var url = location.href;
        var parts = url.split('#');
        var index = 0;
        var hash = '';
        if (parts.length > 1) {
            hash = parts[1];
            parts = hash.split('&');
            index = parts.length;
        }
        var separator = '&';
        var arg = this.buildSearchTerm(term, index);
        var found = false;
        for (var i = 0; i < index; ++i) {
            if (parts[i] == this.buildSearchTerm(term, i))
                found = true;
        }
        if (!found) {
            hash = hash + separator + arg;
            this.updateHash(hash);
        }
    };
    SearchCmdsDesktop.prototype.buildSearchTerm = function (term, index) {
        return 's' + index + '=' + encodeURIComponent(term);
    };
    SearchCmdsDesktop.prototype.startOver = function () {
        if (this.deviceClass != 'web') {
            document.location.href = QSettings.getSearchUrl();
        }
        else {
            this.updateHash('');
        }
    };
    SearchCmdsDesktop.prototype.removeTermFromCriteria = function (evt) {
        if (this.deviceClass != 'web') {
            document.location.href = QSettings.getSearchUrl();
            return;
        }
        var elem = evt.target;
        var key = encodeURIComponent(elem.attributes['key'].nodeValue);
        var type = elem.attributes['type'].nodeValue;
        var url = location.href;
        var parts = url.split('#');
        var hash = parts[1];
        var args = hash.split('&');
        hash = '';
        for (var index = 0; index < args.length; ++index) {
            var arg = args[index];
            if (arg == '')
                continue;
            var keyval = arg.split('=');
            var argName = keyval[0];
            var argValue = keyval[1];
            if (argName.indexOf(type) == 0) {
                if (argValue == key)
                    continue;
            }
            var newPrefix = (argName.indexOf('kw') == 0) ? 'kw' : 's';
            hash = hash + newPrefix + index + '=' + argValue + '&';
        }
        var len = hash.length;
        if (hash.charAt(len - 1) == '&')
            hash = hash.substring(0, len - 1);
        this.updateHash(hash);
    };
    SearchCmdsDesktop.prototype.resort = function () {
        var ss = document.getElementById('sortSelect');
        var selectedIndex = ss.selectedIndex;
        var o = ss.options[selectedIndex];
        this.sortColumn = o.value;
        this.resortByColumn();
    };
    SearchCmdsDesktop.prototype.resortByColumn = function () {
        var which = this.sortColumn;
        var sortAttribute = this.sortAttributes[which];
        var dataformTable = q$('tableData');
        var allItems = [];
        for (var i = 0; i < this.total; ++i) {
            allItems[i] = q$("result" + i);
            if (allItems[i])
                dataformTable.removeChild(allItems[i]);
        }
        var direction = 1; // highest to lowest
        if (which == 0)
            direction = -1; // lowest to highest
        this.divs.sort(function (a, b) {
            return Common.genericCompare(sortAttribute, direction, a, b);
        });
        this.fillTable();
        DelayedBackground.loadImages();
        if (dataformTable && this.deviceClass == 'web')
            PopupPreview.Update(dataformTable);
    };
    SearchCmdsDesktop.prototype.startDiscussion = function () {
        location.href = '/newPublicDiscussion';
    };
    return SearchCmdsDesktop;
}());

//include "../lib/trimpath/trimpath-template-1.0.38.js"
//include "SearchTerm.js"



// uJST.js

/*
 * (c)2018 Univadis
 * a micro-template-language evaluator for mobile
 * (we don't want to download a full templating engine)
 * implements ${subst_expression} and {if expr}...{/if}
 * {if}'s can nest.
 *
 * The supported subset of JST grammer we support is:
 * Template         := TemplateExpr Template | empty
 * TemplateExpr     := IfExpr Template CloseIf | StringWithSubs
 * StringWithSubs   := PlainString OptionalSubst
 * OptionalSubst	:= OpenBrace ModelRef CloseBrace StringWithSubs | empty
 * PlainString		:= any characters that aren't part of a JST expression
 * IfExpr           := {if javascript_expr}
 * CloseIf          := {/if}
 *
 */
// Simple variable substitutions
var StringWithSubst = (function () {
    function StringWithSubst(template) {
        this.results = null;
        this.error = null;
        this.results = template.split("${");
        for (var i = 0; i < this.results.length; ++i) {
            var line = this.results[i];
            this.results[i] = line.split("}");
        }
        return this;
    }
    StringWithSubst.prototype.evaluate = function (dataModel) {
        var results = [];
        for (var i = 0; i < this.results.length; ++i) {
            var lines = this.results[i];
            if (lines.length == 1) {
                results[i] = lines[0];
            }
            else {
                with (dataModel) {
                    results[i] = eval(lines[0]) + lines[1];
                }
            }
        }
        return results.join("");
    };
    return StringWithSubst;
}());
var QMicroTemplateExpr = (function () {
    function QMicroTemplateExpr(str) {
        this.length = 0;
        this.error = null;
        this.stringWithSubst = null;
        this.expr = null;
        this.innerTemplate = null;
        this.length = 0;
        this.error = null;
        this.stringWithSubst = null;
        this.expr = null;
        this.innerTemplate = null;
        if (!str) {
            this.error = 'Unexpected empty string in TemplateExpr';
            return (this);
        }
        // find first and last {if}{/if} and recurse
        var openIf = str.indexOf('{if');
        if (openIf === 0) {
            // starts with {if expr}...
            // get ifexpr
            var closeIfOffset = str.indexOf('}', openIf);
            if (closeIfOffset == -1) {
                this.error = 'Unclosed {if';
                return this;
            }
            this.expr = str.substring(openIf + 4, closeIfOffset);
            str = str.substring(closeIfOffset + 1);
            this.innerTemplate = new QMicroTemplate(str); // parses up to the closing {/if}
            this.error = this.innerTemplate.error;
            /*  len of expr = (the length up to the end of the expr) + (the length of the inner Template) + (the length of the trailing {/if}) */
            if (str.substr(this.innerTemplate.length, 5) == '{/if}')
                this.length = (closeIfOffset + 1) + (this.innerTemplate.length) + 5;
            else
                this.error = 'No closing {/if}';
        }
        else {
            // else it's a StringWithSubs with (possibly) a following ifexpr
            var len = str.length;
            var closeIf = str.indexOf('{/if}');
            if (closeIf == -1)
                closeIf = len;
            if (openIf == -1)
                openIf = len;
            len = Math.min(openIf, closeIf);
            str = str.substring(0, len);
            this.stringWithSubst = new StringWithSubst(str);
            this.error = this.stringWithSubst.error;
            this.length = len;
        }
        return this;
    }
    QMicroTemplateExpr.prototype.evaluate = function (dataModel) {
        if (this.stringWithSubst)
            return this.stringWithSubst.evaluate(dataModel);
        if (this.innerTemplate) {
            with (dataModel) {
                var isTrue = eval(this.expr);
                if (isTrue)
                    return this.innerTemplate.evaluate(dataModel);
                else
                    return '';
            }
        }
    };
    return QMicroTemplateExpr;
}());
var QMicroTemplate = (function () {
    function QMicroTemplate(template) {
        this.error = null;
        this.length = 0;
        this.templateExpr = null;
        this.followingTemplate = null;
        this.error = null;
        this.length = 0;
        if (!template)
            return this;
        this.templateExpr = new QMicroTemplateExpr(template);
        if (this.templateExpr.error) {
            this.error = this.templateExpr.error;
        }
        else if (this.templateExpr.length > 0) {
            // if not at the end already
            template = template.substring(this.templateExpr.length); // take all the characters following the expr
            this.followingTemplate = new QMicroTemplate(template);
            this.length = this.templateExpr.length + this.followingTemplate.length;
            this.error = this.followingTemplate.error;
        }
        return this;
    }
    QMicroTemplate.prototype.isEmpty = function () {
        return this.length === 0;
    };
    QMicroTemplate.prototype.evaluate = function (dataModel) {
        if (this.error) {
            alert("Error parsing template: " + this.error);
            return '';
        }
        try {
            if (this.isEmpty())
                return '';
            var results = this.templateExpr.evaluate(dataModel);
            if (this.followingTemplate)
                results = results + this.followingTemplate.evaluate(dataModel);
            return results;
        }
        catch (e) {
            alert("Error evaluating template: " + e.toString());
            return "";
        }
    };
    return QMicroTemplate;
}());




// SearchCmdsMobile.js

//xnclude "../uJST.js"
//xnclude "SearchTerm.js"
//xnclude "../QUtils.js"
/// <reference path="../mootools.d.ts" />
/// <reference path="../Common.d.ts" />
/// <reference path="SearchTerm.ts" />
/// <reference path="../MobileDelayedBg.ts" />
/// <reference path="../AfterStartupEvents.ts" />
/// <reference path="../uJST.ts" />
/// <reference path="ISearchCmds.d.ts" />
var SearchTermCollectionMobile = (function () {
    function SearchTermCollectionMobile(srcAry, p) {
        this.termAry = []; // should contain SearchTermMobile items
        this.parent = p;
        var tempThis = this;
        /*Tempo removed because  it takes time for the new instance of SearchTermCollectionMobile to reflect the value of  termAry.
        * This behavior causes the instructions following the SearchTermCollectionMobile instantiation to not have the actual value of termAry, so the search context is not retrieved   */
        //setTimeout(function () {
        if (!srcAry || srcAry.length == 0) {
            srcAry = Pageparams.initialSearchTerms;
        }
        tempThis.assignTerms(srcAry);
        //}, 10);
    }
    SearchTermCollectionMobile.prototype.clear = function () {
        this.termAry = [];
    };
    SearchTermCollectionMobile.prototype.assignTerms = function (fromJson) {
        if (fromJson)
            this.termAry = fromJson;
        else
            this.termAry = [];
    };
    SearchTermCollectionMobile.prototype.makeArgsFromTerms = function () {
        var args = '';
        if (this.termAry) {
            for (var i = 0; i < this.termAry.length; ++i) {
                var term = this.termAry[i];
                var progid = term.progid;
                if (progid == null || progid == '') {
                    progid = encodeURIComponent(term.displayText);
                }
                args = args + '&' + term.type + i + '=' + progid;
            }
        }
        return args;
    };
    SearchTermCollectionMobile.prototype.addTerm = function (type, dispText) {
        var newTerm = new SearchTerm(type, dispText);
        this.termAry.push(newTerm);
    };
    SearchTermCollectionMobile.prototype.addUserEnteredTerm = function (userEnteredTerm) {
        for (var i = 0; i < this.termAry.length; ++i) {
            // ignore terms already in list
            var oneTerm = this.termAry[i];
            if (oneTerm.displayText == userEnteredTerm)
                return false;
        }
        var newTerm = new SearchTerm('s', userEnteredTerm, userEnteredTerm);
        this.termAry.push(newTerm);
        return true;
    };
    SearchTermCollectionMobile.removeCountFromText = function (t) {
        if (t) {
            if (t.indexOf(' (') > -1)
                t = t.substring(0, t.indexOf(' ('));
        }
        return t;
    };
    SearchTermCollectionMobile.prototype.isInColl = function (st) {
        for (var i = 0; i < this.termAry.length; ++i) {
            var oneTerm = this.termAry[i];
            if (oneTerm.progid == st.progid && oneTerm.type == st.type)
                return true;
        }
        return false;
    };
    SearchTermCollectionMobile.prototype.addKeyword = function (selectionCtrl) {
        var dirty = false;
        for (var index = 0; index < selectionCtrl.options.length; ++index) {
            if (selectionCtrl.options[index].selected) {
                var progid = selectionCtrl.options[index].value;
                var displayText = SearchTermCollectionMobile.removeCountFromText(selectionCtrl.options[index].text);
                if (displayText) {
                    var term = new SearchTerm('kw', displayText, progid);
                    if (!this.isInColl(term)) {
                        this.termAry.push(term);
                        dirty = true;
                    }
                }
            }
        }
        return dirty;
    };
    SearchTermCollectionMobile.prototype.removeTerm = function (progid, type) {
        var newTerms = [];
        for (var i = 0; i < this.termAry.length; ++i) {
            var oneTerm = this.termAry[i];
            if (oneTerm.progid == progid && oneTerm.type == type)
                continue;
            newTerms.push(oneTerm);
        }
        this.termAry = newTerms;
    };
    SearchTermCollectionMobile.prototype.updateSearchTermsDisplay = function (container) {
        if (container == null)
            return;
        container.innerHTML = '';
        for (var i = 0; i < this.termAry.length; ++i) {
            var term = this.termAry[i];
            var searchTermElem = document.createElement('div');
            searchTermElem.className = 'searchTerm';
            var newChild = document.createElement('div');
            newChild.className = 'removeKeywordButton';
            newChild.setAttribute('key', term.progid);
            newChild.setAttribute('type', term.type);
            newChild.addEventListener('click', this.parent.removeTermFromCriteria.bind(this.parent));
            searchTermElem.appendChild(newChild);
            var textChild = document.createElement('div');
            var disptext = term.displayText;
            if (term.type == 's')
                disptext = '"' + disptext + '"';
            if (i > 0)
                disptext = "+ " + disptext;
            var textNode = document.createTextNode(disptext);
            textChild.appendChild(textNode);
            searchTermElem.appendChild(textChild);
            container.appendChild(searchTermElem);
        }
    };
    return SearchTermCollectionMobile;
}());
var SavedSearchState = (function () {
    function SavedSearchState(termsAry, sc) {
        this.terms = termsAry || [];
        this.sortColumn = sc || 0;
    }
    SavedSearchState.prototype.save = function () {
        if (PageFlavor.isMoBr())
            this.saveViaCookie();
        else
            this.saveViaAppSetting();
    };
    SavedSearchState.retrieve = function (onRetrieval) {
        // async
        if (PageFlavor.isMoBr())
            SavedSearchState.getViaCookie(onRetrieval);
        else
            SavedSearchState.getViaAppSetting(onRetrieval);
    };
    // ios uses app_setting
    SavedSearchState.getViaAppSetting = function (onRetrieval) {
        theAppIFace.getSettingAsync('searchState', function (savedState) {
            var decodedState = new SavedSearchState(null, null);
            if (savedState != '') {
                var xx = decodeURIComponent(savedState);
                decodedState = JSON.decode(xx);
            }
            onRetrieval(decodedState);
        });
    };
    SavedSearchState.prototype.saveViaAppSetting = function () {
        theAppIFace.setSetting('searchState', encodeURIComponent(JSON.encode(this)));
    };
    // android uses cookie
    SavedSearchState.prototype.saveViaCookie = function () {
        var date = new Date();
        date.setTime(date.getTime() + (-1) * (24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toUTCString();
        document.cookie = "searchState" + "=" + "" + expires + "; path=/";
        var strData = JSON.encode(this);
        document.cookie = 'searchState=' + encodeURIComponent(strData);
    };
    ;
    SavedSearchState.getViaCookie = function (onRetrievalFunc) {
        var decodedState = new SavedSearchState(null, null);
        var leadingString = 'searchState=';
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; ++i) {
            var cc = cookies[i];
            // find leading string as leading *proper* substring
            if ((cc.indexOf(leadingString)) > -1 && (cc != leadingString)) {
                var index = cc.indexOf('=');
                if (index == cc.length)
                    break;
                var value = cc.substring(index + 1);
                value = decodeURIComponent(value);
                decodedState = JSON.decode(value);
                break;
            }
        }
        onRetrievalFunc(decodedState);
    };
    return SavedSearchState;
}());
var SearchCmdsMobile = (function () {
    function SearchCmdsMobile() {
        this.dfgid = 0;
        this.total = 0;
        this.displayCount = 20;
        this.unloaded = false;
        this.sortColumn = 0;
        this.searchEventID = 0;
        this.selectedScore = -1;
        this.jst = null;
        this.deviceClass = "";
        this.searchTermColl = new SearchTermCollectionMobile(null, this);
        addEventListener('keydown', this.keydownHandler.bind(this));
        AfterStartupEvents.registerAfterStartup(this.reloadAndRquestSearchResult.bind(this));
    }
    SearchCmdsMobile.prototype.keydownHandler = function (e) {
        // SearchCmd not yet instantiated, but should
        if (!SearchCmds)
            return;
        var searchBox = q$('search');
        if (!searchBox)
            return;
        if ((e.keyCode == 13 || e.keyCode == 10) && (searchBox.value != "")) {
            var term = searchBox.value;
            term = encodeURIComponent(term).replace("'", "%27");
            searchBox.value = '';
            this.ResetState('/search?cb=' + new Date().getTime() + '&s=' + term);
            searchBox.blur();
        }
    };
    /**
     * Resets the Search results data collection to show a new blank search page
     * @param url to which the window should be redirected to. if null or not given then no redirection is performed
     */
    SearchCmdsMobile.prototype.ResetState = function (url) {
        this.sortColumn = 0;
        this.searchTermColl = new SearchTermCollectionMobile(null, this);
        this.saveSearchState();
        if (url) {
            document.location.href = url;
        }
    };
    SearchCmdsMobile.prototype.requestSearchResults = function () {
        try {
            // Common.addDebugStr("requestSearchResults enter");
            var args = this.makeArgsFromTerms(); //SearchResultsMobile.searchTermColl.makeArgsFromTerms();
            var url = '/searchResults?bc=' + DateUtils.msNow() + args + "&;soTimeout=30000";
            var self_1 = this;
            Ajax.getText(url, function (text) {
                // Common.addDebugStr("requestSearchResults OK func");
                self_1.updateContents(text);
            });
        }
        catch (e) {
            Common.addDebugStr("EXC reqestSearchResults = " + e);
            // log me
        }
    };
    SearchCmdsMobile.prototype.reloadAndRquestSearchResult = function () {
        // Common.addDebugStr("reloadAndRquestSearchResult");
        this.showSpinner();
        // restoration of state can be async, so chain the actual request.
        var self = this;
        this.restoreSearchState(function afterRestorationFunc() {
            // Common.addDebugStr("afterRestoreFunc");
            self.searchTermColl.makeArgsFromTerms();
            self.requestSearchResults();
        });
    };
    SearchCmdsMobile.prototype.makeTermsFromUrl = function () {
        var parts = [];
        var url = location.href;
        if (url.indexOf('#') > -1)
            parts = url.split('#');
        else if (url.indexOf('?') > -1)
            parts = url.split('?');
        var hash = '';
        if (parts.length > 1) {
            hash = parts[1];
        }
        this.searchTermColl.clear();
        parts = hash.split('&');
        for (var i = 0; i < parts.length; ++i) {
            // each part is like s0=term or kw1=term
            var part = parts[i];
            if (part == '') {
                continue;
            }
            var term = part.split('=');
            var termType = "";
            if (term[0].match('^s[0-9]*$') != null) {
                termType = 's';
            }
            else if (term[0].match('^kw')) {
                termType = 'kw';
            }
            else {
                continue;
            }
            this.searchTermColl.addTerm(termType, term[1]);
        }
    };
    SearchCmdsMobile.prototype.makeArgsFromTerms = function () {
        return this.searchTermColl.makeArgsFromTerms();
    };
    SearchCmdsMobile.prototype.fillTable = function () {
        if (this.jst == null)
            this.jst = new QMicroTemplate(document["search_jst"]);
        var total = this.divs.length;
        if (total > this.displayCount)
            total = this.displayCount;
        var dataformTable = document.getElementById('dataformTable');
        if (dataformTable) {
            dataformTable.innerHTML = '';
            for (var index = 0; index < total; ++index) {
                var model = this.divs[index];
                var html = this.jst.evaluate(model);
                var newElement = document.createElement('div');
                newElement.innerHTML = html;
                dataformTable.appendChild(newElement);
            }
        }
        var strValue = "";
        if (this.total == 1)
            strValue = QSTR.oneResult;
        else if (this.total <= this.displayCount)
            strValue = sprintf(QSTR.keywordCategoryResults, this.total);
        else
            strValue = sprintf(QSTR.showingNofM, this.displayCount, this.total);
        var totalElement = document.getElementById('totalStr');
        if (totalElement)
            totalElement.innerHTML = strValue;
    };
    // updateContents when search/refined search results are returned from server
    SearchCmdsMobile.prototype.updateContents = function (text) {
        var decodedData = null;
        if (text == null || text == '' || text == 'null')
            return;
        try {
            decodedData = JSON.decode(text);
        }
        catch (e) {
            alert("Error parsing search results: " + text);
            return;
        }
        // let searchResultsElt = q$('qSearchResults');
        // if (searchResultsElt) {
        //     searchResultsElt.set('html', decodedData.html);
        // } else {
        //     alert("missing element: qSearchResults");
        // }
        var listing = document.getElementById('drilldownResultListing'); // different in SearchResultsDesktop
        listing.innerHTML = decodedData.html;
        this.divs = decodedData.divs;
        this.total = this.divs.length;
        this.searchTermColl.assignTerms(decodedData.terms);
        //setSearchResults(SearchResultsMobile);
        this.fillTable();
        this.saveSearchState();
        if (this.sortColumn > 0) {
            this.resortByColumn();
        }
        this.updateMoreResultsButton();
        this.searchTermColl.updateSearchTermsDisplay(document.getElementById('searchTerms'));
        this.hideSpinner();
        this.addHandler();
        AfterStartupEvents.doAfterDomChange();
    };
    SearchCmdsMobile.prototype.showMoreResults = function () {
        this.displayCount += 20;
        this.fillTable();
        MobileDelayedBg.loadImages();
        this.updateMoreResultsButton();
    };
    SearchCmdsMobile.prototype.setDfgid = function (dfgid, score) {
        this.dfgid = dfgid;
        this.selectedScore = score;
    };
    /**
     * Some kinds of dataforms replace the search page in-situ, others
     * open a new browser tab (i.e. Urls as Dataform)
     */
    SearchCmdsMobile.prototype.causesUnload = function (ns) {
        return (ns != 'dataform:url');
    };
    SearchCmdsMobile.prototype.trackSearchResultClick = function (dfid, ns, goToUrl) {
        if (this.unloaded)
            return;
        // if (SearchResultsDesktop.deviceClass != 'web')
        //     return;
        if (this.causesUnload(ns)) {
            this.unloaded = true;
        }
        var xmlDoc = XML.CreateDocument('<search_action></search_action>');
        var searchElt = xmlDoc.documentElement;
        var queryElt = xmlDoc.createElement('query');
        var url = location.href;
        var parts = url.split('#');
        var hash = '';
        if (parts.length > 1)
            hash = parts[1];
        var inner = xmlDoc.createTextNode(hash);
        queryElt.appendChild(inner);
        searchElt.appendChild(queryElt);
        searchElt.setAttribute('search_event_id', "" + this.searchEventID);
        searchElt.setAttribute('selected_score', this.selectedScore);
        searchElt.setAttribute('dfgid', "" + this.dfgid);
        searchElt.setAttribute('total_results', "" + this.total);
        /* bug 3264: Chrome doesn't let us open a new page to an external page via script from a callback.
         Touchy, touchy.  Okay...  do tracking in onbeforeuload and just go to external url not via callback.
         */
        window.addEvent('beforeunload', function () {
            Ajax.postAsXml(QSettings.postUrl(), xmlDoc, Common.doNothing, Common.doNothing);
        });
        if (goToUrl.indexOf('/player/') == 0)
            theAppIFace.viewDataform(dfid, ns, false, null, goToUrl, 'SearchResultsDesktop');
        else if (Common.isExternalUrl(goToUrl))
            Common.viewExternalPage(goToUrl, dfid, 'SearchResultsDesktop');
        else
            Common.viewInternalPage(goToUrl, 'SearchResultsDesktop');
    };
    SearchCmdsMobile.prototype.updateMoreResultsButton = function () {
        var button = document.getElementById('moreButton');
        button.className = (this.total <= this.displayCount) ?
            'cHidden largeCenteredButton' : 'largeCenteredButton';
    };
    SearchCmdsMobile.prototype.showSpinner = function () {
        var ibc = document.getElementById('innerBodyContainer');
        ibc.className = 'innerBodyContainer clearfix waiting';
    };
    SearchCmdsMobile.prototype.hideSpinner = function () {
        var ibc = document.getElementById('innerBodyContainer');
        ibc.className = 'innerBodyContainer clearfix';
    };
    SearchCmdsMobile.prototype.addHandler = function () {
        var searchBox = document.getElementById('additionalSearchRequest');
        var self = this;
        if (searchBox) {
            searchBox.addEventListener('change', function (evt) {
                self.addUserEnteredTerm();
            });
        }
    };
    SearchCmdsMobile.prototype.addKeyword = function (keyword) {
    };
    SearchCmdsMobile.prototype.updateKeywords = function (eltID) {
        var selectElem = document.getElementById(eltID);
        var dirty = this.searchTermColl.addKeyword(selectElem);
        if (dirty)
            this.requestSearchResults();
    };
    SearchCmdsMobile.prototype.addUserEnteredTerm = function () {
        var inp = document.getElementById('additionalSearchRequest');
        //xoom does not re-paint the text field control if it has the focus
        inp.blur();
        var userEnteredTerm = inp.value;
        if (userEnteredTerm == '')
            return;
        if (this.searchTermColl.addUserEnteredTerm(userEnteredTerm))
            this.requestSearchResults();
    };
    SearchCmdsMobile.prototype.startDiscussion = function () {
        location.href = '/newPublicDiscussion';
    };
    SearchCmdsMobile.prototype.startOver = function () {
        this.searchTermColl.clear();
        this.requestSearchResults();
    };
    SearchCmdsMobile.prototype.removeTermFromCriteria = function (evt) {
        var elem = evt.target;
        var progid = elem.attributes['key'].nodeValue;
        var type = elem.attributes['type'].nodeValue;
        this.searchTermColl.removeTerm(progid, type);
        this.requestSearchResults();
    };
    SearchCmdsMobile.prototype.resort = function () {
        var ss = document.getElementById('sortSelect');
        var selectedIndex = ss.selectedIndex;
        var o = ss.options[selectedIndex];
        this.sortColumn = o.value;
        document.getElementById('currentSort').innerHTML = o.text;
        this.saveSearchState();
        this.resortByColumn();
    };
    SearchCmdsMobile.prototype.resortByColumn = function () {
        var which = this.sortColumn;
        var sortAttribute = SearchCmdsMobile.sortAttributes[which];
        var dataformTable = document.getElementById('dataformTable');
        var allItems = [];
        for (var i = 0; i < this.total; ++i) {
            allItems[i] = document.getElementById("result" + i);
            if (allItems[i])
                dataformTable.removeChild(allItems[i].parentElement);
        }
        var direction = 1; // highest to lowest
        if (which == 0)
            direction = -1; // lowest to highest
        this.divs.sort(function (a, b) {
            return Common.genericCompare(sortAttribute, direction, a, b);
        });
        this.fillTable();
        MobileDelayedBg.loadImages();
    };
    SearchCmdsMobile.prototype.saveSearchState = function () {
        var savedState = new SavedSearchState(this.searchTermColl.termAry, this.sortColumn);
        savedState.save();
    };
    ;
    SearchCmdsMobile.prototype.restoreSearchState = function (callbackFunc) {
        var self = this;
        var onRetrieval = function (savedState) {
            var tempTerms = [];
            var tempColumnn = 0;
            if (savedState) {
                if (savedState.terms)
                    tempTerms = savedState.terms;
                tempColumnn = savedState.sortColumn;
            }
            self.searchTermColl = new SearchTermCollectionMobile(tempTerms, self);
            self.sortColumn = tempColumnn;
            if (callbackFunc)
                callbackFunc();
        };
        SavedSearchState.retrieve(onRetrieval);
    };
    SearchCmdsMobile.sortAttributes = ['relevance', 'startingTimestamp', 'rating', 'commentSort', 'lastCommentTimestamp'];
    return SearchCmdsMobile;
}());

//include "../uJST.js"
//include "SearchTerm.js"
//include "../QUtils.js"
