// File: balloons.js
// Description: Implementa o recurso de balões para uso de dimensões, calculadoras, agenda, etc
// Author: Rogério Ramos - rogerio@kankei.com.br
// Obs:
//      - Para balões com calendários, incluir antes "calendar.js" e um skin
// Date: 08/jun/2006
// Version: 1.0
// Copyright: Kankei Software e Consultoria Ltda. - http://www.kankei.com.br


Balloon= function (iWidth,iHeight,imgurl) // class constructor
    {
        if (imgurl == null) 
            imgurl = "images/";            
        Balloon.imagesFolder= imgurl;
        
        this.Width= (typeof iWidth != "undefined" ? new Number(iWidth).valueOf() : 250);
        this.Height= (typeof iHeight != "undefined" ? new Number(iHeight).valueOf() : 150);

        var parent = document.getElementsByTagName("body")[0];
        this.ControlsBind = null;

	    var table= Balloon.createElement("table");
	    table.cellSpacing = 0;
	    table.cellPadding = 0;
	    table.border= 0;
        var tbody = Balloon.createElement("tbody", table);
        var row= Balloon.createElement("tr", tbody);
        Balloon.createImgCell(row,"bse",Balloon.larguraBordaEsquerda,Balloon.alturaBordaMenor);
        
        var cell= Balloon.createElement("td", row);
        Balloon.createSimpleImg(cell,"bstse");
        Balloon.createSimpleImg(cell,"bsu");
        Balloon.createSimpleImg(cell,"bstsd");
        
        cell= Balloon.createImgCell(row,"bsd",Balloon.larguraBordaDireita,Balloon.alturaBordaMenor);
        img= Balloon.createSimpleImg( cell, "closebox" );
        with( img )
        {
            width= 11;
            height= 11;
            style.cursor= "pointer";
            style.position= "relative";
            style.left= "-26px";
        }; // criar closebox
        img.theBalloon= this;
        Balloon.addEvent(img, "click", Balloon.is_ie ?
                                            function(ev) { ev.srcElement.theBalloon.hide(); } :
                                            function(ev) { ev.target.theBalloon.hide(); } );
        
        row= Balloon.createElement("tr", tbody);
        Balloon.createImgCell(row,"bes",Balloon.larguraBordaEsquerda,this.Height);
        this.balloonArea= Balloon.createElement("td", row);
        if( Balloon.is_ie )
        {
            this.balloonArea.background= Balloon.imagesFolder + "bfun.png";
        } else
        {
            this.balloonArea.style.backgroundColor= '#E6E5E5';
        }
        Balloon.createImgCell(row,"bdi",Balloon.larguraBordaDireita,this.Height);

        row= Balloon.createElement("tr", tbody);
        Balloon.createImgCell(row,"bie",Balloon.larguraBordaEsquerda,Balloon.alturaBordaMenor);
        
        cell= Balloon.createElement("td", row);
        Balloon.createSimpleImg(cell,"bstie");
        Balloon.createSimpleImg(cell,"bin");
        Balloon.createSimpleImg(cell,"bstid");

        Balloon.createImgCell(row,"bid",Balloon.larguraBordaDireita,Balloon.alturaBordaMenor);

	    table.style.position = "absolute";
	    table.style.display = "none";
        parent.appendChild(table);

        if( Balloon.is_ie ) 
        {
            this.iframeEl = parent.insertBefore(createIframeToFixIEbug(), table);
            this.iframeElSeta = parent.insertBefore(createIframeToFixIEbug(), table);
        }
        
	    this.element= table;

};
    
function createIframeToFixIEbug()
{
    var iframeEl = Balloon.createElement("iframe");
    iframeEl.frameBorder = 0;
    iframeEl.src = "javascript:;";
    iframeEl.style.display = "none";
    iframeEl.style.position = "absolute";
    iframeEl.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)";
    return iframeEl;
}
    
Balloon.is_ie = ( /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent) );
Balloon.alturaBordaMenor= 23;
Balloon.alturaBordaMaior= 77;
Balloon.larguraBordaEsquerda= 23;
Balloon.larguraBordaDireita= 30;
Balloon.larguraSeta= 105;

