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 () {
    var args = Array.prototype.slice.apply(arguments);
    var objName = args.shift();
    var callback = args.pop();
    if (!this.test(objName)) {
        var script = document.createElement('SCRIPT');
        script.src = this.dir+objName+'.js';
        script.type = "text/javascript";
        this.documentHead.appendChild(script);
    }
    var i = 0;
    this.interval = window.setInterval(function () {
        try {
            if (typeof window[objName] == 'function' && typeof window[objName].prototype.init != 'undefined') {
                this.obj = new window[objName];
                if (this.obj instanceof window[objName]) {    
                    this.obj.init.apply(this.obj, args);
                    throw true;
                } else throw false;
            } else throw false;
        } catch (e) {
            if (e) {
                window.clearInterval(this.interval);
                callback(this.obj);
            } else {
                this.obj = false;
            }
        }
        i++;
        if (i >= 100) {
            window.clearInterval(this.interval);
        }
    }.bindTo(this), 10)
}

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