feedItems = []
allFeedItems = []
csrf_token = $("form#replyForm input[name='csrfmiddlewaretoken']").val()
refresh = false
counter = 0
limitHolder = 30
recipientIDs = []
hash = window.location.hash
type = window.location.pathname.substring("/engagement/".length, window.location.pathname.length - 1)
if type == "/" then type = null
specificID = window.location.search.substr(4)
infiniteScrollFlag = true
$loading = $('div.loading.container')
firstRun = true
block = false
replyTutorialSet = false
newestDate = moment()

loadReplyAlpha = (thisItem) ->
  if !($(thisItem).hasClass("disabled") || $(this).hasClass("replied"))
    $("#alphaOverlay").toggleClass("active")
    pos = $(thisItem).offset()

    if ($("div#replyToAlpha").hasClass("required")) 
      $("#replyToAlpha").toggleClass("active")
    else
      $("#cannedAlpha.alpha").toggleClass("active").css("top", pos.top - (if specificID then 100 else 50))
    
    #Get checkedbox count
    activeBoxes = $(".response .select button.checkBox.active")
    checkedCount = activeBoxes.length
    recipient = ""

    #if single Reply
    if ($(thisItem).hasClass("reply")) 
      $(".alpha").css("top", pos.top - 50)
      $("html,body").animate scrollTop: (pos.top - 150), 1000
      #if no boxes are checked
      if (checkedCount == 0) 
        $("p.recipients").addClass('hidden')
        recipient = $(thisItem).prev("div.info").find("p.responseEmail span").text()
        recipientIDs[0] = $(thisItem).parents("li.response").attr("id")
      
      #else add checked boxes to recipient list
      else 
        $("p.recipients").removeClass('hidden')
        $("p.recipients span").text(checkedCount)
        activeBoxes.each( (index) ->
          sender = $(this).parents("li.response").find("p.responseEmail span").text()
          recipient = recipient.concat(sender)
          recipientIDs[index] = $(this).parents("li.response").attr("id")
          if (!((index + 1) == checkedCount)) 
            recipient = recipient.concat(", ")
        )
        if checkedCount == 1
          $("p.recipients").addClass('hidden')
        #If the selected reply does not have an active checkbox
        if (!$(thisItem).parents("li.response").find(".cbWrapper button").hasClass("active")) 
          sender = $(thisItem).prev("div.info").find("p.responseEmail span").text()
          recipient = recipient.concat(", "+sender)
          recipientIDs.push($(this).parents("li.response").attr("id"))
          $("p.recipients span").text(checkedCount + 1)
          $("p.recipients").removeClass('hidden')
   
    #Reply All -> find checked boxes and set recipients
    else if ($(thisItem).hasClass("replyAll")) 
      $("p.recipients").removeClass('hidden')
      $("p.recipients span").text(checkedCount)
      if checkedCount == 1
        $("p.recipients").addClass('hidden')
      $(".alpha").css("top", pos.top + 20)
      activeBoxes.each( (index) ->
        sender = $(this).parents("li.response").find("p.responseEmail span").text()
        recipient = recipient.concat(sender)
        recipientIDs[index] = $(this).parents("li.response").attr("id")
        if index + 1 != checkedCount 
          recipient = recipient.concat(", ")
      )
      
    $("#cannedAlpha input#recipients").val(recipient)

markAsRead = (fbResponse) ->
  $.post("/feedback/read/#{fbResponse.attr('id')}/",
    { csrfmiddlewaretoken: csrf_token }).done( -> fbResponse.addClass("read") )

scrollAndMark = ->
  scrollBottom = $(window).scrollTop() + $(window).height()
  $('li.response').each ->
    thisBottom = $(this).offset().top + $(this).innerHeight()
    if (scrollBottom > thisBottom) and not $(this).hasClass('read')
      markAsRead($(this))

$(document).ready ->
  if Django.subscription_type != 'free'
    getFeedItemList(counter,counter+limitHolder)
    setTimeout( (() -> getNewItemList(0,1000000000,newestDate)), 1000*60)
  else
    $('#upgradeOverlay.feed').addClass('active').click (e) ->
      e.preventDefault()
    $('#upgradePopup').show()
    $('.dropdown.category a').addClass('disabled').prop('disabled', true)
  $("a.replyAlpha.replyAll").click( -> loadReplyAlpha(this) )

displayAll = ->
  $("input.all").each ->
    if not $(this).is(':checked')
      $(this).click()

#Select All Checkboxes that are not hidden
window.selectAll = true
$("a.selectAll").click ->
  if !$(this).hasClass("disabled")
    if window.selectAll
      window.selectAll = false
      $(this).text('Deselect All')
      $("li.response").not(".hidden").find(".select .checkBox").addClass("active")
      $("a.replyAll").removeClass("disabled")
    else
      window.selectAll = true
      $(this).text('Select All')
      $("li.response").not(".hidden").find(".select .checkBox").removeClass("active")
      $("a.replyAll").addClass("disabled")

#For replyToAlpha -> Email address must be entered before submission
#Email Validation
isValidEmailAddress = (emailAddress)  ->
  pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
  return pattern.test(emailAddress)

#The Infinite scrolling functions
infiniteLoad = ->
  if not block
    block = true
    $loading.remove()
    $('#loadingHolder').append($loading)
    getFeedItemList(counter,counter+limitHolder)
    block = false
  
infiniteScroll = -> 
  if ($(window).scrollTop() == $(document).height() - $(window).height()) 
    if (infiniteScrollFlag == true) 
      infiniteLoad()

$("div#allItemsLoaded p a").click ->
  infiniteScrollFlag = true
  $("div#allItemsLoaded").removeClass("active")
  infiniteLoad()