Balloon.createElement = function(type, parent) 
    {
	    var el = null;
	    if (document.createElementNS) 
	    {
		    // use the XHTML namespace; IE won't normally get here unless
		    // _they_ "fix" the DOM2 implementation.
		    el = document.createElementNS("http://www.w3.org/1999/xhtml", type);
	    } else 
	    {
		    el = document.createElement(type);
	    }
	    if (typeof parent != "undefined") 
	    {
		    parent.appendChild(el);
	    }
	    return el;
    };
    
Balloon.createSimpleImg = function(parent,imgID)
    {
        var img= Balloon.createElement("img", parent);
        img.border= 0;
        var imgName= imgID + ".png";
        img.src= Balloon.imagesFolder + imgName;
        img.id= imgID; 
        img.setAttribute("rsrc", imgName);
        return img;
    }
    
Balloon.createImgCell = function(row, imgID, largura, altura)
    {
        var cell= Balloon.createElement("td", row);
        var img= Balloon.createSimpleImg(cell, imgID);
        img.width= largura; 
        img.height= altura;
        return cell;
    };
    
Balloon.addEvent = function(el, evname, func) 
    {
	    if (el.attachEvent) { // IE
		    el.attachEvent("on" + evname, func);
	    } else if (el.addEventListener) { // Gecko / W3C
		    el.addEventListener(evname, func, true);
	    } else {
		    el["on" + evname] = func;
	    }
    };
    
Balloon.pageWidth = function() 
    {
        return window.innerWidth != null ? 
                    window.innerWidth : 
                    document.documentElement && document.documentElement.clientWidth ? 
                        document.documentElement.clientWidth :
                        document.body != null ? document.body.clientWidth : null;
    };
    
Balloon.pageHeight = function() 
    {
        return window.innerHeight != null ? 
                    window.innerHeight : 
                    document.documentElement && document.documentElement.clientHeight ? 
                        document.documentElement.clientHeight:document.body != null ? 
                            document.body.clientHeight : null;
    };

Balloon.posLeft = function() 
    {
        return typeof window.pageXOffset != 'undefined' ? 
                    window.pageXOffset :
                    document.documentElement && document.documentElement.scrollLeft ? 
                        document.documentElement.scrollLeft :
                        document.body.scrollLeft ? document.body.scrollLeft : 0;
    };
    
    
Balloon.posTop = function() 
    {
        return typeof window.pageYOffset != 'undefined' ? 
                    window.pageYOffset :
                    document.documentElement && document.documentElement.scrollTop ? 
                        document.documentElement.scrollTop : 
                        document.body.scrollTop ? document.body.scrollTop : 0;
    };

Balloon.findPosX = function(obj)
    {
           var curleft = 0;
           if (obj.offsetParent)
        {

            while (obj.offsetParent)
            {
                curleft += obj.offsetLeft;
                obj = obj.offsetParent;
            }
            if ( obj != null )
            {
                curleft += obj.offsetLeft;
            }
        } else 
        {
            if( obj.x )
            {
                curleft += obj.x;
            }
        }
        return curleft;
    };

Balloon.findPosY = function(obj)
    {
        var curtop = 0;
        if (obj.offsetParent)
        {
            while (obj.offsetParent)
            {
                curtop += obj.offsetTop;
                obj = obj.offsetParent;
            }
            if ( obj != null )
            {
                curtop += obj.offsetTop;
            }
        } else 
        {
            if( obj.y )
            {
                curtop += obj.y;
            }
        }
        return curtop;
    };

   
