﻿// *******************************************************************
// Description  Returns the localized decimal separator.
// *******************************************************************
function getLocalizedDecimalSeparator() {
    var decimalSeparator = new Number(0.1).toLocaleString().substring(1, 2);
    if (decimalSeparator != "'" &&
        decimalSeparator != "." &&
        decimalSeparator != ",") {
        decimalSeparator = ".";
    }
    return decimalSeparator;
}

// *******************************************************************
// Description  Returns the localized thousand separator.
// *******************************************************************
function getLocalizedThousandSeparator() {
    var thousandSeparator = new Number(1000).toLocaleString().substring(1, 2);
    if (thousandSeparator != "'" &&
        thousandSeparator != "." &&
        thousandSeparator != ",") {
        thousandSeparator = "'";
    }
    return thousandSeparator;
}

// *******************************************************************
// Description  The localized decimal separator.
// *******************************************************************
var _decimalSeparator = "."; 

// *******************************************************************
// Description  The localized thousand separator.
// *******************************************************************
var _thousandSeparator = "'";

// *******************************************************************
// Description  Format the numeric text box on got focus (with 2 decimals).
// Parameters   s           The sender source.
//              e           The arguments.
// *******************************************************************
function gotFocusNumericStandard(s, e) {
    gotFocusNumeric(s, e, 2);
}

// *******************************************************************
// Description  Format the numeric text box on got focus.
// Parameters   s            The sender source.
//              e            The arguments.
//              decimalCount The decimal count to use.
// *******************************************************************
function gotFocusNumeric(s, e, decimalCount) {
    if (!(isNaN(parseFloat(s.GetText())) || s.GetText() == '')) {
        var inputText = getNonLocalizedValue(s.GetText());
        s.SetText(parseFloat(inputText).toFixed(decimalCount));
        s.SetCaretPosition(0);
        s.SelectAll();
    }
}

// *******************************************************************
// Description  Format the numeric text box on lost focus (with 2 decimals).
// Parameters   s           The sender source.
//              e           The arguments.
//              withThousandSeparator With or without thousand separator.
// *******************************************************************
function lostFocusNumericStandard(s, e, withThousandSeparator) {
    lostFocusNumeric(s, e, 2, withThousandSeparator);    
}

// *******************************************************************
// Description  Format the numeric text box on lost focus.
// Parameters   s            The sender source.
//              e            The arguments.
//              decimalCount The decimal count to use.
//              withThousandSeparator With or without thousand separator.
// *******************************************************************
function lostFocusNumeric(s, e, decimalCount, withThousandSeparator) {
    var inputString = s.GetText();
    var integerPart = '';
    var decimalPart = '';
    if (!(isNaN(parseFloat(inputString)) || inputString == '')) {
        // Fix to decimal count.
        inputString = getFixToDecimalCount(inputString, decimalCount);
        // Retrieve the decimal separator position.
        var decimalSeparatorPosition = inputString.indexOf(_decimalSeparator);
        if (decimalSeparatorPosition > -1) {
            integerPart = inputString.substring(0, decimalSeparatorPosition);
            decimalPart = inputString.substring(decimalSeparatorPosition + 1, inputString.length);
        }
        else {
            integerPart = inputString;
        }
        // Format to locale culture.
        var negativeValue = parseFloat(inputString) < 0
        if (withThousandSeparator) {
            integerPart = getLocalizedInteger(integerPart);
        }
        // Retrieve the new decimal separator position.
        decimalSeparatorPosition = integerPart.indexOf(_decimalSeparator);
        if (decimalSeparatorPosition > -1) {
            integerPart = integerPart.substring(0, decimalSeparatorPosition);
        }
        if (negativeValue && !(integerPart.substring(0, 1) == '-')) {
            integerPart = "-" + integerPart;
        }
        if (decimalCount <= 0) {
            s.SetText(integerPart);
        }
        else {
            s.SetText(integerPart + _decimalSeparator + decimalPart);
        }
    }
    else {
        if (inputString == '-' || inputString == _decimalSeparator || inputString == '-' + _decimalSeparator) {
            // Doesn't allow only a "-", a decimal separator or a "-" and decimal separator.
            s.SetText('');
        }
    }
    s.Validate();
}

// *******************************************************************
// Description  Returns a string fixed to a given decimal count.
// Parameters   inputString    The string to fix.
//              decimalCount   The given decimal count to use.
// *******************************************************************
function getFixToDecimalCount(inputString, decimalCount) {
    // Fix to decimal count.
    if (_decimalSeparator != '.') {
        // Parse float does not parse the number correctly 
        // when the decimal separator is not a dot.
        var fixedDecimalNumber = inputString.replace(_decimalSeparator, '.');
        inputString = parseFloat(fixedDecimalNumber).toFixed(decimalCount);
        inputString = inputString.replace('.', _decimalSeparator);
    }
    else {
        inputString = parseFloat(inputString).toFixed(decimalCount);
    }
    return inputString;
}

