// File: Kalk.js
// Description: Implementa a calculadora do Kankei
// Author: Rogério Ramos - rogerio@kankei.com.br
// Obs: Incluir antes o "balloons.js"
// Date: 21/jun/2006
// Version: 1.0
// Copyright: Kankei Software e Consultoria Ltda. - http://www.kankei.com.br


Kalk= function(par)
{
    var table= Balloon.createElement("table", par);
    table.cellSpacing = 3;
    table.cellPadding = 0;
    table.style.border= "0px";
    this.tbody= Balloon.createElement("tbody", table);
    this.TR1(); this.TR2(); this.TR3(); this.TR4(); this.TR5(); this.TR6();
    this.OKandCancel();
    this.clearTape();
};

Kalk.breakLine= "<br />";
Kalk.nonBreakableSpace= "&nbsp;";

Kalk.processKeyPress= function(ev)
    {
        if(!ev)
        {
            ev= window.event;
        }
        var kal= ev.currentTarget ?  ev.currentTarget.Kalk : ev.srcElement.Kalk;
        if( kal )
        {
            var keyPressed= String.fromCharCode(ev.which ? ev.which : ev.keyCode);
            if( keyPressed >= '0' && keyPressed <= '9' )
            {
                kal.processDigit( keyPressed );
            } else
            {
                switch( keyPressed )
                {
                case '%' : kal.processPercent(); break;
                case '+' : kal.processPlus(); break;
                case '-' : kal.processMinus(); break;
                case '/' : kal.processDivision(); break;
                case '*' : kal.processMultiply(); break;
                case ',' :
                case '.' : kal.processDigit(','); break;
                case '=' : kal.processShowResult(); break;
                }
            }
            return false;
        }
    };
    
Kalk.prototype.show= function()
    {
        this.txtBuffer.focus();
    };

Kalk.prototype.TR1= function()
    {
        var tr= Balloon.createElement("tr",this.tbody);
        tr.align= "right";
        tr.valign= "top";
        var td= Balloon.createElement("td",tr);
        td.colSpan= 2;
        var button= Balloon.createElement("button",td);
        button.className= "form_button";
        button.style.width= "55px";
        button.style.height= "40px";
        button.Kalk= this;
        button.onclick= function() { this.Kalk.clearTape(); };
        button.innerHTML= "Limpa<br />fita";
        with( Balloon.createElement("span",td) )
        {
            style.fontSize= "8pt";
            innerHTML= "<br /><br />decimais:<br />";
        }
        this.slPrecision= Balloon.createElement("select", td);
        with( Balloon.createElement("option", this.slPrecision) )
        {
            innerHTML= "F";
            value= "F";
        }
        for(var i= 0; i <= 6; i++)
        {
            with( Balloon.createElement("option", this.slPrecision) )
            {
                innerHTML= i;
                value= i;
                if( i == 2 )
                {
                    selected= true;
                }
            }
        }
        with( Balloon.createElement("span",td) )
        {
            style.fontSize= "8pt";
            innerHTML= "<br /><br />tipo:<br />";
        }
        this.slTipo= Balloon.createElement("select", td);
        this.slTipo.style.width= "55px";
        this.slTipo.size= "2";
        this.slTipo.disabled= true;

        with( Balloon.createElement("option", this.slTipo) )
        {
            innerHTML= "Normal";
            value= "N";
        }
        with( Balloon.createElement("option", this.slTipo) )
        {
            innerHTML= "Adic.";
            value= "A";
            selected= true;
        }
        td= Balloon.createElement("td",tr);
        td.colSpan= 4;
        td.align= "right";
        td.style.border= "solid 1px #8cacbb";
        td.style.fontSize= "8pt";
        this.createTape( td, "" );
    };
    
Kalk.killInvalidKeys= function(ev)
    {
        var kal= ev.currentTarget ?  ev.currentTarget.Kalk : ev.srcElement.Kalk;
        var keyCode= ev.which ? ev.which : ev.keyCode;
        if( keyCode == 8 || keyCode == 13 || keyCode == 27 )
        {
            ev.returnValue= false;
            ev.cancelBubble= true;
            switch( keyCode )
            {
                case  8 : kal.processBack(); break;
                case 13 : kal.OK(); break;
                case 27 : kal.Cancel(); break;
            }
        }
    };
    
