var Loader = function () {
    this.dir = 'core/js/opt/';
    this.documentHead = document.getElementsByTagName('head')[0];
    this.documentScripts = this.documentHead.getElementsByTagName('script');
};

Loader.prototype.test = function (scriptname) {
    var reg = new RegExp('.*'+this.dir+scriptname+'\.js');
    for (var i=0;i<this.documentScripts.length;i++) {
        if (typeof this.documentScripts[i].src != 'undefined'
            && this.documentScripts[i].src.match(reg)) {
            return true;
        }
    }
    return false;
};

Loader.prototype.instantiate = function (constructor, args, callback) {
    if (!this.test(constructor)) {
        var script = document.createElement('SCRIPT');
        script.src = this.dir+constructor+'.js';
        script.type = "text/javascript";
        this.documentHead.appendChild(script);
    }
    var i = 0;
    this.interval = window.setInterval(function () {
        try {
            if (typeof window[constructor] == 'function' && typeof window[constructor].prototype.init != 'undefined') {
                this.obj = new window[constructor]();
                if (this.obj instanceof window[constructor]) {
                    this.obj.init.apply(this.obj, args);
                    throw true;
                } else {
                    throw false;
                }
            } else {
                throw false;
            }
        } catch (e) {
            if (e) {
                window.clearInterval(this.interval);
                if (typeof callback == 'function') {
                    callback(this.obj);
                }
            }
        }
        i++;
        if (i >= 100) {
            window.clearInterval(this.interval);
        }
    }.bindTo(this), 100);
    return this.obj;
};

eventHandler.addLoadEvent(function () {
    window.loader = new Loader();
});
