/*
 * $Id$
 * $URL$
 */

/*jslint browser: true, undef: true, evil: false,
    onevar: true, debug: false, on: false, eqeqeq: true */
/*global LMI, YAHOO, self, window*/

/**
 * @fileOverview Initialization routines
 * @name Init
 */

/**
 * Initialization functions
 * @constructor
 * @memberOf LMI
 * @name Init
 */
LMI.Init = function() {
    // private vars
    var inited = false,
        funcs = [],
        errors = [];

    /**
     * after init is called the "addFunction" method is
     * replaced with this one which simply throws an error
     * @name addFunctionError
     * @function
     * @memberOf LMI.Init
     * @private
     */
    function addFunctionError() {
        throw new Error( 'an attempt was made to add an init function after all init functions have been called' );
    }

    /**
     * Add an init function to be called on page load
     * @name addFunction
     * @function
     * @memberOf LMI.Init
     * @static
     * @param {Function} func   the function to call
     * @param {Integer} pri     functions with the same priority are called in
     *                          the order that they were added.  Lower numbers
     *                          are called before larger numbers. (Default: 50)
     */
    function addFunction( func, pri ) {
        pri = pri || 50;
        var i = funcs.length - 1;
        while( i >= 0 && funcs[i][1] > pri ) {
            --i;
        }
        funcs.splice( i + 1, 0, [ func, pri ] );
    }

    /**
     * Add an init function to be called on page load
     * @name getErrors
     * @function
     * @memberOf LMI.Init
     * @static
     * @return {Array} an array of exceptions that occured during init
     */
    function getErrors() {
        return errors;
    }

    /**
     * Run all the init functions and destroy the init array.
     * @name init
     * @function
     * @memberOf LMI.Init
     * @throws Exception
     * @private
     */
    function init() {
        var i, len;

        // quit if this function has already been called
        if( inited ) {
            return;
        }
        inited = true;

        for( i = 0, len = funcs.length; i < len; ++i ) {
            try {
                funcs[i][0]();
            } catch( e ) {
                errors.push( e );
            }
        }

        funcs = null;  // clean up to free up some memory
        LMI.Init.addFunction = addFunctionError;
    }
    if( self !== top && document.all ) {
        // this fixes an issue in IE when you have LMI.Init in in iframe as well as in the parent doc
        YAHOO.util.Event.on( window, 'load', init );
    } else {
        YAHOO.util.Event.onDOMReady( init );
    }

    return {
        addFunction: addFunction,
        getErrors: getErrors
    };
}();