Kalk.prototype.TR2= function()
    {
        var tr= Balloon.createElement("tr",this.tbody);
        var td= Balloon.createElement("td", tr);
        td.colSpan= 6;
        td.align= "right";
        this.txtBuffer= Balloon.createElement("input", td);
        this.txtBuffer.Kalk= this;
        Balloon.addEvent(this.txtBuffer,"keydown",Kalk.killInvalidKeys);
        this.txtBuffer.onkeypress= Kalk.processKeyPress;
        with( this.txtBuffer )
        {
            type= "text";
            className= "form_input";
            style.width= "193px";
            style.textAlign= "right";
        }
    };

Kalk.prototype.createButton= function(strValue,tr,align)
    {
        var td= Balloon.createElement("td", tr);
        if( typeof align == "string" )
        {
            td.align= align;
        }
        var button= Balloon.createElement("input");
        button.Kalk= this;
        with( button )
        {
            type= "button";
            className= "form_button";
            value= strValue;
            style.width= "25px";
        }
        td.appendChild(button);
        return button;
    };

Kalk.prototype.TR3= function()
    {
        var tr= Balloon.createElement("tr",this.tbody);
        tr.style.height= "19px";
        
        var btn= this.createButton("C", tr);
        btn.onclick= function() { this.Kalk.processClear(); };
        with( btn )
        {
            style.backgroundColor= "red";
            style.fontSize= "8pt";
            style.fontWeight= 900;
            style.color= "White";
        }
        this.createButton("«", tr).onclick= function() { this.Kalk.processBack(); };
        this.createButton("7", tr, "right").onclick= function() { this.Kalk.processDigit("7"); };
        this.createButton("8", tr).onclick= function() { this.Kalk.processDigit("8"); };
        this.createButton("9", tr, "left").onclick= function() { this.Kalk.processDigit("9"); };
        
        btn= this.createButton("-", tr);
        btn.onclick= function() { this.Kalk.processMinus(); };
        with( btn )
        {
            style.backgroundColor= "red";
            style.fontSize= "8pt";
            style.fontWeight= 900;
            style.color= "White";
        }                
    };

Kalk.prototype.TR4= function()
    {
        var tr= Balloon.createElement("tr",this.tbody);
        tr.style.height= "19px";
        this.createButton("-/+", tr).onclick= function() { this.Kalk.processInvertSignal(); };
        this.createButton("÷", tr).onclick= function() { this.Kalk.processDivision(); };
        this.createButton("4", tr, "right").onclick= function() { this.Kalk.processDigit("4"); };
        this.createButton("5", tr).onclick= function() { this.Kalk.processDigit("5"); };
        this.createButton("6", tr, "left").onclick= function() { this.Kalk.processDigit("6"); };
        var btn= this.createButton("+", tr);
        btn.onclick= function() { this.Kalk.processPlus(); };
        with( btn )
        {
            style.height= "60px";
            parentNode.rowSpan= 3;
        }
    };

Kalk.prototype.TR5= function()
    {
        var tr= Balloon.createElement("tr",this.tbody);
        tr.style.height= "19px";
        this.createButton("%", tr).onclick= function() { this.Kalk.processPercent(); };
        this.createButton("X", tr).onclick= function() { this.Kalk.processMultiply(); };
        this.createButton("1", tr, "right").onclick= function() { this.Kalk.processDigit("1"); };
        this.createButton("2", tr).onclick= function() { this.Kalk.processDigit("2"); };
        this.createButton("3", tr, "left").onclick= function() { this.Kalk.processDigit("3"); };
    };

Kalk.prototype.TR6= function()
    {
        var tr= Balloon.createElement("tr",this.tbody);
        tr.style.height= "19px";
        this.createButton("#", tr).onclick= function() { this.Kalk.processSubtotal(); };
        this.createButton("=", tr).onclick= function() { this.Kalk.processShowResult(); };
        var btn= this.createButton("0", tr, "right");
        btn.onclick= function() { this.Kalk.processDigit("0"); };
        btn.style.width= "40px";
        this.createButton("00", tr).onclick= function() { this.Kalk.processDigit("00"); };
        var btnComma= this.createButton(",", tr, "left");
        btnComma.onclick= function() { this.Kalk.processDigit(","); };
        btnComma.parentNode.style.width= "40px";
    };