Balloon.prototype.show = function(oCtrl)
    {
        this.pontaSetaX = Math.floor(Balloon.findPosX(oCtrl) + (oCtrl.offsetWidth/4));
        this.pontaSetaY = Math.floor(Balloon.findPosY(oCtrl) + (oCtrl.offsetHeight/2));
        
        this.balloonRealHeight= this.Height + Balloon.alturaBordaMenor + Balloon.alturaBordaMaior;
        this.balloonRealWidth= this.Width + Balloon.larguraBordaEsquerda + Balloon.larguraBordaDireita;
        
        var areaAcima= this.pontaSetaY - Balloon.posTop();
        var areaEsquerda= this.pontaSetaX - Balloon.posLeft();
        this.blnUpperBalloon= areaAcima > (Balloon.pageHeight() / 2);
        this.blnLeftBalloon= areaEsquerda > (Balloon.pageWidth() / 2 );
        
        if( this.blnUpperBalloon && this.pontaSetaY <= this.balloonRealHeight )
        {
            this.blnUpperBalloon= false;
        }

        var iTop= (this.blnUpperBalloon ? 
                            this.pontaSetaY - this.balloonRealHeight : 
                            this.pontaSetaY);
        var iLeft= ((this.blnLeftBalloon ? 
                            this.pontaSetaX - this.balloonRealWidth + oCtrl.offsetWidth : 
                            this.pontaSetaX
                     ) - Balloon.larguraBordaEsquerda);
        
        this.element.style.top = iTop + 'px';
        this.element.style.left = iLeft + 'px';
        this.FixIEPNGTransparencyAndSizes();

        if ( this.iframeEl )
        {   // fix IE bug quando overlap SELECT e outros controles "windowed"
            var alturaSeta= Balloon.alturaBordaMaior - Balloon.alturaBordaMenor;
            with( this.iframeEl )
            {
                style.left = this.element.style.left;
                style.top  = (iTop + (this.blnUpperBalloon ? 0 : alturaSeta)) + "px";
                style.width  = this.balloonRealWidth + "px";
                style.height = (this.balloonRealHeight - alturaSeta) + "px";
                style.display = "";
            }
            with( this.iframeElSeta )
            {
                style.left = (iLeft + (this.blnLeftBalloon ? 
                                        (this.balloonRealWidth - Balloon.larguraBordaEsquerda - Balloon.larguraSeta) :
                                        Balloon.larguraBordaEsquerda
                                     )) + "px";
                style.top  = (iTop + (this.blnUpperBalloon ? (this.balloonRealHeight - alturaSeta) : 0)) + "px";
                style.width  = Balloon.larguraSeta + "px";
                style.height = alturaSeta + "px";
                style.display = "";
            }
            if ( this.ControlsBind )
            for (var i=0; i < this.ControlsBind.length; i++)
            {
                var oElem = window.parent.document.getElementById(this.ControlsBind[i][0]);
                alert(oElem)
			    if( oElem != null )
			    {
			        oElem.value = this.ControlsBind[i][1]
			        alert(oElem.value)
			    }
            }
            
        }
        
        this.element.style.display = 'block';
    };
    
Balloon.prototype.hide = function()
    {
        this.element.style.display= "none";
        if ( this.iframeEl )
        {
            this.iframeEl.style.display= "none";
            this.iframeElSeta.style.display= "none";
        }
    };

Balloon.prototype.isVisible= function()
    {
        return (this.element.style.display == 'block');
    };

