﻿//Contains helper functions for use in calculators. Used with the Personal Loan calculator, Cash Investment Planner and Budget Planner only at present

/// <summary>
/// Adds commas (or other characters) to separate a number into a currency
/// </summary>
/// <param name="number">The number to format</param>
/// <param name="thousandsSeparator">The separator character to insert for thousands</param>
function addThousandsSeparator(number, thousandsSeparator) {
    var thousandsFormatted = "";
    var thousandsCount = 0;
    for (var j = number.length; j > 0; j--) {
        char = number.substr(j - 1, 1);
        thousandsCount++;
        if (thousandsCount % 3 == 0) {
            char = thousandsSeparator + char;
        }
        thousandsFormatted = char + thousandsFormatted;
    }
    if (thousandsFormatted.substr(0, 1) == thousandsSeparator) {
        thousandsFormatted = thousandsFormatted.substring(1, thousandsFormatted.length);
    }
    return thousandsFormatted;
}

/// <summary>
/// Formats a field as currency
/// </summary>
/// <param name="input">The input field</param>
/// <param name="validatorId">The ID of the validator for the input field (can be null if no validator)</param>
function formatCurrency(input, validatorId) {
    var validator = $("#" + validatorId);
    if (!validatorId || validator[0].isvalid) {
        var integerVal = input.value.replace(/\$*,*(\.\d*)*/g, "");
        input.value = addThousandsSeparator(integerVal, ",");
    }
}

function formatCurrencyInput(input) {
    var integerVal = input.value.replace(/\$*,*(\.\d*)*/g, "");
    input.value = addThousandsSeparator(integerVal, ",");
}

/// <summary>
/// Removes all currency symbols from inputs within the given container control
/// </summary>
/// <param name="validatorId">The ID of the container control</param>
function removeAllCurrencySymbols(containerId) {
    $("#" + containerId + " input[type='text']").each(function() {
        formatCurrencyInput($(this)[0]);
    });
}
function removeSeparator(n) {
    var number = n.replace(/[,\$%]/g, "") - 0;
    if (isNaN(number)) {
        number = 0;
    }
    return number;
}

/// <summary>
/// Enables all validators, or disables them, depending on the value of the "enable" parameter
/// </summary>
/// <param name="enable">Whether to enable or disable the validators</param>
function enableAllValidators(enable) {
    for (i = 0; i < Page_Validators.length; i++) {
        ValidatorEnable(Page_Validators[i], enable);
    }
}

/// <summary>
/// Enables the validator with the specified ID, or disables it, depending on the value of the "enable" parameter
/// </summary>
/// <param name="validatorId">The ID of the validator to enable</param>
/// <param name="enable">Whether to enable or disable the validator</param>
function enableValidator(validatorId, enable) {
    var validator = $("#" + validatorId);
    validator[0].enabled = enable;
}


//Sets the form back to its initial state, resetting all input values
function clearForm() {
    //Reset the dropdown values in the first table
    $(".tbl-complex:eq(0) select").restoreDefaults("0");
    //Reset the values in the Incomes table
    $(".tbl-complex:eq(1)")
                .find("input[type='text']")
                .restoreDefaults("").end()
                .find("select")
                .restoreDefaults("3");
    //Reset the values in the Expenses table
    $(".tbl-complex:eq(2)")
                .find("input[type='text']")
                .restoreDefaults("").end()
                .find("select")
                .restoreDefaults("2");
    //Reset the values in the footer table
    $(".tbl-complex:eq(3) span").hide();
}

$.fn.disableEnterKey = function() {
    $(this).live("keypress", function(e) {
        if (e.which === 13) {
            e.preventDefault();
        }
    });
};

