﻿function FormatDecimalAsCurrency(c, precision)
{
//    var max=new Number(c.getAttribute('999999999999999'));
//    if(c.value>max)
//    {
//        c.value=max
//    }
//    
//    var min=new Number(c.getAttribute('-999999999999999M'));
//    if(c.value<min)
//    {
//        c.value=min
//    }
    
    c.value=DecimalToCurrency(c.value,precision);
//    c.style.color=(c.value.match(/\x2D/)==null?c.getAttribute("positiveColor"):c.getAttribute("negativeColor"));
}

function FormatCurrencyAsDecimal(c)
{
    c.value=CurrencyToDecimal(c.value);
    c.style.color="black";
    c.select();
}

function CurrencyToDecimal(n)
{
    n=n.toString();
    n=n.replace(/[^\d\x2D\x2E]/g,'');
    return n;
}

function DecimalToCurrency(n,p)
{
    n=n.toString();
    if(p==null)
    {
        p=2;
    }
    
    var sy=new Array('','','','');
    var neg=(n.match(/\x2D/)!=null?true:false);
    n=n.replace(/[^\d\x2E]/g,'');
    var m=n.match(/(\d*)(\x2E*)(\d*)/);
    var f=m[3];
    
    if(f.length>p)
    {
        f=f/Math.pow(10,(f.length-p));
        f=Math.round(f);
        
        while(f.toString().length<p)
        {
            f='0'+f
        };
    }
    else
    {
        while(f.toString().length<p)
        {
            f+='0'
        };
    }
    
    var w=new Number(m[1]);
    if(f==Math.pow(10,p))
    {
        w+=1;f=f.toString().substr(1);
    }
    
    w=w.toString();
    var s=3;
    var l=w.length-s;
    
    while(l>0)
    {
        w=w.substr(0,l)+'\x2C'+w.substr(l);
        l-=s;
    }
    
    if(p==0)
    {
        m[2]='';
        f=''
    }
    else
    {
        m[2]='\x2E'
    }
    
    return (neg?sy[2]+w+m[2]+f+sy[3]:sy[0]+w+m[2]+f+sy[1]);
}