Kalk.prototype.createOKorCancelButton= function(strValue,td)
    {
        var btn= Balloon.createElement("input");
        btn.Kalk= this;
        with( btn )
        {
            type= "button";
            className= "form_button";
            value= strValue;
            style.width= "70px"
        }
        td.appendChild(btn);
        return btn;
    };

Kalk.prototype.OKandCancel= function()
    {
        var tr= Balloon.createElement("tr",this.tbody);
        tr.style.height= "5px";
        var td= Balloon.createElement("td",tr);
        td.colSpan= "6";
        tr= Balloon.createElement("tr",this.tbody);
        tr.style.height= "19px";
        tr.align= "center";
        td= Balloon.createElement("td",tr);
        td.colSpan= "6";
        this.createOKorCancelButton("OK",td).onclick= function() { this.Kalk.OK(); };
        Balloon.createElement("span",td).innerHTML= "&nbsp;&nbsp;";
        this.createOKorCancelButton("Cancela",td).onclick= function() { this.Kalk.Cancel(); };
    };
    
Kalk.prototype.OK= function()
    {
        this.processShowResult();
        if( this.onFinish ) this.onFinish(true);
    };
    
Kalk.prototype.Cancel= function()
    {
        if( this.onFinish ) this.onFinish(false);
    };

Kalk.prototype.processDigit= function(key)
    {
        if( this.justResult )
        {
            this.txtBuffer.value= "";
            this.justResult= false;
        }
        if( key != ',' || this.txtBuffer.value.indexOf(',') < 0 )
        {
            this.txtBuffer.value= this.txtBuffer.value + key;
        }
        this.txtBuffer.focus();
    };

Kalk.prototype.finishLastMultiplyOrDivision= function(blnPerc)
    {
        if( this.lastOperation == "*" || this.lastOperation == "/" )
        {
            var number= this.getNumber();
            this.restoreTape();
            
            var strPerc;
            if( blnPerc )
            {
                strPerc= this.format(number) + "%";
                number/= 100;
            }
            
            if( this.lastOperation == "*" )
            {
                this.printInTape( number, "X", strPerc );
                this.lastResult*= number;
            } else
            {
                this.printInTape( number, "÷", strPerc );
                this.lastResult/= number;
            }
            this.numItems++;
            return true;
        } else
        {
            return false;
        }
    };

Kalk.prototype.processShowResult= function(blnPerc)
    {
        var blnFinish= this.isBufferEmpty();
        if( !blnFinish )
        {
            blnFinish= this.finishLastMultiplyOrDivision(blnPerc);
        }
        if( blnFinish && this.numItems > 0 )
        {
            this.printInTape( this.lastResult, "=", this.numItems );
            this.showLastResult();
            this.lastOperand= this.lastResult;
            this.lastResult= "";
            this.lastOperation= "";
            this.numItems= 0;
        } else
        {
            this.txtBuffer.focus();
        }
    };

Kalk.prototype.processPlus= function()
    {
        if( this.txtBuffer.value == this.getPercentQuestion() )
        {
            var perc= this.lastResult * (this.lastOperand/100);
            this.printInTape( perc, "+", this.lastOperand + "%" );
            this.lastOperand= perc;
        } else
        {
            if( !this.isBufferEmpty() )
            {
                
                this.lastOperand= this.getNumber();
            }
            this.printInTape( this.lastOperand, "+" );
        }
        if( this.lastResult == "" )
        {
            this.lastResult= this.lastOperand;
        } else
        {
            this.lastResult+= this.lastOperand;
        }
        this.numItems++;
        this.showLastResult();
        this.lastOperation= "+";
    };

