// AJAX setup
$.ajaxSetup({
  type: "POST",
  dataType: "json"
})


// jQuery + AJAX + Rails + protect_against_forgery FIX
$(document).ajaxSend(function(event, request, settings) {
  if (typeof(AUTH_TOKEN) == "undefined") return
  settings.data = settings.data || ""
  if (/authenticity_token=/.test(settings.data)) return
  settings.data += ((settings.data == "") ? "" : "&") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN)
})


// BEHAVIOUR
$(document).ready(function() {

  // CANCEL buttons
  $("input.button.cancel").click(function() {
    console.log("asdf");
    var classes = $(this).attr('class').split(' ')
    for (var i = 0; i < classes.length; i++) {
      console.log(classes[i])
      if ((classes[i] != 'button') && (classes[i] != 'cancel') && (classes[i] != 'root')) {
        // redirect to the custom action
        window.location = '/' + classes[i].replace(/_/g, '/')
        return
      }
      if (classes[i] == 'root') {
        // redirect to root
        window.location = '/'
        return
      }
    }
  })

  // focus the email field for login/register/etc. forms
  $('input[value=""]#user_email').focus()

  // preload the spinner image
  var spinner = $('<img/>').attr('src', '/images/spinner.gif').attr('alt', 'Chwila, moment...')

  // Function -> attach the spinner image to a given element, ie: $('element').attach_spinner()
  $.fn.attach_spinner = function() {
    $(this).append(spinner)
  }

  // EMAIL ADDRESSES -> unobfuscate
  $('span.email').each(function() {
    // convert text inside the element to a valid email address
    email = $(this).text().replace(/ AT /i, '@').replace(/ \. /g, '.').replace(/ DOT /ig, '.')
    // wrap link tag around the element
    $(this).wrap('<a href="mailto:' + email + '"></a>');
    // put the email address as text inside the link tag (old class="email" element is automatically removed)
    $(this).parent().text(email)
  })

  // RATING STARS -> hover effects
  $('ul.rating-stars span').hover(function() {
    // display different message for each hovered star
    $(this).parent().parent().parent().find('p.rating-message').text($(this).attr('title')).show()
    // hide current rating
    $(this).parent().parent().find('li.current-rating').hide()
    // mark appropriate number of stars as selected
    $(this).parent().parent().find('li.selected-rating').css('width', $(this).css('width'))
  }, function() {
    // hide the hover message
    $(this).parent().parent().parent().find('p.rating-message').text('Oceń:')
    // show current rating
    $(this).parent().parent().find('li.current-rating').show()
    // hide the selection
    $(this).parent().parent().find('li.selected-rating').css('width', 0)
  })

  // RATING STARS -> click event (rate a wish)
  $('ul.rating-stars span').click(function() {
    var id = $(this).parent().parent().parent().parent().parent().attr('id').substr(4)
    var value = $(this).text()

    // AJAX
    $.ajax({
      url: '/ocen',
      data: "id=" + id + "&value=" + value,
      beforeSend: function() {
        $('#wish' + id + ' p.rating-message').empty().attach_spinner()
      },
      success: function(json) {
        // display message (hides the spinner)
        $('#wish' + id + ' p.rating-message').text(json.message)
        // update votes
        $('#wish' + id + ' p.ratings-count').text(json.ratings_count + 'x')
      }
    })

    // disable hover actions
    $(this).parent().parent().find('span').unbind()
    // mark appropriate number of stars as selected
    $(this).parent().parent().find('li.selected-rating').css('width', $(this).css('width'))
  })


  // WISH EDIT

  // 'edit' button
  $('div.wish input.edit').click(function() {
    var id = $(this).parent().parent().parent().attr("id").substr(4)
    var old_content = $(this).parent().parent().parent().find('div.content').clone(true)

    $.ajax({
      url: '/edytuj/' + id,
      type: "GET",
      dataType: "html",
      beforeSend: function() {
        $('#wish' + id + ' p.edit').attach_spinner()
      },
      success: function(html) {
        // show edit form
        $('#wish' + id + ' div.content').empty().append(html).removeClass('administrative-buttons')

        // 'save' button
        $('#wish' + id + ' input.save').click(function() {
          $.ajax({
            url: '/edytuj/' + id,
            data: $('#wish' + id + ' form').serialize(),
            beforeSend: function() {
              $('#wish' + id + ' span.message').empty().attach_spinner()
            },
            success: function(json) {
              // show the updated wish or the error message
              if (json.message == "ok") {
                // old content
                $('#wish' + id + ' div.content').replaceWith(old_content)
                // new body
                $('#wish' + id + ' div.body').replaceWith(json.body)
                // new category
                $('#wish' + id + ' p.category a').attr("href", "/" + json.category.slug).text(json.category.name)
                // yellow fade
                $('#wish' + id + ' div.body p').css('backgroundColor', '#FF8').animate({backgroundColor: 'transparent'}, 1000)
              } else $('#wish' + id + ' span.message').text(json.message)
            }
          })
        })

        // 'cancel' button
        $('#wish' + id + ' input.cancel').click(function() {
          // show the wish
          $('#wish' + id  + ' div.content').replaceWith(old_content)
        })
      }
    })
  })


  // WISH REMOVAL

  // 'delete' button
  $('div.wish input.delete').click(function() {
    $(this).parent().find('span.confirmation').fadeIn(100)
  })

  // 'yes' button
  $('div.wish input.yes').click(function() {
    var id = $(this).parent().parent().parent().parent().attr("id").substr(4)

    $.ajax({
      url: '/usun',
      data: "id=" + id,
      beforeSend: function() {
        $('#wish' + id + ' span.confirmation').attach_spinner()
      },
      success: function(json) {
        // hide the wish or show the error message
        json.message == "ok" ? $('#wish' + id).parent().fadeOut(200) : $('#wish' + id + ' span.confirmation').text('Wystąpił błąd.')
      }
    })
  })

  // 'no' button
  $('div.wish input.no').click(function() {
    $(this).parent().fadeOut(100)
  })

})