Balloon.prototype.checkUpAndDown = function(img)
    {
        var setupArrow= function(img,isInline) 
                            {       
                                if( isInline )
                                {
                                    img.width= Balloon.larguraSeta;
                                    img.height= Balloon.alturaBordaMaior;
                                    img.style.display= "inline";
                                } else
                                {
                                    img.style.display= "none";
                                }
                            };

        switch( img.id )
        {
        case "bes" : 
        case "bdi" :
            img.height= this.Height;
            break;
        case "bse" :
            img.attributes["rsrc"].value= this.blnUpperBalloon ? "bse.png" : "bse2.png";
            img.height= (this.blnUpperBalloon ? Balloon.alturaBordaMenor : Balloon.alturaBordaMaior);
            break;
        case "bsu" :
            img.attributes["rsrc"].value= this.blnUpperBalloon ? "bsu.png" : "bsu2.png";
            img.height= this.blnUpperBalloon ? Balloon.alturaBordaMenor : Balloon.alturaBordaMaior;
            img.width= this.Width - (this.blnUpperBalloon ? 0 : Balloon.larguraSeta);
            break;
        case "bsd" :
            img.attributes["rsrc"].value= this.blnUpperBalloon ? "bsd.png" : "bsd2.png";
            img.height= this.blnUpperBalloon ? Balloon.alturaBordaMenor : Balloon.alturaBordaMaior;
            break;
        case "bie" :
            img.attributes["rsrc"].value= this.blnUpperBalloon ? "bie2.png" : "bie.png";
            img.height= this.blnUpperBalloon ? Balloon.alturaBordaMaior : Balloon.alturaBordaMenor;
            break;
        case "bin" :
            img.attributes["rsrc"].value= this.blnUpperBalloon ? "bin2.png" : "bin.png";
            img.height= this.blnUpperBalloon ? Balloon.alturaBordaMaior : Balloon.alturaBordaMenor;
            img.width= this.Width - (this.blnUpperBalloon ? Balloon.larguraSeta : 0);
            break;
        case "bid" :
            img.attributes["rsrc"].value= this.blnUpperBalloon ? "bid2.png" : "bid.png";
            img.height= this.blnUpperBalloon ? Balloon.alturaBordaMaior : Balloon.alturaBordaMenor;
            break;
        case "bstse" :
            setupArrow(img, !this.blnUpperBalloon && !this.blnLeftBalloon);
            break;
        case "bstsd" :
            setupArrow(img, !this.blnUpperBalloon && this.blnLeftBalloon);
            break;
        case "bstie" :
            setupArrow(img, this.blnUpperBalloon && !this.blnLeftBalloon);
            break;
        case "bstid" :
            setupArrow(img, this.blnUpperBalloon && this.blnLeftBalloon);
            break;
        }
    };

Balloon.prototype.FixIEPNGTransparencyAndSizes = function()
    {
        var arrImages = this.element.getElementsByTagName("img");
        for(var i=0; i < arrImages.length; i++)
        {
            if( arrImages[i].attributes["rsrc"] )
            {
                this.checkUpAndDown( arrImages[i] );
			    if( Balloon.is_ie ) // Checa se é IE
			    {
			        if( arrImages[i].style.display != "none" )
			        {
				        arrImages[i].style.filter= "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',src='" +
				            Balloon.imagesFolder + arrImages[i].attributes["rsrc"].value + "',sizingMethod='crop')";		
				        arrImages[i].src= Balloon.imagesFolder + "transparent.gif";
				    }
			    } else
			    {
				    arrImages[i].src= Balloon.imagesFolder + arrImages[i].attributes["rsrc"].value;
			    }
            }   
        }
    };

// Balões com calendários. Para usar, necessário incluir "calendar.js"

CalendarBalloon= function () // class constructor
    {
        this.theBalloon= new Balloon(230,200);
        this.theCalendar= new Calendar(0);
        this.theCalendar.create( this.theBalloon.balloonArea );
        this.UseIframeToFixIEbug= false; // Já há um balão de fundo
        this.readonly= false;
        this.theCalendar.show();
    };
    
CalendarBalloon.prototype.show = function(txtCtrl)
    {
        with( this.theCalendar )
        {
            if (typeof txtCtrl == "string")
            {
                txtCtrl= document.getElementById(txtCtrl);
            }
            setDateFormat( "%d/%m/%Y" );
            if( typeof txtCtrl.value == "string" )
            {
                parseDate( txtCtrl.value );
            }
            yearStep= 1;
            onSelected= function (cal) 
                        {
                            if( cal.dateClicked && !cal.balloon.readonly )
                            {
                                txtCtrl.value= cal.date.print( cal.dateFormat );
                                cal.balloon.hide();
                            }
                        };
        }
        this.theCalendar.balloon= this;
        this.theBalloon.show( txtCtrl );
    };

CalendarBalloon.prototype.hide = function()
    {
        this.theBalloon.hide();
    };
    
CalendarBalloon.currentBalloon= null;

CalendarBalloon.showCalendar= function(txtCtrl,readOnly)
    {
        if( CalendarBalloon.currentBalloon == null )
        {
            CalendarBalloon.currentBalloon= new CalendarBalloon();
        }
        if( typeof readOnly == "boolean" )
        {
            CalendarBalloon.currentBalloon.readonly= readOnly;
        }
        CalendarBalloon.currentBalloon.show(txtCtrl);
    };
    