//Allows only number, cursors, backspace, comma and dot key press into specifed input control
$.fn.allowOnlyCurrencyInput = function(options) {
    var defaults = { decimal: 2, maxDegit: 6 };
    var opts = $.extend(defaults, options);
    $(this).live("keypress", function(e) {
        var isAllowedKey = false, pressedNumber = "",
            inputValue = $(this).val(),
            allowedFunctionKeys = [0, 8, 9, 44, 46]; //cursors, backspace, tab, comma and dot
        if (opts.maxDegit < 4) {
            removeByElement(allowedFunctionKeys, 44); // do not allow comma
        }
        if (opts.decimal === 0) {
            removeByElement(allowedFunctionKeys, 46); // do not allow dot
        }
        if ((e.which >= 48) && (e.which <= 57)) {
            pressedNumber = String.fromCharCode(e.which);
        }
        if (inputValue.search(/\./) >= 0) {
            if (inputValue.match(/\./g).length > 0) {
                //prevent more than one dot and prevent comma after dot
                allowedFunctionKeys = [0, 8];
            }
        }
        if (inputValue.search(/\.$|,\d{0,2}$/) >= 0) {
            // prevent continuous comma or dot and prevent less than three digit after comma
            allowedFunctionKeys = [0, 8, 9];
        }
        if (String.fromCharCode(e.which).match(/[0-9]/)) {
            isAllowedKey = true;
        }

        //Get the selected text and only do length-related checks if the User hasn't selected anything.
        //This is so we can handle the scenario where a User enters the maximum number of characters
        //in the field, then tries to select some of them and "over-type". Without this text selection check,
        //we can end up preventing this as the max length appears to be violated
        var selectedText = $(this).getSelection();
        if (selectedText.length == 0) {
            if (inputValue.search(/,\d{3}$/) >= 0) {
                // prevent more than 3 numbers after comma 
                isAllowedKey = false;
            }
            var decimalNumberRegex = new RegExp("\\.\\d{" + opts.decimal + "}$");
            if ((inputValue.search(decimalNumberRegex) >= 0) && (getCursorPosition(this) > inputValue.length - (opts.decimal + 1))) {
                // prevent more than 2 numbers after dot 
                isAllowedKey = false;
            }
            if (eval(inputValue.replace(/,/g, "").replace(/[\$\%]/g, "") + pressedNumber) >= Math.pow(10, opts.maxDegit)) {
                //prevenet more than maximum digit 
                isAllowedKey = false;
            }
        }

        if (inputValue.length === 0) { // cannot start with comma or dot but allow tab and cursor
            allowedFunctionKeys = [0, 9];
        }
        for (var i in allowedFunctionKeys) {
            if (e.which === allowedFunctionKeys[i]) {
                isAllowedKey = true;
            }
        }
        if (!isAllowedKey) {
            e.preventDefault();
        }
    });
    $(this).bind('paste', function(e) {
        var pasteData = window.clipboardData.getData("Text");
        inputNumber = ($(this).val() + pasteData).replace(/[,\$\%]/g, "") - 0;
        if (isNaN(inputNumber)) {
            e.preventDefault();
        } else if (inputNumber >= Math.pow(10, opts.maxDegit)) {
            e.preventDefault();
        }
    });
    $(this).bind('drop', function(e) {
        e.preventDefault();
    });
};

function getCursorPosition(o) {
    if (o.createTextRange) {
        var r = document.selection.createRange().duplicate()
        r.moveEnd('character', o.value.length)
        if (r.text == '') return o.value.length
        return o.value.lastIndexOf(r.text)
    } else return o.selectionStart
}

(function($) {
    $.fn.currency = function(options) {
        var defaults = {
            decimal: 2,
            textAlign: 'right',
            eraseInvalid: true,
            currencySymbol: false,
            percentSymbol: false
        };
        var opts = $.extend(defaults, options);
        $(this).blur(function() {
            var input = $(this).val();
            if (input != "") {
                if (!$(this).hasClass('watermark') || (input !== $(this).attr('title') && $(this).hasClass('watermark'))) {
                    input = input.replace(/[,\$\%]/g, "") - 0;

                    if (isNaN(input)) {
                        input = "";
                        if (opts.eraseInvalid) {
                            $(this).val("");
                        }
                    }
                    else {
                        var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})'),
                     input = input.toFixed(opts.decimal);
                        input = input + '';
                        while (sRegExp.test(input)) {
                            input = input.replace(sRegExp, '$1,$2');
                        }
                        if (opts.currencySymbol) {
                            input = String.Format("${0}", input);
                        }
                        if (opts.percentSymbol) {
                            input = String.Format("{0}%", input);
                        }
                        $(this).val(input).css('text-align', opts.textAlign);
                    }
                }
            }
        }).focus(function() {
            $(this).css('text-align', 'left');
            var input = $(this).val();
            input = input.replace(/[,\$\%]/g, "") - 0;
            if (isNaN(input)) {
                if (opts.eraseInvalid) {
                    $(this).val("");
                }
            } else if (input != "") {
                $(this).val(input);
                if ($.browser.msie) {
                    setCursorAtEnd(this.id);
                }
            }
        });
    };
})(jQuery);
//Use this method when you show calculation result including decimal value
var AddThousandSeparator = function(n) {
    var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})'),
    sValue = n + '';
    while (sRegExp.test(sValue)) {
        sValue = sValue.replace(sRegExp, '$1,$2');
    }
    return sValue;
};
function removeByElement(arrayName, arrayElement) {
    for (var i = 0; i < arrayName.length; i++) {
        if (arrayName[i] == arrayElement)
            arrayName.splice(i, 1);
    }
}