// *******************************************************************
// Description  Returns only numeric values for the numeric text box (with 2 decimals).
// Parameters   s           The sender source.
//              e           The arguments.
// *******************************************************************
function keyPressNumericStandard(s, e) {
    return keyPressNumeric(s, e, 2, -1);
}

// *******************************************************************
// Description  Returns only numeric values for the numeric text box.
// Parameters   s                 The sender source.
//              e                 The arguments.
//              decimalCount      The decimal count to allow.
//              integerPartMaxLen The integer part maximum len to allow.
// *******************************************************************
function keyPressNumeric(s, e, decimalCount, integerPartMaxLen) {
    // Retrieve key code.
    var code = getKeyCode(e);
    if ((code == 45 || String.fromCharCode(code) == _decimalSeparator) ||
     (code >= 48 && code <= 57)) {
        // We have a numeric key pressed.
        var positionIndex;
        if (code == 45 || String.fromCharCode(code) == _decimalSeparator) {
            if (code == 45) {
                // Negative value.
                positionIndex = s.GetText().indexOf('-');
                if (positionIndex > -1) {
                    // Set position at beginning.
                    s.SetCaretPosition(1);
                    // Doesn't allow multi "-".
                    return _aspxPreventEvent(e.htmlEvent);
                }
                // Set position at beginning.
                s.SetCaretPosition(0);
            }
            else {
                // Decimal separator.
                if (decimalCount <= 0) {
                    return _aspxPreventEvent(e.htmlEvent);
                }
                positionIndex = s.GetText().indexOf(_decimalSeparator);
                if (positionIndex > -1) {
                    // Set position after the existing decimal separator.
                    s.SetCaretPosition(positionIndex + 1);
                    // Doesn't allow multi decimal separator.
                    return _aspxPreventEvent(e.htmlEvent);
                }
            }
            // Allows only one decimal separator.
            return true;
        }
        else {
            positionIndex = s.GetText().indexOf('-');
            if (positionIndex > -1) {
                var ctrl = getById(s.name + '_I');
                if (getCaretPosition(ctrl) <= positionIndex) {
                    // Doesn't allow before "-".
                    return _aspxPreventEvent(e.htmlEvent);
                }
            }
            // Check if the maximum length for the integer part is exceeded
            if (integerPartMaxLen != -1) {
                var numeric = 0;
                try {
                    var insert_pos = getCaretPosition(getById(s.name + '_I'));
                    var text = s.GetText();
                    text = text.substring(0, insert_pos) + String.fromCharCode(code) + text.substring(insert_pos, text.length);
                    numeric = Math.abs(Math.floor(parseFloat(text.replace(_decimalSeparator, '.'))));
                }
                catch (ex) {
                    // Do nothing
                }

                if (numeric >= Math.pow(10, integerPartMaxLen)) return _aspxPreventEvent(e.htmlEvent);
            }
            // Allows numeric key pressed.     
            return true;
        }
    }
    else if (code != 0) {
        // Doesn't allow any other key pressed (except non printable chars).
        return _aspxPreventEvent(e.htmlEvent);
    }
}

// *******************************************************************
// Description  Returns the caret position in a given control.
// Parameters   ctrl        The given control.
// *******************************************************************
function getCaretPosition(ctrl) {
    var caretPos = 0;
    if (document.selection) {
        // IE Support
        ctrl.focus();
        var Sel = document.selection.createRange();
        Sel.moveStart('character', -ctrl.value.length);
        caretPos = Sel.text.length;
    }
    else {
        if (ctrl.selectionStart || ctrl.selectionStart == '0') {
            // Firefox support
            caretPos = ctrl.selectionStart;
        }
    }
    return (caretPos);
}

// *******************************************************************
// Description  Format the numeric text box for coordinates on got focus (with 3 decimals).
// Parameters   s           The sender source.
//              e           The arguments.
// *******************************************************************
function gotFocusNumericSpecialCoordinate(s, e) {
    // Special format (001.100) represents decimal value (1.1).
    if (!(isNaN(parseFloat(s.GetText())) || s.GetText() == '')) {
        var inputText = replaceText(s.GetText(), '.', '');
        if ((parseFloat(inputText) / 1000) < 1000) {
            // Not null or empty, so we replace "." with decimal separator for editing mode.
            var inputTextCoordinate = s.GetText().replace(".", _decimalSeparator);
            s.SetText(inputTextCoordinate);
        }
    }
    gotFocusNumeric(s, e, 3);
}

