$(document).ready ->
  $('span.activeDate span').text(moment().format('MMM D, YYYY'))
  $( -> 
    FastClick.attach($('div#commentForm')[0])
  )
  #Show form based on seal type
  vpWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)
  vpHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
  #if Ipad scroll up

  #set select boxes height
  setSelectHeight = ->
    if vpWidth < 479
      height = $('#selectContainer ul.selectScore li.left').outerWidth()
      $('ul.selectScore li').height(height)

  $(window).resize ->
    if vpWidth < 479
      setSelectHeight()

  if app.seal_type
    #if #feedback then display Get In Touch Form
    if(app.seal_type == 'M' or app.seal_type == 'U')
      $('#alphaOverlay').addClass('active').show()

  #Mobile Menu Toggle

  url = $('a.companyURL').text()
  url = url.split("//")[1]
  if url
    urlLength = url.length
    url = url.substring(0,(urlLength - 1))
  else
    urlLength = 0
    url = ''
  $('a.companyURL').text(url)

  $("#mobileMenu button").click ->
    $("#mobile.mobileMenu").toggleClass("open")

  #Open Feedback Widget
  $("a#giveFeedback").click ->
    if !($(this).hasClass("btn-disabled"))
      $(".validationContainer").toggleClass("active").show()
      $("#alphaOverlay").toggleClass("active").show()

  $(".closeFbForm").click ->
    $(".validationContainer").removeClass("active").hide()
    $("#alphaOverlay").toggleClass("active").hide()

  $(".fbForm li.option button").click ->
    if not $(this).hasClass("active")
      active = $(".fbForm li.option button").filter ".active"
      active.removeClass "active"
      active.parents('li.option').removeClass 'active'
      $(this).parents('li.option').addClass 'active'
      active.next(".optionBody").slideToggle 800
      $(this).next(".optionBody").slideToggle 800
      $(this).toggleClass "active"  
      setSelectHeight()
      $('li#review.option').addClass('shift')

  $('.mainValidationContainer li.option button').click ->
    thisID = $(this).attr("id")
    thisID = thisID.split('Side')[0]
    option = $(".fbForm li.option button##{thisID}")
    if not option.hasClass("active")
      active = $(".fbForm li.option button").filter ".active"
      active.removeClass "active"
      active.next(".optionBody").removeClass('active').hide()
      option.addClass "active"
      option.next(".optionBody").addClass('active').show()
    $(".validationContainer").toggleClass("active").show()
    $("#alphaOverlay").toggleClass("active").show()

#Review Face Select
  $("ul.reviewFaces li a").click ->
    $("ul.reviewFaces").addClass("selected")
    $('#feedbackSubmit').removeClass('btn-disabled')
    $('#feedbackSubmit').prop('disabled', false)
    if not $(this).parent("li").hasClass("active")
      active = $("ul.reviewFaces li").filter ".active"
      active.removeClass "active"
      $("ul.reviewFaces li p").hide()
      $(this).parent("li").toggleClass "active"
      $(this).parent("li").find("p").show()
      $('li#review.option').removeClass 'active'
      $('li#recommend.option').addClass 'active'
      $('.fbForm button#review').removeClass 'active'
      $('.fbForm li.option div#commentForm.optionBody').slideToggle 800
      $('.fbForm button#recommend').addClass 'active'
      $('.fbForm li.option div#recommendScore.optionBody').slideToggle 800
      setSelectHeight()

  $("ul.reviewFaces li a").mouseenter ->
    if !($(this).parent("li").hasClass("active"))
      $(this).parent("li").find("p").show()

  $("ul.reviewFaces li a").mouseleave ->
    if !($(this).parent("li").hasClass("active"))
      $(this).parent("li").find("p").hide()