$("a.topButton").click ->
  $("html,body").animate scrollTop: 0, 1000

$(".refreshHolder button#refresh").click ->
  $("html,body").animate scrollTop: 0, 1000
  $loading.remove()
  $('ul.feed').prepend($loading)
  getNewItemList(0,1000000000,newestDate)

$(".refreshHolder button#export").click ->
  $.get('/engagement/feedback-sessions-export', ->
    $('#exportAlpha.alpha').addClass('active')
    $('#alphaOverlay').addClass('active')
  )

$(".filterOptions a.clear").click ->
  displayAll()
  applyCategoryFilters()

getNewItemList = (start,limit,date) ->
  dateStr = date.add(1,"s").format("YYYYMMDDHHmmss")
  $loading.show().delay(500)
  updatePos()
  $.getJSON("/engagement/feedback-sessions/?start=#{dateStr}&offset=#{start}&limit=#{limit}")
  .done((data) ->
    if (data.length == 0)
      infiniteScrollFlag = false
      $loading.hide()
      setTimeout( ->
        $("#allItemsLoaded").addClass("active")
      , 2000)
    else
      iter = 0
      newIter = 0
      while(data.length > iter)
        if moment(data[iter].created_at).isAfter(newestDate)
          newestDate = moment(data[iter].created_at)
          feedItems[newIter] = data[iter]
          newIter++
        iter++
      infiniteScrollFlag = true
      $loading.hide()
    return data
  )
  .always( ->
    feedItems.reverse()
    refresh = true
    createFeed()
    applyCategoryFilters()
    updatePos()
    $.getScript("/static/js/jquery.rateit.min.js")
  )

getFeedItemList = (start,limit) ->
  counter += limitHolder
  infiniteScrollFlag = false
  $loading.show().delay(500)
  updatePos()
  $.get("/engagement/feedback-sessions/?offset=#{start}&limit=#{limit}")
  .done((data) ->
    if data.length == 0
      infiniteScrollFlag = false
      $loading.hide()
      setTimeout( ->
        $("#allItemsLoaded").addClass("active")
      , 2000)
    else
      feedItems = feedItems.concat(data)
      for item, i in data
        if i == 0
          newestDate = moment(item.created_at)
        if moment(item.created_at).isAfter(newestDate)
          newestDate = moment(item.created_at)
      infiniteScrollFlag = true
    return data

  )
  .always(->
    createFeed()
    applyCategoryFilters()
    updatePos()
    if specificID 
      if $("li##{specificID}.response").length > 0
        $('html, body').animate({
          scrollTop: $("li##{specificID}.response").offset().top - 160
        }, 2000)
        loadReplyAlpha($("li##{specificID}.response a.reply"))
        specificID = null
      else
        getFeedItemList(counter,counter+limitHolder)
    $.getScript("/static/js/jquery.rateit.min.js")
  )

#On select of a saved response. Populate with ajax
$(".cannedResponses select").change ->
  if $("option:selected", this).attr("id") == "blank"
    $("form#replyForm input#subject").val("")
    $("form#replyForm textarea#message").val("")
    $("form#replyForm button[type='submit']").addClass("disabled").attr("disabled", true)
  else
    canned_response_id = $(this).val()
    $.get("/engagement/response-template/" + canned_response_id)
    .done((data) ->
      #load data into the form
      $("form#replyForm input#subject").val(data.subject)
      $("form#replyForm textarea#message").val(data.body)
      $("form#replyForm button[type='submit']").removeClass("disabled").attr("disabled", false)
    )

$(".cannedResponses button#edit").click ->
  $("form#replyForm").addClass("hidden")
  $("form#editForm").removeClass("hidden")
  $(this).addClass("disabled").attr("disabled", true)

$("form#editForm a.closeEdit").click ->
  $("form#replyForm").removeClass("hidden")
  $("form#editForm").addClass("hidden")
  $("button#edit").removeClass("disabled").attr("disabled", false)

$("ul.editResponseList .cbWrapper button").click ->
  $(this).toggleClass("active")
  if $("ul.editResponseList .cbWrapper button.active").length > 0
    $("form#editForm button.submit").removeClass("disabled").attr("disabled", false)
  else
    $("form#editForm button.submit").addClass("disabled").attr("disabled", true)

$('form#editForm').submit ->
  event.preventDefault()
  $checked = $(this).find("button.active")
  responseTemplateIDs = []
  $checked.each ->
    responseTemplateIDs.push(parseInt($(this).val())) 
  if responseTemplateIDs.length > 0
    $.post('/engagement/response-templates/delete/', {
      response_template_ids: responseTemplateIDs,
      csrfmiddlewaretoken: csrf_token
    }).done( (data) ->
      $checked.each ->
        $(this).parents("li").remove()
        thisID = $(this).val()
        $(".cannedResponses select option[value='#{thisID}']").remove()
    )

$("form#replyForm").submit (event) ->
  event.preventDefault()
  feedback_session_ids = recipientIDs
  if ($("input#saveCanned").is(":checked"))
    $("form#responseName").addClass("active")
    $("#saveAlpha.alpha .closeForm").addClass("prompt")

  $.post('/engagement/send-response/', {
    feedback_session_ids: feedback_session_ids,
    subject: $("form#replyForm input#subject").val(),
    body: $("form#replyForm textarea#message").val(),
    save_as_template: $("#saveCanned").is(':checked'),
    csrfmiddlewaretoken: csrf_token
  }).done( (response) ->
    window.response_id = response.response_id
    $("#sentSuccess").show()
    for feedback_session in feedback_session_ids
      $("li.response##{feedback_session}").find("a.reply").addClass("replied").find("span").text("Replied")
      $("li.response##{feedback_session}").find(".cbWrapper").remove()
    $("#saveAlpha.alpha").addClass("active")
  ).fail((response) ->
    if response.statusCode() == 400
      messages = JSON.parse(response.responseText).messages
      $("#sentFailure").text(messages.join())
    else
      window.response_id = response.response_id
      $("#sentFailure").text("Message failed to send.  Please try again later.")
    $("#duplicateAlpha.alpha").addClass("active") 
  ).always( (data) ->
    $("#cannedAlpha.alpha").removeClass("active")
    $("#replyForm #subject").val("")
    $("#replyForm textarea").val("")
    $("#replyForm #saveCanned").prop('checked', false)
  )    

