﻿function validateAmount(amount)
{
    if (amount == "")
        amount = "0";
    else
        amount = amount.toString();
        
    return amount;
}

function validateSignPosition(sp)
{
    if (sp != "L" && sp != "R")
        return "L";
    else
        return sp;
}


function formatCurrency(txtid,amount, CurrencySign, SignPosition, iDecSeparator, 
                        oDecSeparator, iIntSeparator, oIntSeparator, DecimalShift, DecimalPrecision)
{
    // Validate the amount. Check only whether or not amount is an empty string
    amount = validateAmount(amount);
    SignPosition = validateSignPosition(SignPosition);
        
    if (iDecSeparator == "")
        iDecSeparator = ".";
        
    if (oDecSeparator == "")
        oDecSeparator = iDecSeparator;
    
    var decPos = amount.indexOf(iDecSeparator, 0);
    var decPart = amount.substring(decPos + 1, amount.length);
 
    while (decPart.length < DecimalShift)
        decPart += "0";
    
    var intPart = amount.substring(0, decPos);
    intPart += decPart.substr(0, DecimalShift);
       
    decPart = decPart.substring(DecimalShift, decPart.length);
    
    if (decPart.length > DecimalPrecision)
        decPart = decPart.substr(0, DecimalPrecision);
    else
        while (decPart.length < DecimalPrecision)
            decPart += "0";
    
    var re = new RegExp(iIntSeparator, "gi");
    intPart = intPart.replace(re, "");
    
    var i = intPart.length;
    var newIntPart = "";
    
    while (i > 0)
    {
        if ((i - 3 > 0) && (i == intPart.length))
        {
            newIntPart = intPart.substr(i - 3, 3);
        }
        else if ((i - 3 > 0) && (i != intPart.length))
        {
            newIntPart = intPart.substr(i - 3, 3) + oIntSeparator + newIntPart;
        }
        else
        {
            if (intPart.substr(0, i) != "0")
                newIntPart = intPart.substr(0, i) + oIntSeparator + newIntPart;
        }
            
        i -= 3;
    }
    
    if (decPart.length > 0)
        var newAmount = newIntPart + oDecSeparator + decPart;
    else
        var newAmount = newIntPart;
    
    switch (SignPosition)
    {
        case "L":
            newAmount = CurrencySign + " " + newAmount;
            break;
        case "R":
            newAmount += " " + CurrencySign;
            break;        
    }	
document.getElementById(txtid).innerHTML=newAmount;
}