// *******************************************************************
// Description  Format the numeric text box for coordinates on lost focus (with 3 decimals).
// Parameters   s           The sender source.
//              e           The arguments.
// *******************************************************************
function lostFocusNumericSpecialCoordinate(s, e) {
    lostFocusNumeric(s, e, 3, true);
    // Special format (001.100) represents decimal value (1.1).
    if (!(isNaN(parseFloat(s.GetText())) || s.GetText() == '')) {
        var inputText = replaceText(s.GetText(), '.', '');
        if ((parseFloat(inputText) / 1000) < 1000) {
            // Not null or empty, so we replace decimal separator with "." for display mode.
            var inputTextCoordinate = s.GetText().replace(_decimalSeparator, ".");
            // Add first x "0", if necessary.
            if (inputTextCoordinate.length < 7) {
                do {
                    inputTextCoordinate = "0" + inputTextCoordinate;
                } while (inputTextCoordinate.length < 7);
            }
            s.SetText(inputTextCoordinate);
            s.Validate();
        }
    }
}

// *******************************************************************
// Description  Allows only numeric values for the numeric text box for coordinates (with 3 decimals).
// Parameters   s           The sender source.
//              e           The arguments.
// *******************************************************************
function keyPressNumericSpecialCoordinate(s, e) {
    return keyPressNumeric(s, e, 3, 3);
}

// *******************************************************************
// Description  Replaces a text in a given string.
// Parameters   text        The given text to modify.
//              find        The text to find.
//              replace     The text to use.
// *******************************************************************
function replaceText(text, find, replace) {
    var result = '';
    var textLenght = text.length;
    for (var i = 0; i < textLenght; i += 1) {
        if (text.substring(i, i + find.length) == find) {
            result += replace;
            i += find.length - 1;
        }
        else {
            result += text.substring(i, i + 1);
        }
    }
    return result
}

// *******************************************************************
// Description  Returns a non localized value.
// Parameters   value       The value to transform.
// *******************************************************************
function getNonLocalizedValue(value) {
    value = replaceText(value, _thousandSeparator, '');
    return value;
}

// *******************************************************************
// Description  Returns the key code.
// Parameters   e       The key argument.
// *******************************************************************
function getKeyCode(e) {
    var code;
    if (e.htmlEvent.charCode != undefined) {
        // Firefox.
        code = e.htmlEvent.charCode;
    }
    else {
        // IE.
        code = e.htmlEvent.keyCode;
    }
    return code;
}

// *******************************************************************
// Description  Returns the localized number.
// Parameters   e       The number argument.
// *******************************************************************
function getLocalizedInteger(e) {
    e = parseFloat(e).toLocaleString();
    if (e.indexOf(getLocalizedThousandSeparator()) == -1) {
        e = getWithThousandSeparator(e);
    }
    e = replaceText(e, getLocalizedThousandSeparator(), _thousandSeparator);
    e = replaceText(e, getLocalizedDecimalSeparator(), _decimalSeparator);
    return e;
}

// *******************************************************************
// Description  Puts the localized separator.
// Parameters   e       The number argument.
// Remarks      Correction due to Google Chrome error on 'xxx.toLocaleString()'
// *******************************************************************
function getWithThousandSeparator(e) {
    var result = '';
    var index = 0;
    var integerPart = '';
    var decimalSeparatorPosition = e.indexOf(getLocalizedDecimalSeparator());
    if (decimalSeparatorPosition > -1) {
        integerPart = e.substring(0, decimalSeparatorPosition);
        result = getLocalizedDecimalSeparator() + e.substring(decimalSeparatorPosition + 1, e.length);
    }
    else {
        integerPart = e;
    }
    var textLenght = integerPart.length;
    for (var i = textLenght - 1; i >= 0; i -= 1) {
        result = integerPart.substring(i, i + 1) + result;
        index += 1;
        if (index % 3 == 0 && i > 0) {
            result = _thousandSeparator + result;
        }
    }
    return result;
}

// *******************************************************************
// Description  Updates the value of a dx combo box.
// Parameters   e       The number argument.
// Remarks      Correction due to Google Chrome error on 'xxx.toLocaleString()'
// *******************************************************************
function dxUpdateComboBox(comboBoxId, jsonCollection) {
    // TODO
    // 1.  Deserialize data
    // 2.  Clear combo box;
    // 3.  Add new members to combo box.
    var collection = $.parseJSON(jsonCollection);
    var comboBox = getById(comboBoxId);
    var item;
    comboBox.ClearItems();
    for (i = 0; i < collection.items.length; i++) {
        item = collection.items[i];
        comboBox.AddItem(item.text, item.value);
    }
    if (collection.items.length > 0) {
        comboBox.SetSelectedIndex(0);
    }
}

// *******************************************************************
// Description  Click the given button if enter key is pressed.
// Parameters   e       The event argument.
// *******************************************************************
function clickButtonOnEnterKeyPress(s, e, buttonId) {
	var button = getById(buttonId);
	if (button) {
		if (getKeyCode(e) === 13) {
			button.DoClick();
			_aspxPreventEvent(e.htmlEvent);
		}
	}
}