#on save form submission
$("form#responseName").submit (event) ->
  event.preventDefault()
  responseName = $("input#responseName").val()
  if responseName
    $.post('/engagement/new-response-template/', {
      'name': responseName,
      'response_id': window.response_id,
      'csrfmiddlewaretoken': csrf_token
    }).done((response) ->
      $(".cannedResponses select").append($("<option>").val(response.response_template.id).text(response.response_template.name))
      $("ul.editResponseList").append($("<li>").val(response.id).text(response.name))
      $("#saveAlpha.alpha #sentSuccess").addClass("hidden")
      $("#saveAlpha.alpha #saveSuccess").removeClass("hidden")
      $("form#responseName").removeClass("active").addClass("complete")
    ).fail( (response) ->
      $("#duplicateAlpha.alpha").addClass("active")
      $("#sentFailure").text("Template failed to save.  Please try again later.")
    )

#show Hide Feed
#sets the size of the left nav
options = $(".accountOptions")
nav = $("#accountNav")
mainHeight = $("#rightContent").height()
$topButton = $('a.topButton')

updatePos = ->
  $("#engagement.feedHolder").height("auto")
  mainHeight = $("#rightContent").height()
  $("#engagement.feedHolder").height(mainHeight + 40)
  nav.height(mainHeight + 40)
  $("#mainContent").height(mainHeight + 40)
  if options.hasClass("fixed")
    if $(window).scrollTop() + $(window).height() > mainHeight + 39
      options.removeClass("fixed").addClass("relative")
      nav.removeClass("fixed").addClass("relative")
      $topButton.removeClass("fixed").addClass("relative")
  if options.hasClass("relative")
    if $(window).scrollTop() + $(window).height() < mainHeight + 39
      options.removeClass("relative").addClass("fixed")
      nav.removeClass("relative").addClass("fixed")
      $topButton.removeClass("relative").addClass("fixed")

