CKEDITOR.disableAutoInline = true

jQuery ($)->
  $.unsavedChanges = false
  window.onbeforeunload = ->
    return "Are you sure you want to leave this page? Your unsaved changes will not be stored!" if $.unsavedChanges
  $(document).ready ->
    # Find blocks
    fetch_blocks = => $(".polyblock[contenteditable='true']").not('.polyblock-condensed')
    blocks = fetch_blocks()
    return unless blocks.length

    # Find switches
    pb_switch = $('.polyblock-switch')
    has_switch = pb_switch.is('*')

    initialize = ->
      # Clone each block and instanciate CKeditor on the original
      blockclones = {}
      instanciateCKEditor = (id)->
        editor = CKEDITOR.inline id,
          on:
            contentDom: =>
              editor.document.on 'keydown', (e)=>
                if (e.data.$.ctrlKey or e.data.$.metaKey) and e.data.$.keyCode == 83
                  try e.data.$.preventDefault()
                  editor.focusManager.blur true
                  $('*:focus').blur()
                  console.log("Before: " + $.unsavedChanges) if verbose
                  saveChanges =>
                    #$.unsavedChanges = false
                    console.log("After: " + $.unsavedChanges) if verbose
                  false
            focus: (e)->
              editorModeOn()
              startListening(id)
            blur: (e)-> stopListening()
      blocks.each ->
        id = $(@).attr('id')
        blockclones[id] = $(@).clone()
        instanciateCKEditor(id) unless $.map(CKEDITOR.instances, (inst, key)-> key).indexOf(id) > -1

      # Wait for changes
      verbose = false
      changeChecker = null
      indicator = $('.pb-change-indicator')
      changeText = $('.pb-change-text')
      startListening = (which)->
        stopListening()
        console.log("I'm listening...") if verbose
        buffer = CKEDITOR.instances[which].getData()
        changeChecker = setInterval ->
          console.log("Checking for changes...") if verbose
          reading = CKEDITOR.instances[which].getData()
          if reading!=buffer and !$.unsavedChanges then showUnsavedChanges()
          else if reading==buffer and $.unsavedChanges then showSavedChanges()
        , 1000
      stopListening = ->
        return unless changeChecker?
        console.log("I'm no longer listening.") if verbose
        clearInterval(changeChecker)
        changeChecker = null
      showUnsavedChanges = =>
        indicator.transition({rotate:"-30deg",color:"red"})
        changeText.html("You have unsaved changes.").transition({color:"red"})
        $.unsavedChanges = true
      showSavedChanges = ->
        indicator.transition({rotate:"0deg",color:"green"})
        changeText.html("All changes saved.").transition({color:"green"})
        # console.log "In function: " + $.unsavedChanges
        $.unsavedChanges = false
        # console.log "In function: " + $.unsavedChanges
      showSavingChanges = =>
        indicator.transition({rotate:"30deg",color:"yellow"})
        changeText.html("Saving changes...").transition({color:"yellow"})

      # Editor functionality toggles
      initialBodyPadding = $('body').css("padding-bottom")
      editorModeOn = (pb)->
        $('#pb_bar').show "slide", {direction:"down"}, 250, ->
          $('body').css("padding-bottom",$("#pb_bar").height() + 20)
          pb?()
      editorModeOff = (pb)->
        $('#pb_bar').hide "slide", {direction:"down"}, 250, ->
          $('body').css("padding-bottom",initialBodyPadding)
          pb?()

      # Change storage
      saveChanges = (cb)->
        stopListening()
        showSavingChanges()
        original_scroll = x: window.scrollX, y: window.scrollY
        pbs = $.map blocks, (block_element, i)->
          block = $(block_element)
          pbid = block.attr('data-pbid')
          pbname = block.attr('data-pbname')
          editor = CKEDITOR.instances[block.attr('id')]
          editor.focus()
          content = editor.getData()
          editor.focusManager.blur true
          $('*:focus').blur()
          { id: pbid, name: pbname, content: content }
        setTimeout (-> window.scrollTo original_scroll.x, original_scroll.y), 1
        $.post "/polyblock/update", {pbs: pbs}, (data)->
          showSavedChanges()
          editorModeOff ->
            alertify.success("Your changes have been saved.") if alertify?
            cb?()
      revertChanges = (pb)->
        return unless confirm("Are you sure you want to discard your changes?")
        editorModeOff ->
          blocks.each -> $(@).replaceWith(blockclones[$(@).attr("id")])
          alertify.success("Your changes have been discarded.") if alertify?

      # Modes
      # currentMode = previousMode = "WYSIWYG"
      # convertToTextarea = (block,content=null,tab="\t")->
      #   tabchars = tab.replace(/\\/,"").length
      #   previous_textarea = $("textarea[data-pbid=#{block.attr("data-pbid")}]")
      #   content ?= if previous_textarea.is("*") then previous_textarea.val() else block.html()
      #   textarea = $('<textarea />')
      #   .addClass("form-control")
      #   .attr("data-pbid",block.attr("data-pbid"))
      #   .val(content)
      #   .css("font-family": 'Monaco, Menlo, Consolas, "Courier New", monospace')
      #   .on "keydown", (e)->
      #       keycode = e.keyCode or e.which
      #       return unless keycode == 9 or keycode == 8 or keycode == 46
      #       start = $(@).get(0).selectionStart
      #       end = $(@).get(0).selectionEnd
      #       if keycode == 9
      #         e.preventDefault()
      #         $(@).val("#{$(@).val().substring(0,start)}#{tab}#{$(@).val().substring(end)}")
      #         $(@).get(0).selectionStart = $(@).get(0).selectionEnd = start + tabchars
      #       else if keycode == 8
      #         return unless currentMode=="HAML" and $(@).val().substring(start-tabchars,start) == tab
      #         e.preventDefault()
      #         $(@).val("#{$(@).val().substring(0,start-tabchars)}#{$(@).val().substring(end)}")
      #         $(@).get(0).selectionStart = $(@).get(0).selectionEnd = start-tabchars
      #       else if keycode == 46
      #         return unless currentMode=="HAML" and $(@).val().substring(start,start+tabchars) == tab
      #         e.preventDefault()
      #         $(@).val("#{$(@).val().substring(0,start)}#{$(@).val().substring(end+tabchars)}")
      #         $(@).get(0).selectionStart = $(@).get(0).selectionEnd = start
      #   replaceIt = (html)=>
      #     if !previous_textarea.is("*") then block.replaceWith(textarea)
      #     else previous_textarea.replaceWith(textarea)
      #     textarea.autosize().focus()
      #   if previousMode != "HAML" then replaceIt(content)
      #   else $.post "/convert_haml_to_html", {haml: content}, (data)=> replaceIt(data)
      # convertFromTextarea = (block)->
      #   textarea = $("textarea[data-pbid=#{block.attr("data-pbid")}]")
      #   replaceIt = (html)=>
      #     console.log "Replacing with html: #{html}"
      #     textarea.replaceWith(block)
      #     block.html(html)
      #   if previousMode != "HAML" then replaceIt(textarea.text())
      #   else $.post "/convert_haml_to_html", {haml: textarea.val()}, (data)=> replaceIt(data)
      #
      # $('#pb_bar_format_buttons button').click (e)->
      #   e.preventDefault()
      #   return if $(@).hasClass("active")
      #   previousMode = currentMode
      #   currentMode = $(@).html()
      #   changeModes = (block)=>
      #     textarea = $("textarea[data-pbid=#{block.attr("data-pbid")}]")
      #     content = if textarea.is("*") then textarea.val() else block.html()
      #     switch currentMode
      #       when "WYSIWYG" then convertFromTextarea block
      #       when "HTML" then convertToTextarea block, html_beautify(content)
      #       when "HAML" then $.post "/convert_html_to_haml", {html: content}, (data)=> convertToTextarea(block,data,"  ")
      #       when "Markdown" then convertToTextarea block, html_beautify(content)
      #   blocks = fetch_blocks() if previousMode == "WYSIWYG"
      #   blocks.each -> changeModes $(@)
      #   $(@).siblings().removeClass("active").end().addClass("active")

      # Button handlers
      $('#pb_bar_revert').click (e)->
        e.preventDefault()
        revertChanges()
      $('#pb_bar_save').click (e)->
        e.preventDefault()
        saveChanges()

    if has_switch
      pb_switch.click (e)->
        e.preventDefault()
        if $(@).hasClass("active")
          $(@).removeClass("active")
          window.location.reload()
        else
          $(@).addClass("active")
          initialize()
    else
      initialize()