#Satisfaction Rating  
  $(".selectScore li").click ->
    $('#feedbackSubmit').removeClass('btn-disabled')
    $('#feedbackSubmit').prop('disabled', false)
    $(".selectScore li").removeClass("selected")
    $(this).addClass("selected")
    $('li#recommend.option').removeClass 'active'
    $('li#rate.option').addClass 'active'
    $('.fbForm button#recommend').removeClass 'active'
    $('.fbForm li.option div#recommendScore.optionBody').removeClass('active').slideToggle 800
    $('.fbForm button#rate').addClass 'active'
    $('.fbForm li.option ul#fbMetrics.optionBody').addClass('active').slideToggle 800

   
  values = ['Poor', 'Below Average', 'Average', 'Excellent', 'Outstanding']
  
  $(".rateit").bind 'over', (event, value) ->
    $(this).next(".value").text(values[value-1])
  
  $(".rateit").mouseleave -> 
    if $(this).next(".value").hasClass("notRated")
   	  $(this).next(".value").text("")
    else
      curr = $(this).next(".value").attr('id')
      $(this).next(".value").text(values[curr]) 
  
  $(".unsub .rateit").on 'reset', (event, value) -> 
    $(this).addClass("notRated").next(".value").addClass("notRated")
    $(this).next(".value").text("")
    $(this).find(".rateit-reset").css('left', '-34px')
    rated = false
    $('.unsub .rateit').each (index, element) =>
      if !($(element).hasClass("notRated"))
        rated = true
    if $('.unsub .selectScore li.selected').length != 0 or $('.unsub .reviewFaces li.active').length != 0
      rated = true
    if rated == false
      $('.unsub #feedbackSubmit').addClass('btn-disabled')
      $('.unsub #feedbackSubmit').prop('disabled', true)

  $(".fb .rateit").on 'reset', (event, value) -> 
    $(this).addClass("notRated").next(".value").addClass("notRated")
    $(this).next(".value").text("")
    $(this).find(".rateit-reset").css('left', '-34px')
    rated = false
    $('.fb .rateit').each (index, element) =>
      if !($(element).hasClass("notRated"))
        rated = true
    if $('.fb .selectScore li.selected').length != 0 or $('.fb .reviewFaces li.active').length != 0
      rated = true
    if rated == false
      $('.fb #feedbackSubmit').addClass('btn-disabled')
      $('.fb #feedbackSubmit').prop('disabled', true)

  $(".unsub .rateit").bind 'rated', (event, value) ->
    $('.unsub #feedbackSubmit').removeClass('btn-disabled')
    $('.unsub #feedbackSubmit').prop('disabled', false)
    $(this).next(".value").text(values[value-1])
    $(this).next(".value").attr('id', value-1)
    $(this).removeClass("notRated").next(".value").removeClass("notRated") 
    reset = $(this).find(".rateit-reset")     
    left = -34
    for i in [0...value]
      left = left + 34
    reset.css('left', "#{left}px")

  $(".fb .rateit").bind 'rated', (event, value) ->
    $('.fb #feedbackSubmit').removeClass('btn-disabled')
    $('.fb #feedbackSubmit').prop('disabled', false)
    $(this).next(".value").text(values[value-1])
    $(this).next(".value").attr('id', value-1)
    $(this).removeClass("notRated").next(".value").removeClass("notRated") 
    reset = $(this).find(".rateit-reset")     
    left = -34
    for i in [0...value]
      left = left + 34
    reset.css('left', "#{left}px")

  $(".reasons input").click ->
    if $(this).is(":checked")
      $(".unsub #feedbackSubmit").removeClass('btn-disabled')
      $('.unsub #feedbackSubmit').prop('disabled', false)
    else
      if $(".reasons input:checked").length == 0
        $(".unsub #feedbackSubmit").addClass('btn-disabled')
        $('.unsub #feedbackSubmit').prop('disabled', true)

  $('.unsub form.review button#feedbackSubmit').click ->
    if $('.unsub #feedbackSubmit').hasClass('btn-disabled')
      $('.fbError').show()
      return
    else
      $(".unsub .fbForm").removeClass("active").hide()
      $('.unsub #alphaOverlay').removeClass("active").hide()
    if $('.unsub .selectScore li.selected').length != 0
      $('.unsub input[name="nps"]').val($('.unsub .selectScore li.selected').val())
    $('.unsub .rateit').each (index, element) =>
      id = $(element).attr('id')
      value = $(element).rateit('value')
      $('.unsub input[name="'+ id + '"]').val(value)
    if $('.unsub .reviewFaces li.active').length != 0
      reviewVal = $('.unsub .reviewFaces li.active').attr('value')
    else 
      reviewVal = 0
    valueVal = 0
    frequencyVal = 0
    relevancyVal = 0
    designVal = 0
    if $('.unsub input[name="value"]').val() then valueVal =  $('.unsub input[name="value"]').val()
    if $('.unsub input[name="frequency"]').val() then frequencyVal =  $('.unsub input[name="frequency"]').val()
    if $('.unsub input[name="relevancy"]').val() then relevancyVal =  $('.unsub input[name="relevancy"]').val()
    if $('.unsub input[name="design"]').val() then designVal =  $('.unsub input[name="design"]').val()
    satisfactionVal =  $('.unsub .selectScore li.selected').val()
    if not satisfactionVal then satisfactionVal = 11
    too_frequent = false
    inbox_overflow = false
    not_expected = false
    not_relevant = false
    repetitive = false
    other = false
    $('ul.reasons input:checked').each ->
      if $(this).attr("name") is "too_frequent" then too_frequent = true
      if $(this).attr("name") is "inbox_overflow" then inbox_overflow = true
      if $(this).attr("name") is "not_expected" then not_expected = true
      if $(this).attr("name") is "not_relevant" then not_relevant = true
      if $(this).attr("name") is "repetitive" then repetitive = true
      if $(this).attr("name") is "other" then other = true
    accountID = $('.unsub input[name="account_id"]').val()
    csrf_token = $('.unsub form.review input[name="csrfmiddlewaretoken"]').val()
    ga('send', 'event', 'feedback', 'feedback', 'feedback', 1)
    $.ajax('/feedback/give-feedback/', 
      {
      type: "POST",
      data: {
        account_id: accountID,
        nps: satisfactionVal,
        value: valueVal,
        frequency: frequencyVal,
        relevancy: relevancyVal,
        design: designVal,
        review: reviewVal,
        too_frequent: too_frequent,
        inbox_overflow: inbox_overflow,
        not_expected: not_expected,
        not_relevant: not_relevant,
        repetitive: repetitive,
        other: other,
        csrfmiddlewaretoken: csrf_token
      },
      dataType: 'json',
      statusCode: {
        500: (response) ->
        ,
        200: (response) -> 
          
        ,
        400: (response) ->  
          
        ,
        502: (response) ->

      }
      }
    )
    .error( (response) ->
    )
    .success( (data) ->
      $('input[name="additionalFeedbackUUID"]').val(data.uuid)
    )
    .always( (data) ->
    )
    $('body').scrollTop(0)

  $('.fb form.review button#feedbackSubmit').click ->
    if $('.fb #feedbackSubmit').hasClass('btn-disabled')
      $('.fbError').show()
      return
    else
      $(".fb .fbForm").removeClass("active").hide()
      $('.fb #alphaOverlay').removeClass("active").hide()
    if $('.fb .selectScore li.selected').length != 0
      $('.fb input[name="nps"]').val($('.fb .selectScore li.selected').val())
    $('.fb .rateit').each (index, element) =>
      id = $(element).attr('id')
      value = $(element).rateit('value')
      $('.fb input[name="'+ id + '"]').val(value)
    if $('.fb .reviewFaces li.active').length != 0
      reviewVal = $('.fb .reviewFaces li.active').attr('value')
    else 
      reviewVal = 0
    valueVal = 0
    frequencyVal = 0
    relevancyVal = 0
    designVal = 0
    if $('.fb input[name="value"]').val() then valueVal =  $('.fb input[name="value"]').val()
    if $('.fb input[name="frequency"]').val() then frequencyVal =  $('.fb input[name="frequency"]').val()
    if $('.fb input[name="relevancy"]').val() then relevancyVal =  $('.fb input[name="relevancy"]').val()
    if $('.fb input[name="design"]').val() then designVal =  $('.fb input[name="design"]').val()
    satisfactionVal =  $('.fb .selectScore li.selected').val()
    if not satisfactionVal and satisfactionVal != 0 then satisfactionVal = 11
    accountID = $('.fb input[name="account_id"]').val()
    csrf_token = $('.fb form.review input[name="csrfmiddlewaretoken"]').val()
    $.ajax('/feedback/give-feedback/', 
      {
      type: "POST",
      data: {
        account_id: accountID,
        nps: satisfactionVal,
        value: valueVal,
        frequency: frequencyVal,
        relevancy: relevancyVal,
        design: designVal,
        review: reviewVal,
        csrfmiddlewaretoken: csrf_token
      },
      dataType: 'json',
      statusCode: {
        500: (response) ->
        ,
        200: (response) -> 
        ,
        400: (response) ->  
        ,
        502: (response) ->

      }
      }
    )
    .error( (response) ->
    )
    .success( (data) ->
      $('input[name="additionalFeedbackUUID"]').val(data.uuid)
    )
    .always( (data) ->
    )
    $('body').scrollTop(0)

  $('#feedbackSubmit').click ->
    if not $('.unsub #feedbackSubmit').hasClass('btn-disabled')
      $('p.mainPrompt').addClass('hidden')
      $('form.review').addClass('hidden')
      $('form.comment').removeClass('hidden')
      emailVal = $('form#fbComment input[name="email"]').val()
      if isValidEmailAddress(emailVal)
        $("button#commentSubmit").removeClass("btn-disabled").prop("disabled", false)

  #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)

  $.fn.allChange = (callback) -> 
    me = this
    last = ""
    infunc = -> 
      text = $(me).val()
      if isValidEmailAddress(text)
        $("button#commentSubmit").removeClass("btn-disabled").prop("disabled", false)
      else
        $("button#commentSubmit").addClass("btn-disabled").prop("disabled", true) 
      setTimeout(infunc, 100)
    setTimeout(infunc, 100)

  characters = 1000
  $("#commentCounter").append("<strong>"+  characters+"</strong> characters remaining")
  $("#fbComment textarea").keyup ->
    if ($(this).val().length > characters)
      $(this).val($(this).val().substr(0, characters))
    remaining = characters -  $(this).val().length;
    $("#commentCounter").html("<strong>"+  remaining+"</strong> characters remaining")
    if(remaining <= 10)
      $("#commentCounter").css("color","#b37e85")
    else
      $("#commentCounter").css("color","#a3a3a3")

  $("#fbComment input[name='email']").allChange()

  $("#fbComment input[name='email']").keydown ->
    $email = $(this)
    setTimeout( ->
      if isValidEmailAddress($email.val())
        $("button#commentSubmit").removeClass("btn-disabled").prop("disabled", false)
      else
        $("button#commentSubmit").addClass("btn-disabled").prop("disabled", true) 
    ,0)

  $("#fbComment input[name='email']").blur ->
    $email = $(this)
    setTimeout( ->
      if isValidEmailAddress($email.val())
        $("button#commentSubmit").removeClass("btn-disabled").prop("disabled", false)
      else
        $("button#commentSubmit").addClass("btn-disabled").prop("disabled", true) 
    ,0)

  $("button#commentSubmit").click ->
    if !$(this).hasClass('btn-disabled')
      commentSubmit()
      $('body').scrollTop(0)
      

  $('form#fbComment').submit (event) ->
    event.preventDefault()
    if !$("button#commentSubmit").hasClass('btn-disabled')
      commentSubmit()
      $('body').scrollTop(0)

  commentSubmit = ->
    csrf_token = $('form#fbComment input[name="csrfmiddlewaretoken"]').val()
    uuid = $('input[name="additionalFeedbackUUID"]').val()
    comments = $('form#fbComment textarea[name="comments"]').val()
    email = $('form#fbComment input[name="email"]').val()
    $.ajax('/feedback/additional-feedback/' + uuid + '/', 
      {
      type: "POST",
      data: {
        comments: comments,
        email: email,
        csrfmiddlewaretoken: csrf_token
      },
      statusCode: {
        500: (response) ->
        ,
        200: (response) ->
        ,
        400: (response) ->
        ,
        502: (response) ->

      }
      }
    )
    .error( (response) ->
    )
    .success( -> 
      if (window.coupon)
        $("#fbComment").hide()
        $("#fbCoupon").show()
      $(".validationContainer").removeClass("active").hide()
      $("#alphaOverlay").toggleClass("active").hide()
      $('a#giveFeedback.fb').addClass('btn-disabled').prop("disabled", true)
      $('li.option button').addClass('btn-disabled').prop("disabled", true)
      $('h2.thanks').removeClass("hidden")  
      $('a#logo.mobile').attr('href', '/')   
    )
    .always( ->
    )


