window.tooltip = new Class({

    initialize: function( pTarget, pText ){
        this.target = pTarget;
        this.text = pText;
        this.start();
    },

    start: function(){
        this.main = new Element('div', {
            'class': 'ka-tooltip',
            styles: {
                opacity: 0
            }
        }).inject(this.target.getParent('div.kwindow-border'));

        this.bg = new Element('div', {
            'class': 'ka-tooltip-bg',
            styles: {
                opacity: 0.7
            }
        }).inject( this.main )
        .set('tween', {duration: 400});

        this.corner = new Element('div', {
            'class': 'ka-tooltip-corner'
        }).inject( this.bg );

        this.textDiv = new Element('div', {
            'class': 'ka-tooltip-text',
            html: this.text
        }).inject( this.main );

        this.createLoader();

    },

    createLoader: function(){
        this.loader = new Element('img', {
            'class': 'ka-tooltip-loader',
            align: 'left',
            src: '/admin/images/ka-tooltip-loading.gif'
        }).inject( this.textDiv, 'top' );
    },

    stop: function( pText ){
        if( pText ) {
            this.setText( pText );
            this.destroyTimer = (function(){
                this.destroy();
             }.bind(this)).delay(3000);
        } else {
            this.destroy();
        }
        return this;
    },

    setText: function( pText ){
        this.text = pText;
        this.textDiv.set('html', pText);
        this.createLoader();
    },

    destroy: function(){
        this.main.set('tween', {onComplete: function(){
            this.main.destroy();
            this.main = null;
        }.bind(this)});
        this.main.tween('opacity', 0);
    },

    show: function(){
        if( this.destroyTimer ){
            $clear( this.destroyTimer );
            if(this.main)
                this.main.set('tween', {onComplete: $empty});
        }
        if(!this.main) this.start();
        this.main.tween('opacity', 1);
        this.updatePosition();
        this.blink();
    },

    updatePosition: function(){
        this.main.position({
            relativeTo: this.target,
            position: 'top',
            edge: 'center',
            offset: {y: -14, x:-2}
        });
    },

    hide: function(){
        this.main.setStyle('opacity', 0);
    },

    blink: function(){
        this.bg.tween('opacity', 0.7);
        (function(){
            this.bg.tween('opacity', 1);
        }.bind(this)).delay(400);
        this.blink.delay(1400,this);
    }

});