function getSelectedText() {
    var selText = "";
    if (window.getSelection) { // all browsers, except IE before version 9
        if (document.activeElement &&
            (document.activeElement.tagName.toLowerCase() == "textarea" ||
                document.activeElement.tagName.toLowerCase() == "input")) {
            var text = document.activeElement.value;
            selText = text.substring(document.activeElement.selectionStart, document.activeElement.selectionEnd);
        }
        else {
            var selRange = window.getSelection();
            selText = selRange.toString();
        }
    }
    else {
        if (document.selection.createRange) { // Internet Explorer
            var range = document.selection.createRange();
            selText = range.text;
        }
    }
    if (selText !== "") {
        return selText;
    }
    else {
        return null;
    }
}
function formatCurrency(symbol, v) {
    v = (Math.round((v - 0) * 100)) / 100;
    v = (v == Math.floor(v)) ? v + ".00" : ((v * 10 == Math.floor(v * 10)) ? v + "0" : v);
    v = String(v);
    var ps = v.split('.'), whole = ps[0], sub = ps[1] ? '.' + ps[1] : '.00', r = /(\d+)(\d{3})/;
    while (r.test(whole)) {
        whole = whole.replace(r, '$1' + ',' + '$2');
    }
    v = whole + sub;
    if (v.charAt(0) == '-') {
        return '-' + symbol + v.substr(1);
    }
    return symbol + v;
}
TextFieldValidationTypes = {
    Letters: 0,
    Mask: 1,
    Currency: 2
};
TextCases = {
    Normal: 0,
    Lower: 1,
    Upper: 2
};
Ext.define('TextFieldClass15', {
    extend: 'DisplayableAction',
    constructor: function (cfgXML, o, actionSequence) {
        this.Text = "";
        this.TextAlignment = "Left";
        this.FontColor = '#000000';
        this.FontFamily = 'Arial';
        this.FontSize = 14;
        this.FontWeight = 'Normal';
        this.FontStyle = 'Normal';
        this.TextDecoration = 'none';
        this.ValidationType = TextFieldValidationTypes.Letters;
        this.AllowCharacters = null;
        this.MaxTextLength = 0;
        this.MaskTemplate = null;
        this.Mask = null;
        this.PromptCharacter = "_";
        this.StripFromAnswer = false;
        this.TextCase = TextCases.Normal;
        this.IsPassword = false;
        this.PasswordMask = "*";
        this.IsMultiline = false;
        this.CurrencySymbol = "$";
        this.TextMarginTop = 0;
        this.TextMarginLeft = 0;
        this.TextMarginRight = 0;
        this.TextMarginBottom = 0;
        this.InputBox = null;
        this.CurrentValue = "";
        this.LastTyped = null;
        this.CurrencyDecimalLength = 2;
        this.MaskPositions = null;
        this.callParent([ cfgXML, o, actionSequence]);
        this.Text = XmlHelper.tryGetValue(cfgXML, "text", TryGetValueOption.Normal, "");
        this.FontColor = XmlHelper.getString(cfgXML, "fontColor");
        this.FontFamily = XmlHelper.getString(cfgXML, "fontFamily");
        this.FontSize = XmlHelper.getFloat(cfgXML, "fontSize");
        this.TextDecoration = XmlHelper.getString(cfgXML, "textDecoration");
        this.FontStyle = XmlHelper.getString(cfgXML, "fontStyle");
        this.FontWeight = XmlHelper.getString(cfgXML, "fontWeight");
        this.TextAlignment = XmlHelper.getString(cfgXML, "textAlignment");
        this.ValidationType = XmlHelper.getInteger(cfgXML, "validationType");
        this.AllowCharacters = XmlHelper.tryGetValue(cfgXML, "allowCharacters", TryGetValueOption.Normal, null);
        this.MaxTextLength = XmlHelper.getInteger(cfgXML, "maxTextLength");
        this.MaskTemplate = XmlHelper.tryGetValue(cfgXML, "maskTemplate", TryGetValueOption.Normal, null);
        this.Mask = XmlHelper.tryGetValue(cfgXML, "mask", TryGetValueOption.Normal, '');
        this.PromptCharacter = XmlHelper.tryGetValue(cfgXML, "promptCharacter", TryGetValueOption.Normal, "_");
        this.StripFromAnswer = XmlHelper.getBoolean(cfgXML, "stripFromAnswer");
        this.TextCase = XmlHelper.getInteger(cfgXML, "textCase");
        this.IsPassword = XmlHelper.getBoolean(cfgXML, "isPassword");
        this.PasswordMask = XmlHelper.tryGetValue(cfgXML, "passwordMask", TryGetValueOption.Normal, "*");
        this.IsMultiline = XmlHelper.getBoolean(cfgXML, "isMultiline");
        this.CurrencySymbol = XmlHelper.tryGetValue(cfgXML, "currencySymbol", TryGetValueOption.Normal, "$");
        this.TextMarginTop = XmlHelper.getInteger(cfgXML, "textMarginTop");
        this.TextMarginLeft = XmlHelper.getInteger(cfgXML, "textMarginLeft");
        this.TextMarginRight = XmlHelper.getInteger(cfgXML, "textMarginRight");
        this.TextMarginBottom = XmlHelper.getInteger(cfgXML, "textMarginBottom");
    },
    reset: function () {
        this.CurrentValue = '';
    },
    getInteractionValue: function () {
        return this.CurrentValue;
    },
    hasDot: function () {
        return this.CurrentValue.indexOf('.') >= 0;
    },
    getFormattedMaskString: function () {
        var args = this.CurrentValue.split('');
        var prompt = this.PromptCharacter;
        var maskPositions = new Array();
        var replaced = this.MaskTemplate.replace(/\{(\d+)\}/g, function (m, i, index) {
            maskPositions.push(index - (2 * i));
            return i < args.length ? args[i] : prompt;
        });
        this.MaskPositions = maskPositions;
        return replaced;
    },
    getPaddingStyle: function () {
        var padding = "padding:{0}px {1}px {2}px {3}px;";
        return Ext.String.format(padding, this.TextMarginTop, this.TextMarginRight, this.TextMarginBottom, this.TextMarginLeft);
    },
    getTextStyle: function () {
        var textStyle = "text-align:" + this.TextAlignment + ";";
        textStyle += "font-family:" + this.FontFamily + ";";
        textStyle += "font-size:" + this.FontSize + "px;";
        textStyle += "font-style:" + this.FontStyle + ";";
        textStyle += "font-weight:" + this.FontWeight + ";";
        textStyle += "color:" + this.FontColor + ";";
        textStyle += "text-decoration:" + this.TextDecoration + ";";
        return textStyle;
    },
    getDefaultText: function () {
        switch (this.ValidationType) {
            case TextFieldValidationTypes.Mask:
                return this.getFormattedMaskString();
            case TextFieldValidationTypes.Letters:
                var v = ExpressionEngine.evalExpression(this.Text);
                this.CurrentValue = v;
                return v;
        }
        return '';
    },
    getDisplayText: function () {
        var result = this.CurrentValue;
        switch (this.ValidationType) {
            case TextFieldValidationTypes.Currency:
                return formatCurrency(this.CurrencySymbol, this.CurrentValue);
            case TextFieldValidationTypes.Mask:
                return this.getFormattedMaskString();
        }
        switch (this.TextCase) {
            case TextCases.Lower:
                result = result.toLowerCase();
                break;
            case TextCases.Upper:
                result = result.toUpperCase();
                break;
        }
        return result;
    },
    setDisplayText: function () {
        if (this.InputBox == null)
            return;
        this.InputBox.dom.value = this.getDisplayText();
        if (this.ValidationType == TextFieldValidationTypes.Mask) {
            this.setMaskCurPosition();
        }
    },
    setCurPosition: function (pos) {
        if (this.InputBox == null)
            return;
        if (this.InputBox.dom.setSelectionRange) {
            this.InputBox.dom.focus();
            this.InputBox.dom.setSelectionRange(pos, pos);
        }
        else if (this.InputBox.dom.createTextRange) {
            var r = this.InputBox.dom.createTextRange();
            r.moveStart('character', pos);
            r.collapse(true);
            r.select();
        }
    },
    getCurPosition: function () {
        if (this.InputBox == null)
            return -1;
        var curPos = -1;
        if (window.getSelection) { // all browsers, except IE before version 9
            if (document.activeElement &&
                (document.activeElement.tagName.toLowerCase() == "textarea" ||
                    document.activeElement.tagName.toLowerCase() == "input")) {
                var text = document.activeElement.value;
                var selText = text.substring(document.activeElement.selectionStart, document.activeElement.selectionEnd);
                curPos = document.activeElement.selectionStart;
            }
            else {
                try {
                    curPos = window.getSelection().getRangeAt(0).startOffset;
                }
                catch (err) {
                }
            }
        }
        else {
            if (document.selection.createRange) { // Internet Explorer
                var range = document.selection.createRange();
                var re = this.InputBox.dom.createTextRange(), rc = re.duplicate();
                re.moveToBookmark(range.getBookmark());
                rc.setEndPoint('EndToStart', re);
                curPos = rc.text.length;
            }
        }
        return curPos;
    },
    getSelection: function () {
        return getSelectedText();
    },
    setMaskCurPosition: function () {
        if (this.MaskPositions != null && this.CurrentValue.length > 0) {
            this.setCurPosition(this.MaskPositions[this.CurrentValue.length - 1] + 1);
        }
        else {
            this.setCurPosition(this.MaskPositions[0]);
        }
    },
    validTypedChar: function () {
        if (this.LastTyped == null)
            return false;
        if (this.LastTyped == '')
            return true;
        var selectedText, regex;
        switch (this.ValidationType) {
            case TextFieldValidationTypes.Letters:
                if (this.AllowCharacters != null) {
                    regex = eval("/[" + this.AllowCharacters + "]/gi");
                    if (!regex.test(this.LastTyped)) {
                        return false;
                    }
                }
                if (this.MaxTextLength > 0 && this.InputBox.dom.value.length >= this.MaxTextLength) {
                    selectedText = this.getSelection();
                    return  (selectedText != null && selectedText.length > 0);
                }
                break;
            case TextFieldValidationTypes.Mask:
                if (this.CurrentValue.length >= this.Mask.length) {
                    selectedText = this.getSelection();
                    return  (selectedText != null && selectedText.length > 0);
                }
                else {
                    var theMask = this.Mask.charAt(this.CurrentValue.length);
                    var matchReg = /./;
                    switch (theMask) {
                        case "#": //# - Numbers only
                            matchReg = /\d/;
                            break;
                        case "?": //? - Letters only
                            matchReg = /[A-Za-z]/;
                            break;
                        case "*": //& - Any character
                            break;
                        case "H": //H - Hexadecimal values
                            this.LastTyped = this.LastTyped.toUpperCase();
                            matchReg = /[0-9ABCDEF]/;
                            break;
                    }
                    return this.LastTyped.match(matchReg);
                }
                break;
            case TextFieldValidationTypes.Currency:
                if (this.LastTyped == '-') {
                    return this.setCurPosition() == 0;
                }
                if (this.LastTyped == '.') {
                    return !this.hasDot();
                }

                regex = eval("/[0-9]/gi");
                if (!regex.test(this.LastTyped)) {
                    return false;
                }
                if (this.hasDot()) {
                    var decimalPart = this.CurrentValue.slice(this.CurrentValue.indexOf('.') + 1);
                    if (decimalPart.length >= this.CurrencyDecimalLength) {
                        selectedText = this.getSelection();
                        return (selectedText != null && selectedText.length > 0);
                    }
                }
                break;
        }
        return true;
    },
    initializeDC: function (bg) {
        this.initializeDisplayComponent(bg);
        this.InputBox = this.ContentContainer.createChild({
            tag: this.IsMultiline ? "textarea" : "input",
            id: this.ObjectType + "-" + this.id + "-InputBox",
            type: (this.IsMultiline) ? "" : "text",
            name: this.Name,
            value: this.getDefaultText(),
            style: "position:absolute;left:0px;top:0px;width:" + this.ContentContainerWidth + "px;background-color:transparent;border:none;" + this.getTextStyle() + this.getPaddingStyle()
        });
        if (this.IsMultiline) {
            this.InputBox.setStyle("height", this.ContentContainerHeight + "px");
        }
        else {
            var tHeight = this.InputBox.getHeight();
            if (this.ContentContainerHeight > tHeight) {
                this.InputBox.setStyle("top", ((this.ContentContainerHeight - tHeight) / 2 - 1) + "px");
            }
            else {
                this.InputBox.setStyle("height", this.ContentContainerHeight + "px");
            }
        }
        this.setupEventListeners();
    },
    setupEventListeners: function () {
        if (this.InputBox != null) {
            this.InputBox.addListener('keydown', this.onKeyDown, this);
            this.InputBox.addListener('keyup', this.onKeyUp, this);
            this.InputBox.addListener('keypress', this.onKeyPress, this);
            this.InputBox.addListener('focus', this.onFocus, this);
            this.InputBox.addListener('blur', this.onBlur, this);
            this.InputBox.addListener('select', this.onSelect, this);
            this.InputBox.addListener('mousedown', this.onMouseDown, this);
            this.InputBox.addListener('selectstart', this.onSelectStart, this);
        }
    },
    setFocus: function () {
        var that = this;
        setTimeout(function () {
            that.InputBox.dom.focus();
        }, 200);
    },
    onSelectStart: function (evt, el, o) {
        if (this.ValidationType == TextFieldValidationTypes.Mask) {
            evt.stopEvent();
        }
    },
    onKeyDown: function (evt, el, o) {
        this.LastTyped = null;
        var keyCode = evt.getKey();
        switch (keyCode) {
            case evt.F1:
            case evt.F2:
            case evt.F3:
            case evt.F4:
            case evt.F5:
            case evt.F6:
            case evt.F7:
            case evt.F8:
            case evt.F9:
            case evt.F10:
            case evt.F11:
            case evt.F12:
                evt.stopEvent();
                return;
        }
        switch (this.ValidationType) {
            case TextFieldValidationTypes.Letters:
            case TextFieldValidationTypes.Currency:
                this.CurrentValue = this.InputBox.dom.value;
                break;
            case TextFieldValidationTypes.Mask:
                switch (keyCode) {
                    case evt.LEFT:
                    case evt.RIGHT:
                    case evt.UP:
                    case evt.DOWN:
                    case evt.DELETE:
                        evt.stopEvent();
                        break;
                    case evt.BACKSPACE:
                        this.CurrentValue = this.CurrentValue.slice(0, this.CurrentValue.length - 1);
                        this.setDisplayText();
                        evt.stopEvent();
                }
        }
    },
    onKeyUp: function (evt, el, o) {
        switch (this.ValidationType) {
            case TextFieldValidationTypes.Letters:
            case TextFieldValidationTypes.Currency:
                this.CurrentValue = this.InputBox.dom.value;
        }
    },
    onKeyPress: function (evt, el, o) {
        var keycode = evt.getCharCode(),
            valid =(keycode > 47 && keycode < 58) || // number keys
                keycode == 32 || // spacebar & return key(s) (if you want to allow carriage returns)
                (keycode > 64 && keycode < 91) || // letter keys
                (keycode > 95 && keycode < 112) || // numpad keys
                (keycode > 185 && keycode < 193) || // ;=,-./` (in order)
                (keycode > 218 && keycode < 223);   // [\]' (in order)
        this.LastTyped = valid ? String.fromCharCode(evt.getCharCode()) : '';


        if (!this.validTypedChar()) {
            this.LastTyped = null;
            evt.stopEvent();
        }
        else {
            switch (this.ValidationType) {
                case TextFieldValidationTypes.Mask:
                    this.CurrentValue += this.LastTyped;
                    this.setDisplayText();
                    evt.stopEvent()
            }
        }
    },
    onMouseDown: function (evt, el, o) {
        if (this.ValidationType == TextFieldValidationTypes.Mask) {
            evt.stopEvent();
            var that = this;
            setTimeout(function(){that.setMaskCurPosition();}, 200);
        }
    },
    onSelect: function (evt, el, o) {
        evt.stopEvent();
    },
    onFocus: function (evt, el, o) {
        switch (this.ValidationType) {
            case TextFieldValidationTypes.Currency:
                this.InputBox.dom.value = this.CurrentValue;
                break;
            case TextFieldValidationTypes.Mask:
                evt.stopEvent();
                var that = this;
                setTimeout(function(){that.setMaskCurPosition();}, 200);
        }
    },
    onBlur: function (evt, el, o) {
        switch (this.ValidationType) {
            case TextFieldValidationTypes.Currency:
                if (this.CurrentValue.match(/^\d*\.$/)) {
                    this.CurrentValue = this.CurrentValue.slice(0, this.CurrentValue.length - 1);
                }
                this.setDisplayText();
                break;
        }
    },
    processAction: function (bg) {
        if (this.IsChangeAction) {
            Author.DisplayManager.changeAction(this);
        }
        this.initializeDC(bg);
        this.setInitialVisibility();
        this.applyEffect();
        return {MoveOn: true, Interval: 0};
    }
});




