/**
 * Handles the automatic class loading part of Enjin Scripting.
 *
 * @copyright	Interval © 2011
 * @author	Jason Valdron <jason@intervalweb.ca>
 *
 * @project	Enjin
 * @package	Enjin.Scripts
 * @see		http://enjin.intervalweb.ca/
 *
 * @access	public
 */

ClassLoader = {}

/**
 * Contains a list of already loaded class, prevents duplicate loading.
 * @access	public
 * @var         array
 * @static
 */
ClassLoader.imports = [];

/**
 * Includes a class, for example, calling this with
 * "Enjin.Scripts.Template.Form" will load the form class dynamically.
 * @access	public
 * @param	include string
 * @param       completed anonymous function
 * @return	bool
 * @static
 */
ClassLoader.include = function(include, completed){
    
    if($.inArray(include, ClassLoader.imports) === -1){
        ClassLoader.imports.push(include);

        var filePath = include.replace(/\./g, '/') + '.js';
        if(include.indexOf('scripts') == 0 || include.indexOf('plugins') == 0)
        {
            filePath = Settings.enjinPath + filePath;
        }
        
        var lastDot = include.lastIndexOf('.');
        var className = lastDot ? include.substr(lastDot + 1) : include;
        className = className.charAt(0).toUpperCase() + className.slice(1);

        $.ajax({
            url: filePath,
            async: false,
            cache: !Settings.debugging,
            dataType: 'script',
            error: function(httpRequest, message, errorThrown){
                if(errorThrown == 'Not Found')
                {
                    throw 'Include \'' + include + '\' cannot be found.';
                }
                else
                {
                    throw message;
                }
            },
            success: function(){
                var testClassName = className;
                if(window[testClassName] && window[testClassName]['included'])
                {
                    window[testClassName]['included']();
                }
                
                testClassName = 'Plugin_' + className;
                if(window[testClassName] && window[testClassName]['included'])
                {
                    window[testClassName]['included']();
                }
                
                testClassName = 'Plugin_Administration_' + className;
                if(window[testClassName] && window[testClassName]['included'])
                {
                    window[testClassName]['included']();
                }
                
                if(completed)
                {
                    completed();
                }
            }
        });

        return true;
        
    }

    if(completed)
    {
        completed();
    }

    return false;

}