createFeed = ->
  allFeedItems = allFeedItems.concat(feedItems)
  
  if feedItems.length == 0
    $("a.replyAll").attr('data-position', "left")
    $("a.replyAll").attr('data-intro', "<b>Reply:</b> You can respond to individual
      subscribers by selecting reply. If you’d like
      to respond to a group of subscribers, select each
      individual you would like to
      respond to before selecting reply.")
    $("a.replyAll").attr('data-step', "3")

  for thisItem, i in feedItems 
    tempFeedClasses = ""
    parentNumEngagements = 0
    itemContainer = $("<li id='#{thisItem.feedback_session_id}'>").addClass(tempFeedClasses)
    if i == 0 and not thisItem.has_responses
      itemReply = $("<a
        data-position='left'
        data-step='3'
        data-intro='<b>Reply:</b> You can respond to individual
        subscribers by selecting reply. If you’d like
        to respond to a group of subscribers, select each
        individual you would like to
        respond to before selecting reply.'>")
        .attr('href','javascript:void(0)')
        .addClass('reply')
    else
      itemReply = $("<a>")
        .attr('href','javascript:void(0)')
        .addClass('reply')
      $("a.replyAll").attr('data-position', "right")
      $("a.replyAll").attr('data-intro', "<b>Reply:</b> You can respond to individual
        subscribers by selecting reply. If you’d like
        to respond to a group of subscribers, select each
        individual you would like to
        respond to before selecting reply.")
      $("a.replyAll").attr('data-step', "3")
    if not thisItem.has_responses
      itemReply.addClass("replyAlpha")
               .html('<i class="fa fa-reply"></i> <span>Reply</span>')
               .click -> loadReplyAlpha(this)
    else
     itemReply.addClass("replied")
              .html('<i class="fa fa-reply"></i> <span>Replied</span>')
    itemBody = $("<div>").addClass('responseBody')
    itemFeedbackSections = $("<ul>").addClass("responseList")
    
    surveyFlag = thisItem.survey and 
      (thisItem.survey.too_frequent or thisItem.survey.inbox_overflow or
       thisItem.survey.not_expected or thisItem.survey.not_relevant   or
       thisItem.survey.repetitive   or thisItem.survey.other)

    if thisItem.review and (type == "sentiment" or not type)
        tempFeedClasses += " sentiment"
        parentNumEngagements += createReviewSection(thisItem,itemFeedbackSections)

    if thisItem.net_promoter_score and (type == "satisfaction" or not type)
        tempFeedClasses += " satisfaction"
        parentNumEngagements += createNetPromoterScoreSection(thisItem,itemFeedbackSections)

    if thisItem.ratings and (type == "ratings" or not type)
        tempFeedClasses += " ratings"
        parentNumEngagements += createRatingSection(thisItem,itemFeedbackSections)

    if surveyFlag and (type == "surveys" or not type)
      tempFeedClasses += " surveys"
      parentNumEngagements += createSurveySection(thisItem,itemFeedbackSections)

    if thisItem.comments and (parentNumEngagements > 0 or type == "comments")
      tempFeedClasses += " comments"
      parentNumEngagements += createCommentsSection(thisItem,itemFeedbackSections)

    # don't add item if there's no content
    if parentNumEngagements == 0
      continue

    date = moment(thisItem.created_at)
    itemBody.append(itemFeedbackSections)
      .append($("<div>").addClass("dateWrapper")
        .append($("<a>")
          .text("Spam")
          .attr('feedback-id', itemContainer.attr('id'))
          .css('cursor','pointer')
          .click((evt) ->
            $("#deletePopup").show()
            feedback_id = $(this).attr('feedback-id')
            $("#alphaOverlay").addClass("active")
            $("#deleteConfirm").one('click', () ->
              $.post('/feedback/delete/', {
                'session_id': feedback_id,
                'csrfmiddlewaretoken': $("form#replyForm input[name='csrfmiddlewaretoken']").val()
              })
              $("#" + feedback_id).remove()
              $("#deletePopup").hide()
              $("#alphaOverlay").removeClass("active")
            )
            $('#deleteCancel').one('click', () ->
              $("#deletePopup").hide() 
              $("#alphaOverlay").removeClass("active")
            )
            $('#alphaOverlay').one('click', () ->
              $("#deletePopup").hide() 
              $("#alphaOverlay").removeClass("active")
            )
    )).append($("<p id='#{date.format("M-D-YY")}'>").addClass('date').text(date.fromNow())))
    if thisItem.email and Django.reply_grandfathered and not thisItem.has_responses
      cbWrapper = $("<div>").addClass('cbWrapper select')
                            .html('<button value="1" type="button" class="checkBox">
                                   <i class="fa fa-check"></i></button>')
      itemContainer.append(cbWrapper)
      #Set Checkboxes OnClick
      $(cbWrapper).find('button').click ->
        if (!$(this).hasClass("active")) 
          $(this).addClass("active")
          $("a.replyAll").removeClass("disabled")
        else 
          $(this).removeClass("active")
          if ($(".select .checkBox.active").length == 0) 
            $("a.replyAll").addClass("disabled")
    itemInfo = $("<div>").addClass('info')
    .html("<p class='responseEmail'><i class='fa fa-envelope'></i><span>#{thisItem.email or "Anonymous"}</span></p>")

    itemContainer.append(itemInfo)
    if thisItem.email and Django.reply_grandfathered
      itemContainer.append(itemReply)
    itemContainer.append(itemBody)
    if thisItem.read then tempFeedClasses += " read"
    itemContainer.addClass("response " + tempFeedClasses)
    if not refresh
      $('#feed-item-feed').append(itemContainer)
    else
      $('#loadingContainer').after(itemContainer)

    #hide the loading spinner
    $("div.loading").slideUp(1000)

    #Items are loaded unlock the replyAll Function
    $("a.selectAll").removeClass("disabled")
  #if first createFeed then set functions
  if firstRun
    if Django.intro
      introJs().start()
      Django.intro = false
    firstRun = false
    #Set infinite Scrolling function
    #Infinite Scrolling Function
    #Gets: Next 25 Items once user scrolls to the end of the page
    #bind scrolling functions with throttling

    #mark first feedback item as read
    first = $('li.response').first()
    if not first.hasClass("read")
      markAsRead(first)
    mainHeight = $("#rightContent").height()
    $topButton = $('a.topButton') 
    topButtonPos = ->
      if $(window).scrollTop() + $(window).height() > mainHeight + 39
        $topButton.addClass("absolute")
        $('a.topButton').css({
          'left': 'auto'
          'bottom': '15px'
        })
      else if $(window).scrollTop() >= $(window).height()
        $topButton.removeClass('absolute')
        $('a.topButton').removeClass("hidden")
        $('a.topButton').css('left',
          $('#engagement.feedHolder').offset().left + $('#engagement.feedHolder').width() - $(this).scrollLeft()  - 65
        )
      else
        $('a.topButton').addClass("hidden")
    $(window).scroll(_.throttle(infiniteScroll, 1000))
    $(window).scroll(_.throttle(scrollAndMark, 1000))
    $(window).scroll(topButtonPos)
    $(window).resize(topButtonPos)
       
    #Update the size of the nav
    mainHeight = $("#rightContent").height()
    $("#accountNav").height(mainHeight)
    $("#mainContent").height(mainHeight)

    updatePos()


  $('[data-toggle="tooltip"]').tooltip()
  #reset feed items
  feedItems = []

  #reset refresh status
  refresh = false

  $("#cannedAlpha.alpha a.close").click ->
    recipientIDs = []

  $("#replyToAlpha.alpha input").on "keyup blur change", ->
    $email = $("input#replyAddress").val()
    if isValidEmailAddress($email)
      $("form#replyToAddress button[type='submit']").removeClass("disabled").attr("disabled", false)
    else
      $("form#replyToAddress button[type='submit']").addClass("disabled").attr("disabled", true)

  #on ReplyToAddress Submit
  $("form#replyToAddress").submit (event) ->
    event.preventDefault()
    $.post('/settings/change-engagement-email/', {
      csrfmiddlewaretoken: csrf_token,
      engagement_email: $("#replyAddress").val()
    })
    .always( () ->
      $("#replyToAlpha.alpha").removeClass("active")
      $("#cannedAlpha.alpha").addClass("active")
    )

  #If subject and message body are not empty, allow submission of alpha forms
  $("#cannedAlpha.alpha .required").on "keyup blur change", -> 
    if !($("input#subject").val() == "" or $("textarea#message").val() == "")
      $("form#replyForm button[type='submit']").removeClass("disabled").attr("disabled", false)
    else
      $("form#replyForm button[type='submit']").addClass("disabled").attr("disabled", true)

  $("#saveAlpha.alpha .required").on "keyup blur change", -> 
    if $("input#responseName").val() != ""
      $("form#responseName button[type='submit']").removeClass("disabled").attr("disabled", false)
    else
      $("form#responseName button[type='submit']").addClass("disabled").attr("disabled", true)

  #On close prompt for save
  $("#saveAlpha.alpha .closeForm").click ->
    if $(this).hasClass("prompt") and !$("form#responseName").hasClass("complete")
      $("#saveAlpha.alpha p").addClass("active")
      $("input#responseName").addClass("active")
      $(this).removeClass("prompt")
    else
      $("#saveAlpha.alpha").removeClass("active")
      $("#alphaOverlay").removeClass("active")
 
  #If subject and message body are not empty, allow submission
  $("#cannedAlpha.alpha .required").on "keyup blur change", -> 
    if !($("input#subject").val() == "" or $("textarea#message").val() == "")
      $("form#replyForm button[type='submit']").removeClass("disabled").attr("disabled", false)
    else
      $("form#replyForm button[type='submit']").addClass("disabled").attr("disabled", true)

  #Filter Change
  #Lets split this into multiple functions 
  $(".filterOptions .dropdown input").change ->
    #Reset all of the Checkboxes
    $(".select .checkBox").removeClass("active")
    $("a.replyAll").addClass("disabled")

    #get Input ID and parent dropdown
    id = $(this).attr("name")
    $parent = $(this).parents(".dropdown")
    parentID = $parent.attr("id")
    #If not all, uncheck all
    if $(this).is(":checked")
      switch id
        when "all"
          if ! type or type == "ratings"
            $parent.find("input:not(.none)").prop('checked', true)
            $parent.find("input.none").prop('checked', false)
          else
            $parent.find("input").prop('checked', true)
        when "none"
          $parent.find("input:not(.none)").prop('checked', false)
        else
          if !type or type == "ratings"
            $parent.find("input.none").prop('checked', false)
            setAll = true
            $parent.find("input:not(.none):not(.all)").each ->
              if not $(this).is(':checked')
                setAll = false
            if setAll == true
              $parent.find("input.all").prop('checked', true)
          else
            setAll = true
            $parent.find("input:not(.all)").each ->
              if not $(this).is(':checked')
                setAll = false
            if setAll == true
              $parent.find("input.all").prop('checked', true)
    else
      if !(parentID == "replies" || parentID == "address")
        switch id
          when "all"
            if !type or type == "ratings"
              $parent.find("input:not(.none)").prop('checked', false)
              $parent.find("input.none").prop('checked', true)
            else
              $parent.find("input").prop('checked', false)
              $parent.find("input.all").parents("li").next("li").find("input").prop('checked', true)
          when "none"
            $parent.find("input:not(.none)").prop('checked', true)
            $parent.find("input.all").prop('checked', true)
          else
            $parent.find("input.all").prop('checked',false)
    #Replies
    if parentID == "replies"
      $("ul.feed li.response.replyHidden").each ->
        if !($(this).hasClass("satHidden") || $(this).hasClass("ratingsHidden") || $(this).hasClass("reviewHidden") || $(this).hasClass("surveysHidden") || $(this).hasClass("dateHidden") || $(this).hasClass("categoryHidden"))
          $(this).removeClass("hidden").removeClass("replyHidden")
        else
          $(this).removeClass("replyHidden")

      if $(this).is(":checked")
        setAll = true
        $parent.find("input").each ->
          if not $(this).is(':checked')
            setAll = false
        if id == "all" or setAll == true
          $("#repliesFilter.dropdown-toggle span").text("All")
        else if id == "notReplied"
          $("#repliesFilter.dropdown-toggle span").text("Not Replied")
        else
          $("#repliesFilter.dropdown-toggle span").text("Replied")

      else
        if $parent.find("input:checked").length > 0
          if id == "notReplied"
            $parent.find("input.all").prop('checked', false)
            $("#repliesFilter.dropdown-toggle span").text("Replied")
          else if id == "replied"
            $parent.find("input.all").prop('checked', false)
            $("#repliesFilter.dropdown-toggle span").text("Not Replied")
          else if id = "all"
            $parent.find("input.replied").prop('checked', false)
            $("#repliesFilter.dropdown-toggle span").text("Not Replied")
        else
          $parent.find("input").each ->
            $(this).prop('checked', true)
          $("#repliesFilter.dropdown-toggle span").text("All")
      applyCategoryFilters()
    else if parentID == "address"
      $("ul.feed li.response.addressHidden").each ->
        if !($(this).hasClass("satHidden") || $(this).hasClass("ratingsHidden") || $(this).hasClass("reviewHidden") || $(this).hasClass("surveysHidden") || $(this).hasClass("dateHidden") || $(this).hasClass("categoryHidden") || $(this).hasClass("replyHidden"))
          $(this).removeClass("hidden").removeClass("addressHidden")
        else
          $(this).removeClass("addressHidden")

      if $(this).is(":checked")
        setAll = true
        $parent.find("input").each ->
          if not $(this).is(':checked')
            setAll = false
        if id == "all" or setAll == true
          $("#addressFilter.dropdown-toggle span").text("All")
        else if id == "available"
          $("#addressFilter.dropdown-toggle span").text("Available")
        else
          $("#addressFilter.dropdown-toggle span").text("Anonymous")
      else
        if $parent.find("input:checked").length > 0
          if id == "available"
            $parent.find("input.all").prop('checked', false)
            $("#addressFilter.dropdown-toggle span").text("Anonymous")
          else if id == "anonymous"
            $parent.find("input.all").prop('checked', false)
            $("#addressFilter.dropdown-toggle span").text("Available")
          else if id = "all"
            $parent.find("input.anonymous").prop('checked', false)
            $("#addressFilter.dropdown-toggle span").text("Available")
        else
          $parent.find("input").each ->
            $(this).prop('checked', true)
          $("#addressFilter.dropdown-toggle span").text("All")
      applyCategoryFilters()
    #Other Filters
    else 
      #update text
      #if all unchecked then check all
      #change all others that have not been 'set' to null
      $('.dropdown .category').each ->
        if !$(this).attr("id") == parentID and !$(this).hasClass('set')
          $(this).find('ul li input').prop('checked', false)
          $(this).find('ul li input.none').prop('checked', true)
      if $parent.find("input:checked").length == 0
        if !type or type == "ratings"
          $parent.find("input.none").prop('checked', true)
          dropdownText = "None"
        else
          $parent.find("input").prop('checked', true)
          dropdownText = "all"
      else if $parent.find("input.all").prop('checked')
        dropdownText = "All"
      else if $parent.find("input.none").prop('checked')
        dropdownText = "None"
      else
        $parent.find("input:checked").each (index) ->
          inputId = $(this).attr("name")
          #format ratings
          if $parent.attr("id") == "ratings" and inputId != 'all'
            num = inputId.substr(0,1)
            star = inputId.substr(1)
            inputId = num.concat(" ", star)
            #1Stars = 1Star
            if inputId == "1 Stars"
              inputId = "1 Star"
          #format review
          else if (inputId == "veryunhappy") || (inputId == "veryhappy")
            very = "very"
            inputId = very.concat(" ", inputId.substr(4))
          if index == 0
            dropdownText = inputId
          else
            dropdownText = dropdownText.concat(", ", inputId)

      if dropdownText.length > 17
        dropdownText = dropdownText.substr(0,14).concat("...")
      $parent.find(".dropdown-toggle span").text(dropdownText).addClass('set')

      applyCategoryFilters()
    if $("li.response").not(".hidden").length == 0
      $("div.feedEmpty").removeClass("hidden")
    else
      $("div.feedEmpty").addClass("hidden")
    #update Size of Window
    updatePos()
   
  #Filter Options Persist Dropdown on click
  $("div.filterOptions .dropdown-menu a").click ->
    $parent = $(this).parents(".dropdown")
    $parent.addClass("stayOpen")
    setTimeout( ->
      $parent.addClass("open").removeClass("stayOpen")
    , 0.1)

applyCategoryFilters = ->
  window.current_sessions = allFeedItems
  rev_filters = $("#reviews.dropdown input:checked").map( (i,x) -> $(x).attr('name') )
  satis_filters = $("#satisfaction.dropdown input:checked").map( (i,x) -> $(x).attr('name') )
  rating_filters = $("#ratings.dropdown input:checked").map( (i,x) -> $(x).attr('name') )
  response_filters = $("#replies.dropdown input:checked").map( (i,x) -> $(x).attr('name') )
  address_filters = $("#address.dropdown input:checked").map( (i,x) -> $(x).attr('name') )
  survey_filters = $("#surveys.dropdown input:checked").map( (i,x) -> $(x).attr('name') )
  custom_filters = $("#custom.dropdown input:checked").map( (i,x) -> $(x).attr('val') )

  if rev_filters.length == 0 then rev_filters = [ "all" ]
  if satis_filters.length == 0 then satis_filters = [ "all" ]
  if rating_filters.length   == 0 then rating_filters = [ "all" ]
  if response_filters.length == 0 then response_filters = [ "all" ]
  if address_filters.length == 0 then address_filters = [ "all" ]
  if survey_filters.length == 0 then survey_filters = [ "all" ]

  window.current_sessions = window.current_sessions.filter (x) ->
    if ($.inArray("all", survey_filters) > -1)
      return true
    if ($.inArray("none", survey_filters) > -1 and not x.survey)
      return true
    if not x.survey
      return false
    if ($.inArray("frequency", survey_filters) == -1 and x.survey.too_frequent) or
       ($.inArray("overload", survey_filters) == -1 and x.survey.inbox_overflow) or
       ($.inArray("expectation", survey_filters) == -1 and x.survey.not_expected) or
       ($.inArray("relevancy", survey_filters) == -1 and x.survey.not_relevant) or
       ($.inArray("repetitive", survey_filters) == -1 and x.survey.repetitive) or
       ($.inArray("other", survey_filters) == -1 and x.survey.other)
      return false
    return true

  window.current_sessions = window.current_sessions.filter (x) ->
    if ($.inArray("all", rev_filters) > -1) or
       ($.inArray("none", rev_filters) > -1 and (not x.review or x.review.review == 0))
      return true
    if (not x.review) or
       ($.inArray("none", rev_filters) > -1 and (x.review and x.review.review > 0)) or
       ($.inArray("none", rev_filters) == -1 and (not x.review or x.review.review == 0)) or
       ($.inArray("veryunhappy", rev_filters) == -1 and x.review.review == 1) or
       ($.inArray("unhappy", rev_filters)     == -1 and x.review.review == 2) or
       ($.inArray("neutral", rev_filters)     == -1 and x.review.review == 3) or
       ($.inArray("happy", rev_filters)       == -1 and x.review.review == 4) or
       ($.inArray("veryhappy", rev_filters)   == -1 and x.review.review == 5)
      return false
    return true

  window.current_sessions = window.current_sessions.filter (x) ->
    if ($.inArray("all", satis_filters) > -1) or
       ($.inArray("none", satis_filters) > -1 and (not x.net_promoter_score or x.net_promoter_score.score == 11))
      return true
    if ($.inArray("none", satis_filters) == -1 and (not x.net_promoter_score or x.net_promoter_score.score == 11)) or
       ($.inArray("none", satis_filters) > -1 and (x.net_promoter_score and x.net_promoter_score.score == 11)) or
       ($.inArray("promoter", satis_filters)  == -1 and x.net_promoter_score.score > 8) or
       ($.inArray("passive", satis_filters)   == -1 and (x.net_promoter_score.score == 7 or x.net_promoter_score.score == 8)) or
       ($.inArray("detractor", satis_filters) == -1 and x.net_promoter_score.score < 7)
      return false
    return true

  window.current_sessions = window.current_sessions.filter (x) ->
    if x.ratings
      rate_list = [x.ratings.value, x.ratings.design, x.ratings.frequency, x.ratings.relevancy]
    if $.inArray("all", rating_filters) > -1
      return true
    if $.inArray("none", rating_filters) > -1 and (not x.ratings or rate_list == [0,0,0,0])
      return true
    if (not x.ratings) or
       ($.inArray("none", rating_filters) > -1 and x.ratings)
      return false
    return _.intersection(rate_list,
      rating_filters.map((i,x) -> parseInt(x[0]))).length

  window.current_sessions = window.current_sessions.filter (x) ->
    if $.inArray("all", response_filters) > -1
      return true
    if ($.inArray("notReplied", response_filters) == -1 and x.has_responses) or
       ($.inArray("replied", response_filters) == -1 and not x.has_responses)
      return true
    return false

  window.current_sessions = window.current_sessions.filter (x) ->
    if $.inArray("all", address_filters) > -1
      return true
    if ($.inArray("available", address_filters) == -1 and x.email) or
       ($.inArray("anonymous", address_filters) == -1 and not x.email)
      return false
    return true

  window.current_sessions = window.current_sessions.filter (x) ->
    if ($.inArray("all", survey_filters) > -1)
      return true
    if ($.inArray("none", survey_filters) > -1 and not x.survey)
      return true
    if not x.survey
      return false
    if ($.inArray("frequency", survey_filters) == -1 and x.survey.too_frequent) or
       ($.inArray("overload", survey_filters) == -1 and x.survey.inbox_overflow) or
       ($.inArray("expectation", survey_filters) == -1 and x.survey.not_expected) or
       ($.inArray("relevancy", survey_filters) == -1 and x.survey.not_relevant) or
       ($.inArray("repetitive", survey_filters) == -1 and x.survey.repetitive) or
       ($.inArray("other", survey_filters) == -1 and x.survey.other)
      return false
    return true

  window.ftrs_running = 0
  for filter in custom_filters
    if filter == "none"
      continue
    window.ftrs_running += 1
    $.getJSON("/feedback/filter/apply/?filter=#{filter}").done((ids) ->
      window.current_sessions = window.current_sessions.filter (x) ->
        x.feedback_session_id in ids
    ).always ->
      window.ftrs_running -= 1
  if window.ftrs_running > 0
    setTimeout((() -> window.ftrs_running = 0), 2000)
  if type == "ratings"
    filterForRating = (filter, specific) ->    
      window.current_sessions = window.current_sessions.filter (x) ->
        if $.inArray("all", filter) > -1
          return true
        if (not x.ratings) or
           ($.inArray("none", filter) > -1 and x.ratings[specific] > 0)
          return false
        if $.inArray("none", filter) > -1 and x.ratings[specific] == 0
          return true
        return $.inArray(x.ratings[specific], filter.map((i,x) -> parseInt(x[0]))) > -1

    filterForRating($("#value.dropdown input:checked").map( (i,x) -> $(x).attr('name') ), 'value')
    filterForRating($("#frequency.dropdown input:checked").map( (i,x) -> $(x).attr('name') ), 'frequency')
    filterForRating($("#relevancy.dropdown input:checked").map( (i,x) -> $(x).attr('name') ), 'relevancy')
    filterForRating($("#design.dropdown input:checked").map( (i,x) -> $(x).attr('name') ), 'design')
  updateWhenDone()

updateWhenDone = ->
  if window.ftrs_running > 0
    return setTimeout(updateWhenDone, 250)
  $("li.response").hide()
  for sess in window.current_sessions
    $("##{sess.feedback_session_id}").show()
  if $("li.response").filter(':visible').length == 0
    $('#feedEmpty').addClass('active')
  else
    $('#feedEmpty').removeClass('active')
  updatePos()

createRatingSection = (thisItem,sectionContainer) ->
  reviewType = {
    0: "",
    1: "Poor",
    2: "Below Average",
    3: "Average",
    4: "Excellent",
    5: "Outstanding",
  }
  numRatings = 0

  value = thisItem.ratings.value
  frequency = thisItem.ratings.frequency
  relevancy = thisItem.ratings.relevancy
  design = thisItem.ratings.design

  if reviewType[value]
    numRatings += 1
    sectionContainer.append($("<li id='rateResponse'>").addClass("responseItem ratings value #{value}Stars").val(reviewType[value])
      .append($('<h4>').text('Value'))
      .append($("<div>").addClass("responseDataWrapper")
        .append($("<div>").addClass("ratingsResponseData").html("<img class='bigStar' src='/static/images/bigStar.svg'><span>#{value}</span><p class='result'>#{reviewType[value]}</p>"))))

  if reviewType[frequency]
    numRatings += 1
    sectionContainer.append($("<li id='rateResponse'>").addClass("responseItem ratings frequency #{frequency}Stars").val(reviewType[frequency])
      .append($('<h4>').text("Frequency"))
      .append($("<div>").addClass("responseDataWrapper")
        .append($("<div>").addClass("ratingsResponseData").html("<img class='bigStar' src='/static/images/bigStar.svg'><span>#{frequency}</span><p class='result'>#{reviewType[frequency]}</p>"))))

  if reviewType[relevancy]
    numRatings += 1
    sectionContainer.append($("<li id='rateResponse'>").addClass("responseItem ratings relevancy #{relevancy}Stars").val(reviewType[relevancy])
      .append($("<h4>").text("Relevancy"))
      .append($("<div>").addClass("responseDataWrapper")
        .append($("<div>").addClass("ratingsResponseData").html("<img class='bigStar' src='/static/images/bigStar.svg'><span>#{relevancy}</span><p class='result'>#{reviewType[relevancy]}</p>"))))

  if reviewType[design]
    numRatings += 1
    sectionContainer.append($("<li id='rateResponse'>").addClass("responseItem ratings design #{design}Stars").val(reviewType[design])
      .append($('<h4>').text('Design'))
      .append($("<div>").addClass("responseDataWrapper")
        .append($("<div>").addClass("ratingsResponseData").html("<img class='bigStar' src='/static/images/bigStar.svg'><span>#{design}</span><p class='result'>#{reviewType[design]}</p>"))))

  numRatings

createReviewSection = (thisItem,sectionContainer) ->
  if thisItem.review.review == 0
    return 0

  sentimentType = switch thisItem.review.review
    when 0 then "None"
    when 1 then "Very Unhappy"
    when 2 then "Unhappy"
    when 3 then "Neutral"
    when 4 then "Happy"
    when 5 then "Very Happy"
  className = sentimentType.toLowerCase().replace(' ','')
  sectionContainer.append($("<li id='reviewResponse'>").addClass("responseItem sentiment").val(thisItem.review.review)
    .append($('<h4>').text("Sentiment"))
    .append($("<div>").addClass("responseDataWrapper")
      .html("<i class='reviewHappy'><img src='/static/images/#{className}.svg' class='#{className}'/></i><p class='result'>#{sentimentType}</p>")))
  return 1

createNetPromoterScoreSection = (thisItem,sectionContainer) ->
  tempScore = thisItem.net_promoter_score.score
  if tempScore < 7
    tempTitle = "Detractor"
  else if tempScore < 9
    tempTitle = "Neutral"
  else if tempScore < 11
    tempTitle = "Promoter"
  else # 11 indicates not filled out
    return 0
  
  sectionContainer.append(
    $("<li id='satResponse'>").addClass("responseItem satisfaction #{tempTitle.toLowerCase()}").val(tempScore)
      .append($('<h4>').text('Satisfaction'))
      .append($("<div>").addClass('responseDataWrapper')
        .append($("<i>").addClass("satResponseData").text(tempScore))
        .append($("<label>").text('Out of 10'))
        .append($("<p>").addClass("result").text(tempTitle))))
  return 1

buildSurveyItem = (id,label) ->
  $("<li id='#{id}'>")
    .append($("<div>").addClass("cbWrapper")
      .append($("<button>").addClass("checkBox active")
        .append($("<i>").addClass("fa fa-check"))))
      .append($("<label>").text(label))

#Create Survey
createSurveySection = (thisItem, sectionContainer) ->
  surveyCount = 0
  surveyClasses = ""

  if thisItem.survey.too_frequent 
    surveyClasses += " frequency"
    surveyCount++
  if thisItem.survey.inbox_overflow
    surveyClasses += " overload"
    surveyCount++
  if thisItem.survey.not_expected
    surveyClasses += " expectation"
    surveyCount++
  if thisItem.survey.not_relevant
    surveyClasses += " relevancy"
    surveyCount++
  if thisItem.survey.repetitive
    surveyClasses += " repetition"
    surveyCount++
  if thisItem.survey.other
    surveyClasses += " other"
    surveyCount++
  
  if not surveyCount
    return 0 

  itemSurveyResultsContainer = $("<ul>").addClass("surveyResults")
  
  itemFeedbackSurvey = $("<li id='surveyResponse'>").addClass("responseItem surveys" + surveyClasses)
    .append($('<h4>').text('Survey'))
    .append($("<div>").addClass("responseDataWrapper")
    .append($("<div>").addClass("cbWrapper big")
      .attr('data-toggle', 'tooltip')
      .attr('data-placement', 'right')
      .attr('title', '')
      .append($("<button>").addClass("checkBox active").text(surveyCount)))
        .append($("<label>").addClass("dataLabel").text("Out of 6"))
      .append(itemSurveyResultsContainer))
  
  if thisItem.survey.too_frequent
    itemSurveyResultsContainer.append(buildSurveyItem('Frequent', 'Frequency'))
  if thisItem.survey.inbox_overflow
    itemSurveyResultsContainer.append(buildSurveyItem('overload', 'Overload'))  
  if thisItem.survey.not_expected
    itemSurveyResultsContainer.append(buildSurveyItem('expectation', 'Expectation'))
  if thisItem.survey.not_relevant
    itemSurveyResultsContainer.append(buildSurveyItem('Relevant', 'Relevancy'))
  if thisItem.survey.repetitive
    itemSurveyResultsContainer.append(buildSurveyItem('Repetitive', 'Repetitive'))
  if thisItem.survey.other
    itemSurveyResultsContainer.append(buildSurveyItem('Other', 'Other'))

  sectionContainer.append(itemFeedbackSurvey)
  return surveyCount

createCommentsSection = (thisItem,sectionContainer) ->
  sectionContainer.append($("<li id='commentsResponse'>").addClass("responseItem comments")
    .append($('<h4>').text("Comments"))
    .append($("<div>").addClass("responseDataWrapper")
      .append($("<p>").text(thisItem.comments))))
  return 1

if type == 'surveys' and not churn
  $("#unsubscribeSealPrompt").show()