Kalk.prototype.processMinus= function()
    {
        if( this.txtBuffer.value == this.getPercentQuestion() )
        {
            var perc= this.lastResult * (this.lastOperand/100);
            this.printInTape( perc, "-", this.lastOperand + "%" );
            this.lastOperand= perc;
        } else
        {
            if( !this.isBufferEmpty() )
            {
                this.lastOperand= this.getNumber();
            }
            this.printInTape( this.lastOperand, "-" );
        }
        if( this.lastResult == "" )
        {
            this.lastResult= - this.lastOperand;
        } else
        {
            this.lastResult-= this.lastOperand;
        }
        this.numItems++;
        this.showLastResult();
        this.lastOperation= "-";
    };

Kalk.prototype.processMultiplyOrDivision= function(oper, operForDisplay)
    {
        var blnShowSubtotal= false;
        if( !this.isBufferEmpty() )
        {
            blnShowSubtotal= (this.lastOperation == "*" || this.lastOperation == "/");
            if( !blnShowSubtotal )
            {
                blnShowSubtotal= (this.lastResult != "");
                this.processPlus();
            }
        } else
        {
            if( this.lastOperand != "" || this.lastResult != "" )
            {
                if( this.lastResult == "" )
                {
                    this.lastResult= this.lastOperand;
                }
                blnShowSubtotal= true;
            }
        }
        if( blnShowSubtotal )
        {
            this.processSubtotal();
        }
        this.saveTape();
        this.numItems++;
        this.printInTape( "", operForDisplay );
        this.showLastResult();
        this.lastOperation= oper;
    };

Kalk.prototype.processMultiply= function()
    {
        this.processMultiplyOrDivision("*","X");
    };

Kalk.prototype.processDivision= function()
    {
        this.processMultiplyOrDivision("/","÷");
    };

Kalk.prototype.processInvertSignal= function()
    {
        if( this.isBufferEmpty() && this.lastOperand != "" )
        {
            this.txtBuffer.value= this.lastOperand;
            this.justResult= false;
        }
        if( !this.isBufferEmpty() )
        {
            var strNumber= new String(this.getNumber() * -1);
            this.txtBuffer.value= strNumber.replace(".",",");
        }
        this.txtBuffer.focus();
    };

Kalk.prototype.processPercent= function()
    {
        this.txtBuffer.focus();
        if( this.isBufferEmpty() ) return;
        
        if( this.lastOperation == "*" || this.lastOperation == "/" )
        {
            this.processShowResult(true);
        } else 
        {
            if( this.lastOperation == "+" || this.lastOperation == "-" )
            {
                this.lastOperand= this.getNumber();
                this.justResult= true;
                if( this.numItems > 1 )
                {
                    this.processSubtotal();
                }
                this.txtBuffer.value= this.getPercentQuestion();
            }
        }
    };
    
Kalk.prototype.getPercentQuestion= function()
    {
        return "Somar ou subtrair " + this.lastOperand + "%?";
    };

Kalk.prototype.processClear= function(force)
    {
        if( this.txtBuffer.value == "" || force )
        {
            this.lastResult= "";
            this.lastOperation= "";
            this.lastOperand= "";
            this.justResult= false;
            this.numItems= 0;
            if( !force )
            {
                this.printInTape(this.lastResult, "C");
            }
        }
        this.txtBuffer.value= "";
        if( !force )
        {
            this.txtBuffer.focus();
        }
    };

Kalk.prototype.processBack= function()
    {
        if( !this.isBufferEmpty() )
        {
            this.txtBuffer.value= this.txtBuffer.value.substr(0, this.txtBuffer.value.length-1);
        }
        this.txtBuffer.focus();
    };

Kalk.prototype.processSubtotal= function()
    {
        var blnFinish= this.isBufferEmpty();
        if( !blnFinish )
        {
            blnFinish= this.finishLastMultiplyOrDivision();
        }
        if( blnFinish )
        {
            this.printInTape( this.lastResult, "#" );
            this.showLastResult();
        }
    };

Kalk.prototype.setValue= function(strValue)
    {
        this.txtBuffer.value= strValue;
        this.justResult= false;
    };

Kalk.prototype.format= function(value)
    {
        var strValue;
        if( this.slPrecision.value != "F" )
        {
            var number= new Number(value);
            strValue= number.toFixed(this.slPrecision.value);
        } else
        {
            strValue= new String(value);
        }
        return strValue.replace(".",",");
    };

