 class JThreePreviewController
-  @loadedScriptCount = 0;
-
   @initJThree:(config,codeKey)->
    JThreePreviewController.loadj3Script config,codeKey
     .then ()=>
-     JThreePreviewController.checkFinalize config,codeKey
+     root = config.codes[codeKey].root
      promise = Promise.resolve()
+     if config.codes[codeKey].html?
+       promise = promise.then ()=>
+         JThreePreviewController.loadDebuggerControl root + config.codes[codeKey].html
+      if config.codes[codeKey].css?
+        JThreePreviewController.loadStyle root + config.codes[codeKey].css
      config.codes[codeKey].js.forEach (v,i)=>
        url = v
        if !/https?\:\/\//.exec(v)
-         url = config.codes[codeKey].root + v
+         url = root + v
        promise = promise
         .then ()=>
           JThreePreviewController.loadjsScript url
-        .then ()=>
-          JThreePreviewController.checkFinalize config,codeKey
-      promise
+     promise = promise.then ()=>
+       JThreePreviewController.loadCompleted config,codeKey
+     promise
 
   @loadj3Script:(config,codeKey)->
     new Promise (resolve,reject)=>

        resolve()
      document.body.appendChild jsTag

  @checkFinalize:(config,codeKey)->
    JThreePreviewController.loadedScriptCount++
    if !config.codes[codeKey].js || JThreePreviewController.loadedScriptCount == config.codes[codeKey].js.length+1
      window.j3.lateStart();

module.exports = JThreePreviewController;

        resolve()
      document.body.appendChild j3Tag

  @loadDebuggerControl:(url)->
    new Promise (resolve,reject)=>
      xhr = new XMLHttpRequest()
      xhr.open "GET",url,true
      xhr.responseType = "text"
      xhr.onload = () =>
        document.querySelector ".debugControl"
          .innerHTML = xhr.responseText
        resolve()
      xhr.onerror = (err) =>
        reject();
      xhr.send(null);

  @loadStyle:(url)->
    styleTag = document.createElement 'link'
    styleTag.setAttribute 'rel','stylesheet'
    styleTag.setAttribute 'type','text/css'
    styleTag.setAttribute 'href',url
    document.head.appendChild styleTag

  @loadjsScript:(url)->
    new Promise (resolve,reject)=>
      jsTag = document.createElement 'script'
