<commit_before>= render :partial => "pixie"

#error

%ul.filetree
  %li{ :title => "Main" }
    %span.file.script{ 'data-id' => 'main', :class => app.lang } Main
  - if has_access?
    %li{ :title => "Add Library" }
      %span.file.add_library Add Library
  - app.libraries.each do |library|
    %li.closed{ :title => library.title, 'data-library_id' => library.id }
      %span.folder= library.title
      %ul
        - if has_access?
          %li{ :title => "New Script"}
            %span.file.new_script New Script
        - library.scripts.each do |script|
          %li{ :title => script.title }
            %span.file.script{ 'data-id' => script.id, :class => script.lang }= script.title
            .tab_data{ :id => "script#{script.id}", 'data-lang' => script.lang }
              - form_for [:developer, script] do |form|
                = form.hidden_field :code, { :id => "script_code#{script.id}" }
                = form.text_area :src, { :id => "script_src#{script.id}" }
              %button.save Save

  %li.closed{ :title => "Resources" }
    %span.folder.resources Resources
    %ul
      %li.closed{ :title => "Sprites" }
        %span.folder.sprites Sprites
        %ul
          - if has_access?
            %li{ :title => "New Sprite" }
              %span.file.new_sprite New Sprite
            %li{ :title => "Import Sprites" }
              %span.file.import_sprites Import Sprites
          - app.app_sprites.each do |app_sprite|
            - title = app_sprite.name
            %li{ :title => title }
              %span.file.sprite{ 'data-id' => app_sprite.id, 'data-width' => app_sprite.width, 'data-height' => app_sprite.height, :style => "background-image: url(#{app_sprite.data_url})" }= title
      %li.closed{ :title => "Data" }
        %span.folder.data Data
        %ul
          - if has_access?
            %li{ :title => "New Datum" }
              %span.file.new_datum New Datum
              .tab_data.new_datum
                - form_tag :action => :set_app_data do
                  = fields_for :app_datum do |form|
                    = form.hidden_field :name, :id => nil
                    = form.text_area :json, :id => nil
                %button.save Save

          - app.app_data.each do |app_datum|
            - title = app_datum.name
            %li{ :title => title}
              %span.file.datum{ 'data-id' => app_datum.id }= title
              .tab_data{ :id => "datum#{app_datum.id}" }
                - form_tag :action => :set_app_data do
                  = hidden_field_tag :app_datum_id, app_datum.id, :id => nil
                  = fields_for :app_datum do |form|
                    = form.hidden_field :name, :value => app_datum.name, :id => nil
                    = form.text_area :json, :value => app_datum.json, :id => nil
                %button.save Save

  %li{ :title => "Documentation" }
    %span.file.documentation Documentation

  #scriptmain.tab_data{ 'data-lang' => app.lang }
    - form_for [:developer, app] do |form|
      = form.hidden_field :code
      = form.text_area :src
    %button.save Save
  #documentation.tab_data
    %iframe.no_border{:src => "/production/apps/#{app.id}/docs/index.html", :width => "100%", :height => 600}

#tabs
  %ul

.actions
  %button#run Run App
  = link_to "Download Libs", "/developer/apps/#{app.id}/lib.js"

#testZone
  %span#close_app.ui-icon.ui-icon-close
  %h3.ui-widget-header= app.title
  %iframe#testFrame{ :width => app.width, :height => app.height }

#newCanvasModal.modalElement
  %p
    = label_tag :resize_width, "width"
    = text_field_tag :resize_width, 32, {:title => 'width'}
  %p
    = label_tag :resize_height, "height"
    = text_field_tag :resize_height, 32, {:title => 'height'}

  = button_to_function "New Canvas", "newCanvas()"

#importSpriteModal.modalElement
  %table.sprites{ :summary => "User sprites" }
    = render :partial => 'developer/apps/import_sprite', :collection => @user_sprites

  = button_to_function "Import Sprites", "importSprites()"

#scriptTitleModal.modalElement
  %p
    = label_tag :new_script_title, "Title"
    = text_field_tag :new_script_title, '', {:title => 'Title'}

  = button_to_function "Save", "saveNewScript()"

#datumTitleModal.modalElement
  %p
    = label_tag :new_datum_title, "Title"
    = text_field_tag :new_datum_title, '', {:title => 'Title'}

  = button_to_function "Save", "setDatumTitle()"

%ul#libraries.round
  - Library.all.each do |library|
    %li{ "data-library_id" => library.id }
      = check_box_tag "library", "1", app.libraries.include?(library), :id => nil, :name => nil
      = library.title
  %li{ "data-library_id" => "new" } New Library

#newLibraryModal.modalElement
  = render :partial => "developer/libraries/form"

#tips{:style => "display: none;"}
  .tip{ 'data-element_selector' => "#scriptmain"}
    .text
      This is the code editor where you can edit your applications in the CoffeeScript language.
  .tip{ 'data-element_selector' => "ul.filetree"}
    .text
      The files you need to create your app are here.
  .tip{ 'data-element_selector' => "#run"}
    .text
      Press the run button to run your app!
  .tip{ 'data-element_selector' => "#testZone"}
    .text
      Test how your app runs then modify your code and run it again.
  .tip{ 'data-element_selector' => "ul.filetree"}
    .text
      That's it for the tips. The IDE is a work in progress, so ask or leave feedback if you have any questions!
      = link_to "Feedback", "/survey", :class => "button"
  .next
    %button.next_tip.right Next
  .close
    %button.close_tip.left Close

