﻿function ElementFader(objectName, element_id)
{
    var m_Element = document.getElementById(element_id);
    
    var m_Interval = null;
    var m_StartOpacity = 0.0;
    var m_CurrentOpacity = 0.0;
    var m_EndOpacity = 0.0;
    var m_Factor = 0.25;
    
    this.Repeat = false;
    
    this.SetFactor = function(value) { m_Factor = value; }
    this.GetFactor = function() { return m_Factor; }
    
    // Sets the opacity of the element.
    this.SetOpacity = function(opacity)
    {
        m_CurrentOpacity = opacity;
        
        if(opacity == 0) {
            m_Element.style.visibility = "hidden";
            return;
        }
        
        m_Element.style.visibility = "visible";
        m_Element.style.opacity = opacity;
        m_Element.style.filter = "alpha(opacity = " + (opacity * 100) + ")"; // for IE
    }
    
    // Returns the current opacity of the element.
    this.GetOpacity = function(opacity)
    {
        return m_CurrentOpacity;
    }
    
    // Sets the factor used in the linear interpolation for fading.
    this.SetFactor = function(factor)
    {
        m_Factor = factor;
    }
    
    // Starts fading the element.
    this.Fade = function(start_opacity, end_opacity)
    {
        m_StartOpacity = start_opacity;
        m_EndOpacity = end_opacity;
        
        if(m_Interval != null) {
            clearInterval(m_Interval);
            m_Interval = null;
        }
        
        this.SetOpacity(m_StartOpacity);
        m_Interval = setInterval(objectName + ".DoFade()", 25);
    }
    
    this.DoFade = function()
    {
        var opacity = m_CurrentOpacity + (m_EndOpacity - m_CurrentOpacity) * m_Factor;
        this.SetOpacity(opacity);
        
        if(m_CurrentOpacity >= m_EndOpacity - 0.05 && m_CurrentOpacity <= m_EndOpacity + 0.05) {
            if(this.Repeat == true) {
                this.SetOpacity(m_StartOpacity);
            } else {
                this.SetOpacity(m_EndOpacity);
                clearInterval(m_Interval);
                m_Interval = null;
            }
        }
    }
}
