// singletone for controls handling
(function(){

//private properties
var instance = null;
var threads = {};
var loadedScripts = [];

this.ScriptManager = Class.create({
  
  getInstance:function(){
    if (instance === null)
      throw Error("ScriptManager instance still not created");
    return instance;
  }
  
},{
  
  __construct:function(){
    if (instance !== null)
      throw Error("Only one instance of ScriptManager class allowed (ScriptManager is singletone)");
    instance = this;
    
    var c = ControlsManager.getInstance();
    c.addEventListener('preInit',this.getHandler(this.onControlsManagerPreInit));
    
  },
  
  onControlsManagerPreInit:function(){
    loadedScripts = $('script').map(function(){ return $(this).attr('src'); });
  },
  
  loadScripts:function(files,callback){
    
    if (files.length == 0)
      callback();
    
    if (files.constructor !== Array)
      files = [files];
    
    var threadId = Math.random().toString();
    threads[threadId] = { files:files , callback: callback, loaded:[] };
    
    for (var i=0, l=files.length ; i<l; i++) {
      var hnd = this.getHandler(this.onScriptLoaded,[threadId,files[i]]);
      
      if ($.inArray( files[i], loadedScripts ) !== -1)
        hnd(null,"success");
      else
        $.getScript(files[i],hnd);
    }
    
  },
  
  onScriptLoaded:function(threadId,file,data, textStatus){
    
    //TODO - add support for not loaded scripts error handling
    
    if (textStatus == "success") {
      //adding newly loaded script to list
      if (!$.inArray(file, loadedScripts))
        Array.prototype.push.call(loadedScripts,file);
    
      var thread = threads[threadId];
      Array.prototype.push.call(thread.loaded,file);
      
      if (thread.loaded.length == thread.files.length){ //all requested scripts loaded
        delete(threads[threadId]);
        if (thread.callback.constructor === Function)
          thread.callback();
        delete thread;
      }
    }
    
  }
  
  
  
},[Event]);

})();