:plain
  <script type="text/coffeescript">
    window.currentPanel
    shouldCreateEditor = false
    pixieEditorIds = 0
    newScriptIds = 0
    langClass = null

    window.newCanvas = ->
      shouldCreateEditor = false
      langClass = "sprite"

      pixieEditor = createPixelEditor
        width: $('#resize_width').val()
        height: $('#resize_height').val()

      pixieEditorId = "pixie_editor" + (pixieEditorIds++)

      pixieEditor.attr('id', pixieEditorId).addClass('tab_data').appendTo('ul.filetree')

      $tabs.tabs 'add', "#" + pixieEditorId, "Sprite" + pixieEditorIds, 0

      $.modal.close()

    window.importSprites = ->
      if $('.import_sprite.selected').length < 1
        alert "Please select sprites to import"
      else
        sprite_data = $('.import_sprite.selected').map ->
          'app_sprite_id': $(this).attr('data-id')
          'app_id': #{app.id}
          'app_sprite_name': $(this).attr('data-title')

        notify "Importing, please wait..."

        postData =
          'format': 'json',
          'sprite_data': sprite_data

        $.post '/developer/apps/#{app.id}/import_app_sprites', postData, (data) ->
          $(".import_sprite.selected").removeClass('selected')

          if data.status == "error"
            notify data.message
            return

          $.each data, (i, sprite) ->
            updateSpriteNode sprite
            $("#tabs ul li").eq($("#tabs").tabs('option', 'selected')).find('span').first().click()

          notify("Saved!")
        , 'json'

        $.modal.close()

    window.saveNewScript = ->
      title = $("#new_script_title").val()
      $("#tabs ul li.ui-tabs-selected a").text(title)

      tabLi = $("#tabs ul li.ui-state-active")

      panel = $("#tabs .ui-tabs-panel").not('.ui-tabs-hide')
      form = panel.find('form')

      form.find('input[name="script[title]"]').val(title)

      postData = form.serialize()

      notify("Saving...")

      $.post form.attr('action'), postData, (data) ->
        script_id = data.script.id
        libId = data.script.lib_id
        lang = data.script.lang

        setSaved(tabLi)

        form.attr("action", "/developer/scripts/" + script_id)
        form.append("<input type='hidden' name='_method' value='put' />")
        panel.find('button.new_save').removeClass('new_save').addClass('save')

        newScriptNode = $("<span />").text(title).attr('data-id', panel.attr('id')).addClass("new file script " + lang)
        node = $("<li />").attr("title", title).append(newScriptNode)

        libUl = $('ul.filetree li[data-library_id='+libId+'] > ul')

        libUl.append(node).children().removeClass("last").last().addClass('last')

      , "json"

      $.modal.close()

    window.setDatumTitle = ->
      title = $("#new_datum_title").val()

      $("#tabs ul li.ui-tabs-selected a").text(title)

      tabLi = $("#tabs ul li.ui-state-active")

      panel = $("#tabs .ui-tabs-panel").not('.ui-tabs-hide')
      form = panel.find('form')

      form.find('input[name="app_datum[name]"]').val(title)

      form.ajaxSubmit
        dataType: "json"
        success: (data) ->
          setSaved(tabLi)

          appDatum = data.app_datum
          console.log appDatum

          panel.removeClass("new_datum")

          form.append("<input type='hidden' value='"+ appDatum.id +"' name='app_datum_id'/>")

          newDatumNode = $("<span />").text(title).attr('data-id', panel.attr('id')).addClass("new file datum")
          node = $("<li />").attr("title", title).append(newDatumNode)

          destinationUl = $('ul.filetree li[title=Data] > ul')

          destinationUl.append(node).children().removeClass("last").last().addClass('last')

      $.modal.close()

    window.newLibraryScript = (libraryId) ->
      scriptLang = "coffeescript"
      langClass = scriptLang

      newScriptId = "new_script" + (newScriptIds++)

      scriptEditor = createNewScriptEditor
        lang: scriptLang
        libraryId: libraryId
        idNum: newScriptId

      scriptEditor.attr('id', newScriptId).addClass('tab_data').appendTo('ul.filetree')

      $tabs.tabs 'add', "#" + newScriptId, "Script" + newScriptIds, 0

    createNewScriptEditor = (options) ->
      lang = options.lang
      idNum = options.idNum

      editorHtml = $('<div />').append($(#{render(:partial => "script_form").to_json}))
      editorHtml.find('input[name="script[code]"]').attr('id', "new_script_code" + idNum)
      editorHtml.find('input[name="script[lib_id]"]').val(options.libraryId)
      editorHtml.find('textarea').attr('id', "new_script_src" + idNum)
      editorHtml.attr('data-lang', lang)
      $("<button>Save</button>").addClass("new_save").appendTo(editorHtml)

      return editorHtml

    window.updateSpriteNode = (appSprite) ->
      cssImageUrl = appSprite.cssImageUrl
      height = appSprite.height
      id = appSprite.id
      title = appSprite.name
      width = appSprite.width

      node = $(".filetree .sprite[data-id=" + id + "]")

      if node.length
        spriteNode = node
        node = node.parent()
      else
        node = $("<li />").attr("title", title)
        spriteNode = $("<span />").text(title).attr('data-id', id).attr('data-width', width).attr('data-height', height).addClass("file sprite").appendTo(node)
        $('.filetree .sprites').next().append(node).children().removeClass('last').last().addClass('last')

      spriteNode.css "backgroundImage", cssImageUrl

      # Reload tab
      spriteNode.click()

    createLibraryNode = (library) ->
      id = library.id
      title = library.title

      node = $("<li />").attr("title", title).attr('data-library_id', id)
      folderNode = $("<span />").text(title).addClass("folder").appendTo(node)
      fileList = $("<ul />").appendTo(node)

      newScriptNode = $("<li />").attr("title", "New Script").append(
        $("<span />").addClass("file new_script").text("New Script")
      ).appendTo(fileList)

      $.each library.scripts, (i, script) ->
        scriptId = script.id
        title = script.title
        lang = script.lang
        code = script.code
        src = script.src

        scriptNode = $("<li />").attr("title", title)
        $("<span />").attr("data-id", scriptId).addClass("file script " + lang).text(title).appendTo(scriptNode)

        editorHtml = $('<div />').append($(#{render(:partial => "script_form").to_json}))
        editorHtml.find('input[name="script[code]"]').attr('id', "script_code" + scriptId).val(code)
        editorHtml.find('input[name="script[lib_id]"]').val(id)
        editorHtml.find('textarea').attr('id', "script_src" + scriptId).val(src)
        editorHtml.attr('data-lang', lang).attr("id", "script" + scriptId).addClass("tab_data")
        $("<button>Save</button>").addClass("save").appendTo(editorHtml)

        editorHtml.appendTo(scriptNode)

        scriptNode.appendTo(fileList)

      $("ul.filetree > li").eq(1).after(node)

    window.createEditor = (ui) ->
      panel = $(ui.panel)
      tab = $(ui.tab)
      lang = panel.attr('data-lang')
      code_id = "#" + panel.find('input[name="script[code]"], input[name="app[code]"]').attr('id')
      src_id = "#" + panel.find('textarea').attr('id')

      savedCode = $(src_id).val()

      compiled_js = ''

      compile_source = if lang == 'coffeescript'
        (source) ->
          compiled_js = ''
          try
            compiled_js = CoffeeScript.compile source, noWrap: true
            $(code_id).val compiled_js
            $('#error').hide()
          catch error
            $('#error').text(error.message).show()
      else
        (source) ->
          compiled_js = source
          $(code_id).val compiled_js

      compile_source($(src_id).val())

      codeTextArea = $(src_id).get(0)
      editor = new CodeMirror.fromTextArea codeTextArea,
        autoMatchParens: true
        content: codeTextArea.value
        height: "600px"
        lineNumbers: true
        parserfile: ["tokenize_" + lang + ".js", "parse_" + lang + ".js"]
        path: "/javascripts/codemirror/"
        stylesheet: ["/stylesheets/codemirror/main.css", "/stylesheets/codemirror/" + lang + "_colors.css"]
        tabMode: "shift"
        textWrapping: false

      $(editor.win.document).bind('keydown', 'ctrl+f', (e) ->
        e.preventDefault()
        e.stopPropagation()
        s = editor.selection() || prompt("Search string")
        if (s)
          c = editor.getSearchCursor(s, true, "")
          c.findNext()
          c.select()

        false
      )

      $(editor.win.document).bind('keydown', 'ctrl+s', (event) ->
        if ($(window.currentPanel).find('button.new_save').length > 0)
          $("#scriptTitleModal").modal
            containerCss:
              height: 75
              width: 175
        else
          notify("Saving...")
          $(window.currentPanel).find('form').ajaxSubmit
            type: 'POST'
            success: -> setSaved()

        event.preventDefault()
      )

      # Listen for keypresses and recompile.
      $(editor.win.document).keyup ->
        currentCode = editor.getCode()

        if currentCode != savedCode
          setUnsaved()
        else
          tab.parent().removeClass("unsaved")

        compile_source(currentCode)
        $(src_id).val(currentCode)

      lang: lang
      updateSaved: () ->
        savedCode = editor.getCode()

    setUnsaved = () ->
      $("#tabs ul li.ui-state-active").addClass("unsaved")

    setSaved = (tabLi) ->
      notify("Saved!")
      tabLi ||= $("#tabs ul li.ui-state-active")

      tabLi.removeClass("unsaved")
      if c = tabLi.find('a').data('updateSaved')
        c()
      else
        debugger

    runApp = (code) ->
      cacheBust = new Date().getTime()
      zone = $("#testZone")
      zone.css({top: 160, left: 640}).show()

      # Recreate iframe
      $("#testFrame").remove()
      iframe = $('<iframe height="#{app.height}" id="testFrame" width="#{app.width}"></iframe>')
      zone.append(iframe)

      sandbox = iframe[0].contentWindow.document
      sandbox.open();

      sandbox.write(#{stylesheet_link_tag('screen.css').to_json})
      sandbox.write(#{javascript_include_tag("http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js").to_json.gsub('/', '\\/')})
      sandbox.write('<script src="/developer/apps/#{app.id}/lib.js?' + cacheBust + '"><\/script>')
      sandbox.write(#{app.template.to_json})
      sandbox.write("<script>var cacheBust = " + cacheBust + "; $(function(){"+ code +"});<\/script>")

      sandbox.close()

      # Set focus
      $("#testFrame")[0].contentWindow.focus()

    closeApp = ->
      $("#testZone").hide()
      $("#testFrame").remove()

    $('#run').click ->
      runApp $('#app_code').val()

    $('#close_app').click ->
      closeApp();

    window.onbeforeunload = ->
      if $("li.unsaved").length > 0
        return "You have some unsaved changes, if you leave now you will lose your work."

    $ ->
      $("#testZone").draggable(
        handle: "h3"
        iframeFix: true
      ).disableSelection()

      $('ul.filetree').treeview()

      $('.filetree .file.documentation').click ->
        shouldCreateEditor = false
        docSelector = "#documentation"
        langClass = "documentation"

        if $('#tabs ul li a[href="' + docSelector + '"]').length
          $('#tabs ul li a[href="' + docSelector + '"]').click()
        else
          $tabs.tabs 'add', docSelector, $(this).text(), 0

      $('.import_sprite').live 'click', ->
        $(this).toggleClass('selected')

      $('.filetree .file.new_datum').live 'click', ->
        shouldCreateEditor = false
        langClass = "data"
        lang = "dummy"

        newTabContents = $(this).next().clone()

        newId = "new_datum" + (newScriptIds++)
        newIdSelector = "#" + newId

        newTabContents.attr('id', newId).appendTo($('ul.filetree'))

        $tabs.tabs 'add', newIdSelector, $(this).text(), 0

        $datumTextArea = $(newIdSelector).find("textarea")

        datumTextArea = $datumTextArea.get(0)

        savedCode = $datumTextArea.val()

        editor = new CodeMirror.fromTextArea datumTextArea,
          autoMatchParens: true
          content: datumTextArea.value
          height: "600px"
          lineNumbers: true
          parserfile: ["tokenize_" + lang + ".js", "parse_" + lang + ".js"]
          path: "/javascripts/codemirror/"
          stylesheet: ["/stylesheets/codemirror/main.css", "/stylesheets/codemirror/" + lang + "_colors.css"]
          tabMode: "shift"
          textWrapping: false

        # Listen for keypresses and recompile.
        $(editor.win.document).keyup ->
          currentCode = editor.getCode()

          if currentCode != savedCode
            setUnsaved()
          else
            $("#tabs a[href='"+datumSelector+"']").parent().removeClass("unsaved")

          try
            JSON.parse(currentCode)
            $datumTextArea.val(currentCode)
            $('#error').hide()
          catch error
            $('#error').text(error.message).show()

      $('.filetree .file.datum').live 'click', ->
        shouldCreateEditor = false
        langClass = "data"

        if $(this).hasClass("new")
          datumSelector = "#" + $(this).attr('data-id')
        else
          datumSelector = "#datum" + $(this).attr('data-id')
        lang = "dummy"

        if $('#tabs ul li a[href="' + datumSelector + '"]').length
          $('#tabs ul li a[href="' + datumSelector + '"]').click()

        else
          $tabs.tabs 'add', datumSelector, $(this).text(), 0

          $datumTextArea = $(datumSelector).find("textarea")

          datumTextArea = $datumTextArea.get(0)

          savedCode = $datumTextArea.val()

          editor = new CodeMirror.fromTextArea datumTextArea,
            autoMatchParens: true
            content: datumTextArea.value
            height: "600px"
            lineNumbers: true
            parserfile: ["tokenize_" + lang + ".js", "parse_" + lang + ".js"]
            path: "/javascripts/codemirror/"
            stylesheet: ["/stylesheets/codemirror/main.css", "/stylesheets/codemirror/" + lang + "_colors.css"]
            tabMode: "shift"
            textWrapping: false

          # Listen for keypresses and recompile.
          $(editor.win.document).keyup ->
            currentCode = editor.getCode()

            if currentCode != savedCode
              setUnsaved()
            else
              $("#tabs a[href='"+datumSelector+"']").parent().removeClass("unsaved")

            try
              JSON.parse(currentCode)
              $datumTextArea.val(currentCode)
              $('#error').hide()
            catch error
              $('#error').text(error.message).show()

      $('.filetree .file.script').live 'click', ->
        shouldCreateEditor = true
        if $(this).hasClass("new")
          scriptSelector = "#" + $(this).attr('data-id')
        else
          scriptSelector = "#script" + $(this).attr('data-id')

        if $(scriptSelector).parents('#tabs').length
          $('#tabs ul li a[href="' + scriptSelector + '"]').click()
        else
          $tabs.tabs 'add', scriptSelector, $(this).text(), 0

      $('.filetree .file.new_sprite').click ->
        $("#newCanvasModal").modal
          containerCss:
            height: 110,
            width: 180

      $('.filetree .file.import_sprites').click ->
        $("#importSpriteModal").modal()

      $('.filetree .file.new_script').live 'click', ->
        newLibraryScript $(this).parents('[data-library_id]').last().attr('data-library_id')

      $('.filetree .file.add_library').click ->
        pos = $(this).offset()
        pos.top += 20
        $("#libraries").show().offset(pos)

        setTimeout ->
          $(document).one 'click', ->
            $("#libraries").fadeOut()
        , 0

      $('.filetree .file.sprite').live 'click', ->
        shouldCreateEditor = false
        langClass = "sprite"
        appSpriteId = $(this).attr('data-id')
        width = $(this).attr('data-width')
        height = $(this).attr('data-height')

        spriteSelector = "#sprite" + appSpriteId

        if $(spriteSelector).length
          if $(spriteSelector).parents('#tabs').length
            $('#tabs ul li a[href="' + spriteSelector + '"]').click()

            return
          else
            $(spriteSelector).remove()

        bgCss = $(this).css('backgroundImage')
        data = bgCss.substr(4, bgCss.length - 5)
        title = $(this).text()

        pixieEditor = createPixelEditor
          width: width
          height: height
          title: title
          dataUrl: data
          appSpriteId: appSpriteId

        pixieEditor.attr('id', spriteSelector.substr(1)).addClass('tab_data').appendTo($('ul.filetree'))

        $tabs.tabs 'add', spriteSelector, title, 0

      window.currentPanel = $("#scriptmain")

      window.$tabs = $('#tabs').tabs
        add: (event, ui) ->
          $tabs.tabs('select', '#' + ui.panel.id)

          if shouldCreateEditor
            fileData = createEditor(ui)

            $(ui.tab).data('updateSaved', fileData.updateSaved)
            $(ui.tab).parent().find('span.lang').addClass(fileData.lang)
          else
            if langClass
              $(ui.tab).parent().find('span.lang').addClass(langClass)

          langClass = null

        remove: (event, ui) ->
          $(ui.panel).find(".CodeMirror-wrapping").remove()
          $('.filetree').append(ui.panel)

        select: (event, ui) ->
          window.currentPanel = ui.panel

        tabTemplate: '<li><span class="ui-icon ui-icon-close"></span><span class="ui-icon lang"></span><a href="#' + '{href}">#' + '{label}</a></li>'

      $('ul.filetree .file.script').first().click()

      $('button.save').live 'click', ->
        notify("Saving...")
        if $(this).parent().hasClass("new_datum")
          $("#datumTitleModal").modal
            containerCss:
              height: 75
              width: 175
        else
          $(window.currentPanel).find('form').ajaxSubmit
            type: 'POST'
            success: () ->
              setSaved()

      $('button.new_save').live 'click', ->
        $("#scriptTitleModal").modal
          containerCss:
            height: 75
            width: 175

      $('#tabs span.ui-icon-close').live 'click', ->
        parentLi = $(this).parent()

        if !parentLi.hasClass("unsaved") || confirm("You are about to close an unsaved file, continue?")
          index = $('li', $tabs).index(parentLi)
          $tabs.tabs('remove', index)

      $('#tabs span.ui-icon').live 'click', ->
        parentLi = $(this).parent()

        index = $('li', $tabs).index(parentLi)
        $tabs.tabs('select', index)

      $("#libraries li").live "click", (event) ->
        libraryId = $(this).attr("data-library_id")
        checkbox = $(this).children("input")
        boxClick = false

        if $(event.target).is("input")
          boxClick = true

        if libraryId == "new"
          $("#newLibraryModal").modal()
        else
          checked = !(checkbox.attr("checked") ^ boxClick)
          checkbox.attr("checked", checked)

          postData =
            library_id: libraryId

          if checked
            $.post "/developer/apps/#{app.id}/add_library", postData, (data) ->
              createLibraryNode data.library
            , "json"
          else
            $("ul.filetree li[data-library_id='" + libraryId + "']").remove()

            $.post "/developer/apps/#{app.id}/remove_library", postData, (data) ->
              unless data.status == "ok"
                true # TODO Error message
            , "json"

      $("#new_library").ajaxForm
        dataType: "json"
        beforeSerialize: ($form) ->
          $form.find("input[name=app_id]").val(#{app.id})
        success: (data) ->
          createLibraryNode data.library
          $.modal.close()

      $("#tooltip .next_tip").live "click", ->
        nextTip()

      $("#tooltip .close_tip").live "click", ->
        hideTooltip()

      tipIndex = -1
      window.nextTip = () ->
        tipIndex += 1
        tips = $("#tips .tip")
        moreTips = tipIndex < tips.length - 1

        tip = tips.eq(tipIndex)

        targetElement = $(tip.attr("data-element_selector"))

        # TODO Highlight target element

        hideTooltip()

        if tip.length
          tipMessage = tip.html()

          tipMessage += $("#tips .close").html()

          if moreTips
            tipMessage += $("#tips .next").html()

          showTooltip(targetElement, tipMessage)

      nextTip()

  </script>

%style
  :sass
    .import_sprite
      display: inline-block
      padding: 5px
      margin: 3px

      &.selected
        background-color: #1084CE

      img
        height: 50px
        width: 50px<commit_msg>Removed css image sizing to decrease image blur<commit_after>= render :partial => "pixie"

#error

%ul.filetree
  %li{ :title => "Main" }
    %span.file.script{ 'data-id' => 'main', :class => app.lang } Main
  - if has_access?
    %li{ :title => "Add Library" }
      %span.file.add_library Add Library
  - app.libraries.each do |library|
    %li.closed{ :title => library.title, 'data-library_id' => library.id }
      %span.folder= library.title
      %ul
        - if has_access?
          %li{ :title => "New Script"}
            %span.file.new_script New Script
        - library.scripts.each do |script|
          %li{ :title => script.title }
            %span.file.script{ 'data-id' => script.id, :class => script.lang }= script.title
            .tab_data{ :id => "script#{script.id}", 'data-lang' => script.lang }
              - form_for [:developer, script] do |form|
                = form.hidden_field :code, { :id => "script_code#{script.id}" }
                = form.text_area :src, { :id => "script_src#{script.id}" }
              %button.save Save

  %li.closed{ :title => "Resources" }
    %span.folder.resources Resources
    %ul
      %li.closed{ :title => "Sprites" }
        %span.folder.sprites Sprites
        %ul
          - if has_access?
            %li{ :title => "New Sprite" }
              %span.file.new_sprite New Sprite
            %li{ :title => "Import Sprites" }
              %span.file.import_sprites Import Sprites
          - app.app_sprites.each do |app_sprite|
            - title = app_sprite.name
            %li{ :title => title }
              %span.file.sprite{ 'data-id' => app_sprite.id, 'data-width' => app_sprite.width, 'data-height' => app_sprite.height, :style => "background-image: url(#{app_sprite.data_url})" }= title
      %li.closed{ :title => "Data" }
        %span.folder.data Data
        %ul
          - if has_access?
            %li{ :title => "New Datum" }
              %span.file.new_datum New Datum
              .tab_data.new_datum
                - form_tag :action => :set_app_data do
                  = fields_for :app_datum do |form|
                    = form.hidden_field :name, :id => nil
                    = form.text_area :json, :id => nil
                %button.save Save

          - app.app_data.each do |app_datum|
            - title = app_datum.name
            %li{ :title => title}
              %span.file.datum{ 'data-id' => app_datum.id }= title
              .tab_data{ :id => "datum#{app_datum.id}" }
                - form_tag :action => :set_app_data do
                  = hidden_field_tag :app_datum_id, app_datum.id, :id => nil
                  = fields_for :app_datum do |form|
                    = form.hidden_field :name, :value => app_datum.name, :id => nil
                    = form.text_area :json, :value => app_datum.json, :id => nil
                %button.save Save

  %li{ :title => "Documentation" }
    %span.file.documentation Documentation

  #scriptmain.tab_data{ 'data-lang' => app.lang }
    - form_for [:developer, app] do |form|
      = form.hidden_field :code
      = form.text_area :src
    %button.save Save
  #documentation.tab_data
    %iframe.no_border{:src => "/production/apps/#{app.id}/docs/index.html", :width => "100%", :height => 600}

#tabs
  %ul

.actions
  %button#run Run App
  = link_to "Download Libs", "/developer/apps/#{app.id}/lib.js"

#testZone
  %span#close_app.ui-icon.ui-icon-close
  %h3.ui-widget-header= app.title
  %iframe#testFrame{ :width => app.width, :height => app.height }

#newCanvasModal.modalElement
  %p
    = label_tag :resize_width, "width"
    = text_field_tag :resize_width, 32, {:title => 'width'}
  %p
    = label_tag :resize_height, "height"
    = text_field_tag :resize_height, 32, {:title => 'height'}

  = button_to_function "New Canvas", "newCanvas()"

#importSpriteModal.modalElement
  %table.sprites{ :summary => "User sprites" }
    = render :partial => 'developer/apps/import_sprite', :collection => @user_sprites

  = button_to_function "Import Sprites", "importSprites()"

#scriptTitleModal.modalElement
  %p
    = label_tag :new_script_title, "Title"
    = text_field_tag :new_script_title, '', {:title => 'Title'}

  = button_to_function "Save", "saveNewScript()"

#datumTitleModal.modalElement
  %p
    = label_tag :new_datum_title, "Title"
    = text_field_tag :new_datum_title, '', {:title => 'Title'}

  = button_to_function "Save", "setDatumTitle()"

%ul#libraries.round
  - Library.all.each do |library|
    %li{ "data-library_id" => library.id }
      = check_box_tag "library", "1", app.libraries.include?(library), :id => nil, :name => nil
      = library.title
  %li{ "data-library_id" => "new" } New Library

#newLibraryModal.modalElement
  = render :partial => "developer/libraries/form"

#tips{:style => "display: none;"}
  .tip{ 'data-element_selector' => "#scriptmain"}
    .text
      This is the code editor where you can edit your applications in the CoffeeScript language.
  .tip{ 'data-element_selector' => "ul.filetree"}
    .text
      The files you need to create your app are here.
  .tip{ 'data-element_selector' => "#run"}
    .text
      Press the run button to run your app!
  .tip{ 'data-element_selector' => "#testZone"}
    .text
      Test how your app runs then modify your code and run it again.
  .tip{ 'data-element_selector' => "ul.filetree"}
    .text
      That's it for the tips. The IDE is a work in progress, so ask or leave feedback if you have any questions!
      = link_to "Feedback", "/survey", :class => "button"
  .next
    %button.next_tip.right Next
  .close
    %button.close_tip.left Close

:plain
  <script type="text/coffeescript">
    window.currentPanel
    shouldCreateEditor = false
    pixieEditorIds = 0
    newScriptIds = 0
    langClass = null

    window.newCanvas = ->
      shouldCreateEditor = false
      langClass = "sprite"

      pixieEditor = createPixelEditor
        width: $('#resize_width').val()
        height: $('#resize_height').val()

      pixieEditorId = "pixie_editor" + (pixieEditorIds++)

      pixieEditor.attr('id', pixieEditorId).addClass('tab_data').appendTo('ul.filetree')

      $tabs.tabs 'add', "#" + pixieEditorId, "Sprite" + pixieEditorIds, 0

      $.modal.close()

    window.importSprites = ->
      if $('.import_sprite.selected').length < 1
        alert "Please select sprites to import"
      else
        sprite_data = $('.import_sprite.selected').map ->
          'app_sprite_id': $(this).attr('data-id')
          'app_id': #{app.id}
          'app_sprite_name': $(this).attr('data-title')

        notify "Importing, please wait..."

        postData =
          'format': 'json',
          'sprite_data': sprite_data

        $.post '/developer/apps/#{app.id}/import_app_sprites', postData, (data) ->
          $(".import_sprite.selected").removeClass('selected')

          if data.status == "error"
            notify data.message
            return

          $.each data, (i, sprite) ->
            updateSpriteNode sprite
            $("#tabs ul li").eq($("#tabs").tabs('option', 'selected')).find('span').first().click()

          notify("Saved!")
        , 'json'

        $.modal.close()

    window.saveNewScript = ->
      title = $("#new_script_title").val()
      $("#tabs ul li.ui-tabs-selected a").text(title)

      tabLi = $("#tabs ul li.ui-state-active")

      panel = $("#tabs .ui-tabs-panel").not('.ui-tabs-hide')
      form = panel.find('form')

      form.find('input[name="script[title]"]').val(title)

      postData = form.serialize()

      notify("Saving...")

      $.post form.attr('action'), postData, (data) ->
        script_id = data.script.id
        libId = data.script.lib_id
        lang = data.script.lang

        setSaved(tabLi)

        form.attr("action", "/developer/scripts/" + script_id)
        form.append("<input type='hidden' name='_method' value='put' />")
        panel.find('button.new_save').removeClass('new_save').addClass('save')

        newScriptNode = $("<span />").text(title).attr('data-id', panel.attr('id')).addClass("new file script " + lang)
        node = $("<li />").attr("title", title).append(newScriptNode)

        libUl = $('ul.filetree li[data-library_id='+libId+'] > ul')

        libUl.append(node).children().removeClass("last").last().addClass('last')

      , "json"

      $.modal.close()

    window.setDatumTitle = ->
      title = $("#new_datum_title").val()

      $("#tabs ul li.ui-tabs-selected a").text(title)

      tabLi = $("#tabs ul li.ui-state-active")

      panel = $("#tabs .ui-tabs-panel").not('.ui-tabs-hide')
      form = panel.find('form')

      form.find('input[name="app_datum[name]"]').val(title)

      form.ajaxSubmit
        dataType: "json"
        success: (data) ->
          setSaved(tabLi)

          appDatum = data.app_datum
          console.log appDatum

          panel.removeClass("new_datum")

          form.append("<input type='hidden' value='"+ appDatum.id +"' name='app_datum_id'/>")

          newDatumNode = $("<span />").text(title).attr('data-id', panel.attr('id')).addClass("new file datum")
          node = $("<li />").attr("title", title).append(newDatumNode)

          destinationUl = $('ul.filetree li[title=Data] > ul')

          destinationUl.append(node).children().removeClass("last").last().addClass('last')

      $.modal.close()

    window.newLibraryScript = (libraryId) ->
      scriptLang = "coffeescript"
      langClass = scriptLang

      newScriptId = "new_script" + (newScriptIds++)

      scriptEditor = createNewScriptEditor
        lang: scriptLang
        libraryId: libraryId
        idNum: newScriptId

      scriptEditor.attr('id', newScriptId).addClass('tab_data').appendTo('ul.filetree')

      $tabs.tabs 'add', "#" + newScriptId, "Script" + newScriptIds, 0

    createNewScriptEditor = (options) ->
      lang = options.lang
      idNum = options.idNum

      editorHtml = $('<div />').append($(#{render(:partial => "script_form").to_json}))
      editorHtml.find('input[name="script[code]"]').attr('id', "new_script_code" + idNum)
      editorHtml.find('input[name="script[lib_id]"]').val(options.libraryId)
      editorHtml.find('textarea').attr('id', "new_script_src" + idNum)
      editorHtml.attr('data-lang', lang)
      $("<button>Save</button>").addClass("new_save").appendTo(editorHtml)

      return editorHtml

    window.updateSpriteNode = (appSprite) ->
      cssImageUrl = appSprite.cssImageUrl
      height = appSprite.height
      id = appSprite.id
      title = appSprite.name
      width = appSprite.width

      node = $(".filetree .sprite[data-id=" + id + "]")

      if node.length
        spriteNode = node
        node = node.parent()
      else
        node = $("<li />").attr("title", title)
        spriteNode = $("<span />").text(title).attr('data-id', id).attr('data-width', width).attr('data-height', height).addClass("file sprite").appendTo(node)
        $('.filetree .sprites').next().append(node).children().removeClass('last').last().addClass('last')

      spriteNode.css "backgroundImage", cssImageUrl

      # Reload tab
      spriteNode.click()

    createLibraryNode = (library) ->
      id = library.id
      title = library.title

      node = $("<li />").attr("title", title).attr('data-library_id', id)
      folderNode = $("<span />").text(title).addClass("folder").appendTo(node)
      fileList = $("<ul />").appendTo(node)

      newScriptNode = $("<li />").attr("title", "New Script").append(
        $("<span />").addClass("file new_script").text("New Script")
      ).appendTo(fileList)

      $.each library.scripts, (i, script) ->
        scriptId = script.id
        title = script.title
        lang = script.lang
        code = script.code
        src = script.src

        scriptNode = $("<li />").attr("title", title)
        $("<span />").attr("data-id", scriptId).addClass("file script " + lang).text(title).appendTo(scriptNode)

        editorHtml = $('<div />').append($(#{render(:partial => "script_form").to_json}))
        editorHtml.find('input[name="script[code]"]').attr('id', "script_code" + scriptId).val(code)
        editorHtml.find('input[name="script[lib_id]"]').val(id)
        editorHtml.find('textarea').attr('id', "script_src" + scriptId).val(src)
        editorHtml.attr('data-lang', lang).attr("id", "script" + scriptId).addClass("tab_data")
        $("<button>Save</button>").addClass("save").appendTo(editorHtml)

        editorHtml.appendTo(scriptNode)

        scriptNode.appendTo(fileList)

      $("ul.filetree > li").eq(1).after(node)

    window.createEditor = (ui) ->
      panel = $(ui.panel)
      tab = $(ui.tab)
      lang = panel.attr('data-lang')
      code_id = "#" + panel.find('input[name="script[code]"], input[name="app[code]"]').attr('id')
      src_id = "#" + panel.find('textarea').attr('id')

      savedCode = $(src_id).val()

      compiled_js = ''

      compile_source = if lang == 'coffeescript'
        (source) ->
          compiled_js = ''
          try
            compiled_js = CoffeeScript.compile source, noWrap: true
            $(code_id).val compiled_js
            $('#error').hide()
          catch error
            $('#error').text(error.message).show()
      else
        (source) ->
          compiled_js = source
          $(code_id).val compiled_js

      compile_source($(src_id).val())

      codeTextArea = $(src_id).get(0)
      editor = new CodeMirror.fromTextArea codeTextArea,
        autoMatchParens: true
        content: codeTextArea.value
        height: "600px"
        lineNumbers: true
        parserfile: ["tokenize_" + lang + ".js", "parse_" + lang + ".js"]
        path: "/javascripts/codemirror/"
        stylesheet: ["/stylesheets/codemirror/main.css", "/stylesheets/codemirror/" + lang + "_colors.css"]
        tabMode: "shift"
        textWrapping: false

      $(editor.win.document).bind('keydown', 'ctrl+f', (e) ->
        e.preventDefault()
        e.stopPropagation()
        s = editor.selection() || prompt("Search string")
        if (s)
          c = editor.getSearchCursor(s, true, "")
          c.findNext()
          c.select()

        false
      )

      $(editor.win.document).bind('keydown', 'ctrl+s', (event) ->
        if ($(window.currentPanel).find('button.new_save').length > 0)
          $("#scriptTitleModal").modal
            containerCss:
              height: 75
              width: 175
        else
          notify("Saving...")
          $(window.currentPanel).find('form').ajaxSubmit
            type: 'POST'
            success: -> setSaved()

        event.preventDefault()
      )

      # Listen for keypresses and recompile.
      $(editor.win.document).keyup ->
        currentCode = editor.getCode()

        if currentCode != savedCode
          setUnsaved()
        else
          tab.parent().removeClass("unsaved")

        compile_source(currentCode)
        $(src_id).val(currentCode)

      lang: lang
      updateSaved: () ->
        savedCode = editor.getCode()

    setUnsaved = () ->
      $("#tabs ul li.ui-state-active").addClass("unsaved")

    setSaved = (tabLi) ->
      notify("Saved!")
      tabLi ||= $("#tabs ul li.ui-state-active")

      tabLi.removeClass("unsaved")
      if c = tabLi.find('a').data('updateSaved')
        c()
      else
        debugger

    runApp = (code) ->
      cacheBust = new Date().getTime()
      zone = $("#testZone")
      zone.css({top: 160, left: 640}).show()

      # Recreate iframe
      $("#testFrame").remove()
      iframe = $('<iframe height="#{app.height}" id="testFrame" width="#{app.width}"></iframe>')
      zone.append(iframe)

      sandbox = iframe[0].contentWindow.document
      sandbox.open();

      sandbox.write(#{stylesheet_link_tag('screen.css').to_json})
      sandbox.write(#{javascript_include_tag("http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js").to_json.gsub('/', '\\/')})
      sandbox.write('<script src="/developer/apps/#{app.id}/lib.js?' + cacheBust + '"><\/script>')
      sandbox.write(#{app.template.to_json})
      sandbox.write("<script>var cacheBust = " + cacheBust + "; $(function(){"+ code +"});<\/script>")

      sandbox.close()

      # Set focus
      $("#testFrame")[0].contentWindow.focus()

    closeApp = ->
      $("#testZone").hide()
      $("#testFrame").remove()

    $('#run').click ->
      runApp $('#app_code').val()

    $('#close_app').click ->
      closeApp();

    window.onbeforeunload = ->
      if $("li.unsaved").length > 0
        return "You have some unsaved changes, if you leave now you will lose your work."

    $ ->
      $("#testZone").draggable(
        handle: "h3"
        iframeFix: true
      ).disableSelection()

      $('ul.filetree').treeview()

      $('.filetree .file.documentation').click ->
        shouldCreateEditor = false
        docSelector = "#documentation"
        langClass = "documentation"

        if $('#tabs ul li a[href="' + docSelector + '"]').length
          $('#tabs ul li a[href="' + docSelector + '"]').click()
        else
          $tabs.tabs 'add', docSelector, $(this).text(), 0

      $('.import_sprite').live 'click', ->
        $(this).toggleClass('selected')

      $('.filetree .file.new_datum').live 'click', ->
        shouldCreateEditor = false
        langClass = "data"
        lang = "dummy"

        newTabContents = $(this).next().clone()

        newId = "new_datum" + (newScriptIds++)
        newIdSelector = "#" + newId

        newTabContents.attr('id', newId).appendTo($('ul.filetree'))

        $tabs.tabs 'add', newIdSelector, $(this).text(), 0

        $datumTextArea = $(newIdSelector).find("textarea")

        datumTextArea = $datumTextArea.get(0)

        savedCode = $datumTextArea.val()

        editor = new CodeMirror.fromTextArea datumTextArea,
          autoMatchParens: true
          content: datumTextArea.value
          height: "600px"
          lineNumbers: true
          parserfile: ["tokenize_" + lang + ".js", "parse_" + lang + ".js"]
          path: "/javascripts/codemirror/"
          stylesheet: ["/stylesheets/codemirror/main.css", "/stylesheets/codemirror/" + lang + "_colors.css"]
          tabMode: "shift"
          textWrapping: false

        # Listen for keypresses and recompile.
        $(editor.win.document).keyup ->
          currentCode = editor.getCode()

          if currentCode != savedCode
            setUnsaved()
          else
            $("#tabs a[href='"+datumSelector+"']").parent().removeClass("unsaved")

          try
            JSON.parse(currentCode)
            $datumTextArea.val(currentCode)
            $('#error').hide()
          catch error
            $('#error').text(error.message).show()

      $('.filetree .file.datum').live 'click', ->
        shouldCreateEditor = false
        langClass = "data"

        if $(this).hasClass("new")
          datumSelector = "#" + $(this).attr('data-id')
        else
          datumSelector = "#datum" + $(this).attr('data-id')
        lang = "dummy"

        if $('#tabs ul li a[href="' + datumSelector + '"]').length
          $('#tabs ul li a[href="' + datumSelector + '"]').click()

        else
          $tabs.tabs 'add', datumSelector, $(this).text(), 0

          $datumTextArea = $(datumSelector).find("textarea")

          datumTextArea = $datumTextArea.get(0)

          savedCode = $datumTextArea.val()

          editor = new CodeMirror.fromTextArea datumTextArea,
            autoMatchParens: true
            content: datumTextArea.value
            height: "600px"
            lineNumbers: true
            parserfile: ["tokenize_" + lang + ".js", "parse_" + lang + ".js"]
            path: "/javascripts/codemirror/"
            stylesheet: ["/stylesheets/codemirror/main.css", "/stylesheets/codemirror/" + lang + "_colors.css"]
            tabMode: "shift"
            textWrapping: false

          # Listen for keypresses and recompile.
          $(editor.win.document).keyup ->
            currentCode = editor.getCode()

            if currentCode != savedCode
              setUnsaved()
            else
              $("#tabs a[href='"+datumSelector+"']").parent().removeClass("unsaved")

            try
              JSON.parse(currentCode)
              $datumTextArea.val(currentCode)
              $('#error').hide()
            catch error
              $('#error').text(error.message).show()

      $('.filetree .file.script').live 'click', ->
        shouldCreateEditor = true
        if $(this).hasClass("new")
          scriptSelector = "#" + $(this).attr('data-id')
        else
          scriptSelector = "#script" + $(this).attr('data-id')

        if $(scriptSelector).parents('#tabs').length
          $('#tabs ul li a[href="' + scriptSelector + '"]').click()
        else
          $tabs.tabs 'add', scriptSelector, $(this).text(), 0

      $('.filetree .file.new_sprite').click ->
        $("#newCanvasModal").modal
          containerCss:
            height: 110,
            width: 180

      $('.filetree .file.import_sprites').click ->
        $("#importSpriteModal").modal()

      $('.filetree .file.new_script').live 'click', ->
        newLibraryScript $(this).parents('[data-library_id]').last().attr('data-library_id')

      $('.filetree .file.add_library').click ->
        pos = $(this).offset()
        pos.top += 20
        $("#libraries").show().offset(pos)

        setTimeout ->
          $(document).one 'click', ->
            $("#libraries").fadeOut()
        , 0

      $('.filetree .file.sprite').live 'click', ->
        shouldCreateEditor = false
        langClass = "sprite"
        appSpriteId = $(this).attr('data-id')
        width = $(this).attr('data-width')
        height = $(this).attr('data-height')

        spriteSelector = "#sprite" + appSpriteId

        if $(spriteSelector).length
          if $(spriteSelector).parents('#tabs').length
            $('#tabs ul li a[href="' + spriteSelector + '"]').click()

            return
          else
            $(spriteSelector).remove()

        bgCss = $(this).css('backgroundImage')
        data = bgCss.substr(4, bgCss.length - 5)
        title = $(this).text()

        pixieEditor = createPixelEditor
          width: width
          height: height
          title: title
          dataUrl: data
          appSpriteId: appSpriteId

        pixieEditor.attr('id', spriteSelector.substr(1)).addClass('tab_data').appendTo($('ul.filetree'))

        $tabs.tabs 'add', spriteSelector, title, 0

      window.currentPanel = $("#scriptmain")

      window.$tabs = $('#tabs').tabs
        add: (event, ui) ->
          $tabs.tabs('select', '#' + ui.panel.id)

          if shouldCreateEditor
            fileData = createEditor(ui)

            $(ui.tab).data('updateSaved', fileData.updateSaved)
            $(ui.tab).parent().find('span.lang').addClass(fileData.lang)
          else
            if langClass
              $(ui.tab).parent().find('span.lang').addClass(langClass)

          langClass = null

        remove: (event, ui) ->
          $(ui.panel).find(".CodeMirror-wrapping").remove()
          $('.filetree').append(ui.panel)

        select: (event, ui) ->
          window.currentPanel = ui.panel

        tabTemplate: '<li><span class="ui-icon ui-icon-close"></span><span class="ui-icon lang"></span><a href="#' + '{href}">#' + '{label}</a></li>'

      $('ul.filetree .file.script').first().click()

      $('button.save').live 'click', ->
        notify("Saving...")
        if $(this).parent().hasClass("new_datum")
          $("#datumTitleModal").modal
            containerCss:
              height: 75
              width: 175
        else
          $(window.currentPanel).find('form').ajaxSubmit
            type: 'POST'
            success: () ->
              setSaved()

      $('button.new_save').live 'click', ->
        $("#scriptTitleModal").modal
          containerCss:
            height: 75
            width: 175

      $('#tabs span.ui-icon-close').live 'click', ->
        parentLi = $(this).parent()

        if !parentLi.hasClass("unsaved") || confirm("You are about to close an unsaved file, continue?")
          index = $('li', $tabs).index(parentLi)
          $tabs.tabs('remove', index)

      $('#tabs span.ui-icon').live 'click', ->
        parentLi = $(this).parent()

        index = $('li', $tabs).index(parentLi)
        $tabs.tabs('select', index)

      $("#libraries li").live "click", (event) ->
        libraryId = $(this).attr("data-library_id")
        checkbox = $(this).children("input")
        boxClick = false

        if $(event.target).is("input")
          boxClick = true

        if libraryId == "new"
          $("#newLibraryModal").modal()
        else
          checked = !(checkbox.attr("checked") ^ boxClick)
          checkbox.attr("checked", checked)

          postData =
            library_id: libraryId

          if checked
            $.post "/developer/apps/#{app.id}/add_library", postData, (data) ->
              createLibraryNode data.library
            , "json"
          else
            $("ul.filetree li[data-library_id='" + libraryId + "']").remove()

            $.post "/developer/apps/#{app.id}/remove_library", postData, (data) ->
              unless data.status == "ok"
                true # TODO Error message
            , "json"

      $("#new_library").ajaxForm
        dataType: "json"
        beforeSerialize: ($form) ->
          $form.find("input[name=app_id]").val(#{app.id})
        success: (data) ->
          createLibraryNode data.library
          $.modal.close()

      $("#tooltip .next_tip").live "click", ->
        nextTip()

      $("#tooltip .close_tip").live "click", ->
        hideTooltip()

      tipIndex = -1
      window.nextTip = () ->
        tipIndex += 1
        tips = $("#tips .tip")
        moreTips = tipIndex < tips.length - 1

        tip = tips.eq(tipIndex)

        targetElement = $(tip.attr("data-element_selector"))

        # TODO Highlight target element

        hideTooltip()

        if tip.length
          tipMessage = tip.html()

          tipMessage += $("#tips .close").html()

          if moreTips
            tipMessage += $("#tips .next").html()

          showTooltip(targetElement, tipMessage)

      nextTip()

  </script>

%style
  :sass
    .import_sprite
      display: inline-block
      padding: 5px
      margin: 3px

      &.selected
        background-color: #1084CE

{'fraction_non_alphanumeric': 0.1681022243256034, 'fraction_numerical': 0.0032560340747752013, 'mean_word_length': 2.2744064960019834, 'pattern_counts': {'":': 0, '<': 81, '<?xml version=': 0, '>': 339, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5879133', 'n_tokens_mistral': 16485, 'n_tokens_neox': 15919, 'n_words': 3097}