IFrameBalloon= function(iWidth,iHeight,imgurl) // class constructor
    {
        this.theBalloon= new Balloon(iWidth,iHeight,imgurl);
        this.theWaitWarning= Balloon.createElement("span", this.theBalloon.balloonArea);
        this.theWaitWarning.innerHTML= "<p align=\"center\"><b>Aguarde..</b></p>";
	    this.theWaitWarning.style.display= "none";
        this.theFrame = Balloon.createElement("iframe", this.theBalloon.balloonArea);
        this.theFrame.frameBorder = 0;
        this.theFrame.style.width  = iWidth + "px";
        this.theFrame.style.height = iHeight + "px";
    	this.theFrame.style.display= "none";
        this.theFrame.balloon= this;
        this.onload= null;
    };

IFrameBalloon.prototype.show = function(txtCtrl,strURL)
    {
        if (typeof txtCtrl == "string")
        {
            txtCtrl= document.getElementById(txtCtrl);
        }
	    this.theFrame.style.display= "none";
        this.theWaitWarning.style.display = "block";
        
        if( Balloon.is_ie )
        {
            this.theFrame.onreadystatechange = 
                    function()
                    {
                        if( this.readyState == "complete" )
                        {
                            this.balloon.theWaitWarning.style.display = "none";
                            this.style.display = "block";
                            if( this.balloon.onload )
                            {
                                this.balloon.onload(this.balloon);
                            }
                        }
                    };
        } else
        {
            this.theFrame.onload= function()
                                    {
                                        this.balloon.theWaitWarning.style.display = "none";
                                        this.style.display = "block";
                                        if( this.balloon.onload )
                                        {
                                            this.balloon.onload(this.balloon);
                                        }
                                    };
        }
        this.theFrame.src= strURL;
        this.theBalloon.show( txtCtrl );
    };

IFrameBalloon.prototype.hide = function()
    {
        this.theBalloon.hide();
    };

IFrameBalloon.currentBalloon= null;

IFrameBalloon.showFrame= function(txtCtrl,strURL,onload)
    {
        if( IFrameBalloon.currentBalloon == null )
        {
            IFrameBalloon.currentBalloon= new IFrameBalloon(505,400);
        }
        IFrameBalloon.currentBalloon.show(txtCtrl,strURL);
        if( onload )
        {
            IFrameBalloon.currentBalloon.onload= onload;
        }
    };

IFrameBalloon.showFrameEx= function(alt, larg, txtCtrl,urlimg,strURL,onload_event)
    {
        if( IFrameBalloon.currentBalloon == null )
        {
            IFrameBalloon.currentBalloon= new IFrameBalloon(alt,larg,urlimg);
            
        }
        IFrameBalloon.currentBalloon.show(txtCtrl,strURL);
        if( onload_event )
        {
            IFrameBalloon.currentBalloon.onload= onload_event;
        }
    };

    
IFrameBalloon.hideFrame= function()
    {
        if( IFrameBalloon.isFrameVisible() )
        {
            IFrameBalloon.currentBalloon.hide();
        }
    }
    
IFrameBalloon.isFrameVisible= function()
    {
        if( IFrameBalloon.currentBalloon == null )
        {
            return false;
        } else
        {
            return IFrameBalloon.currentBalloon.theBalloon.isVisible();
        }
    };

// Algumas funções auxiliares que devem migrar para outros scripts file
function clearControlValue(txtCtrl)
{
    var oCtrl= null;
    var oCtrlDisabled= null;
    if ( typeof txtCtrl == "string" )
    {
        oCtrl= document.getElementById(txtCtrl);
        oCtrlDisabled= document.getElementById(txtCtrl + "_disabled");
    } else
    {
        oCtrl= txtCtrl;
    }
    if( oCtrl != null )
    {
        oCtrl.value= '';
    }
    if( oCtrlDisabled != null )
    {
        oCtrlDisabled.value= '';
    }
}

function submitOnchangeEvent(strKey)
{
	var oFld= document.getElementById("acao");
	if( oFld != null ) oFld.value= "onchange";
	oFld= document.getElementById("controlKey");
	if( oFld != null ) oFld.value= strKey;
	document.forms[0].submit();
}