Kalk.prototype.showLastResult= function()
    {
        this.txtBuffer.value= this.format(this.lastResult);
        this.justResult= true;
        this.txtBuffer.focus();
    };

Kalk.prototype.isBufferEmpty= function()
    {
        return this.justResult || (this.txtBuffer.value == "");
    };

Kalk.prototype.getNumber= function()
    {
        return new Number( this.txtBuffer.value.replace(",", ".") );
    };

Kalk.prototype.saveTape= function()
    {
        this.savedTape= this.divTape.innerHTML;
    };

Kalk.prototype.restoreTape= function()
    {
        this.divTape.innerHTML= this.savedTape;
    };

Kalk.prototype.clearTape= function()
    {
        this.processClear(true);
        this.createTape(this.divTape.parentNode,"");
    };

Kalk.prototype.createTape= function(par,inner)
    {
        var blnAttach= false;
        if( Balloon.is_ie || !this.divTape )
        {
            if( this.divTape )
            {
                par.removeChild( this.divTape );
            }
            this.divTape= Balloon.createElement("div");
            blnAttach= true;
        }
        
        with( this.divTape.style )
        {
            overflowY= "scroll";
            overflowX= "auto";
            width= "135px";
            height= "150px";
            fontFamily= "monospace";
            fontSize= "8pt";
        }
        this.divTape.innerHTML= inner;
        if( blnAttach )
        {
            par.appendChild( this.divTape );
        }
        this.divTape.scrollTop= this.divTape.scrollTop + this.divTape.scrollHeight;
    };

Kalk.prototype.printInTape= function(value, oper, perc)
    {
        var strSaida;
        if( oper == 'C' )
        {
            strSaida= "------------";
        } else
        {
            if( value != "" )
            {
                strSaida= this.format(value);
                if( oper == '=' )
                {
                    strSaida= "<span style=\"text-decoration:underline\">" + strSaida + "</span>";
                }
            } else
            {
                strSaida= "";
            }
        }
        strSaida+= Kalk.nonBreakableSpace + oper + Kalk.nonBreakableSpace;
        if( typeof perc != "undefined" )
        {
            strSaida= "(" + perc + ")" + Kalk.nonBreakableSpace + Kalk.nonBreakableSpace + strSaida;
        }
        if( oper == '-' || oper == 'C' )
        {
            strSaida= "<span style=\"color:red\">" + strSaida + "</span>";
            if( oper == 'C' )
            {
                strSaida+= Kalk.breakLine;
            }
        }
        if( oper == '=' )
        {
            strSaida= "<b style=\"color:" + (value < 0 ? "red" : "green") + "\">" + 
                        strSaida + "</b>" + Kalk.breakLine;
        }
        this.createTape( this.divTape.parentNode, this.divTape.innerHTML + strSaida + Kalk.breakLine );
    };

KalkBalloon= function () // class constructor
    {
        this.theBalloon= new Balloon(215,300);
        this.Kalk= new Kalk(this.theBalloon.balloonArea);
        this.Kalk.balloon= this;
        this.readonly= false;
    };
    
KalkBalloon.prototype.show = function(txtCtrl)
    {
        with( this.Kalk )
        {
            if (typeof txtCtrl == "string")
            {
                txtCtrl= document.getElementById(txtCtrl);
            }
            if( typeof txtCtrl.value == "string" )
            {
                setValue( txtCtrl.value );
            }
            this.Kalk.onFinish= function(blnOK)
                {
                    if( blnOK && !this.balloon.readonly )
                    {
                        txtCtrl.value= this.format( this.lastOperand );
                    }
                    this.balloon.hide();
                };
        }
        this.theBalloon.show( txtCtrl );
        this.Kalk.show();
    };

KalkBalloon.prototype.hide = function()
    {
        this.theBalloon.hide();
    };
    
KalkBalloon.currentBalloon= null;

KalkBalloon.showKalk= function(txtCtrl,readOnly)
    {
        if( KalkBalloon.currentBalloon == null )
        {
            KalkBalloon.currentBalloon= new KalkBalloon();
        }
        if( typeof readOnly == "boolean" )
        {
            KalkBalloon.currentBalloon.readonly= readOnly;
        }
        KalkBalloon.currentBalloon.show(txtCtrl);
    };
