﻿//
//  animblock.js
//
//  Animated blocks that handle attracts and releases to/from the magnet
//

var g_aAnimBlocks = new Array();
var g_animDuration = 0;
var g_animTimeout = -1;
var g_animCallback = null;

//
//                      AnimBlock
//
//  Constructor
//
function AnimBlock(n)
{
    this.handle = findName( 'imgMagnetBlock' + n );
    this.animX = findName( 'anMagBlockX' + n );
    this.animY = findName( 'anMagBlockY' + n );
    this.anim = findName( 'anMagBlock' + n );
    this.animate = _animBlockAnimate;
    this.X = 0;
    this.Y = 0;
    this.N = n;
}

//
//                      _animBlockAnimate
//
function _animBlockAnimate( src, fromX, fromY, toX, toY, duration )
{
    with( this )
    {
        animX.From = fromX;
        animY.From = fromY;
        animX.To = toX;
        animY.To = toY;
        X = toX;
        Y = toY;
        var secs = duration.toString().substring(0,5);
        animX.Duration = animY.Duration = "0:0:" + secs;
        this.handle.Opacity = 1;
        if( src != null )
        {
            this.handle.Source = 'images/' + src;
        }
        anim.begin();
        
        // see if this one drives the call back
        if( duration > g_animDuration )
        {
            if( g_animTimeout != -1 )
            {
                clearTimeout( g_animTimeout );
            }
            var dur = Math.round( duration * 1000 );
            g_animTimeout = setTimeout( "animBlockDone()", dur );
            g_animDuration = duration;
        }
    }
}

//
//                      animBlockDone
//
//  Called when the longest of a group of animations finishes
//
function animBlockDone()
{
    g_animTimeout = -1;
    
    if( g_animCallback != null )
    {
        g_animCallback();
    }
    g_animCallback = null;
}


//
//                      initAnimBlocks
//
function initAnimBlocks()
{
    if( g_aAnimBlocks.length == 0 )
    {
        var i;
        for( i = 0; i < 3; i++ )
        {
            g_aAnimBlocks[i] = new AnimBlock( i );
        }
    }
}

//
//                      animSetCallback
//
//  Sets a callback for an upcoming animation or group of animations
//
function animSetCallback( f )
{
    g_animDuration = 0;
    g_animCallback = f;
}
