
// 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() {

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

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

  // focus the email field for login/register/etc. forms (but only if the user hasn't started typing yet)
  $('input[value=""]#user_email').focus()

  // add 'cancel' functionality to cancel buttons
  $("input.button.cancel").click(function() {
    var classes = $(this).attr('class').split(' ')
    for (var i = 0; i < classes.length; 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
      }
    }
  })

  // unobfuscate email addresses
  $('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)
  })

  // captcha auto-fill & hide
  $('#captcha_text').attr('value', 'abc').parent().hide()

  // disable the comments submit button after the first click to prevent the double submit error
  $('#dodaj-komentarz').click(function() {
    $(this).attr('value', 'Chwila moment…').attr('disabled', 'disabled').parent().parent().submit()
    return false
  })

  // DOCUMENTS

  // delete unpublished document
  $('ul.documents li form.button-to input.delete').click(function() {
    return confirm('Czy na pewno chcesz usunąć ten dokument?')
  })


  // HIGHLIGHTS

  // show picture
  $('#highlight_show_picture').click(function() {
    if ($(this).attr('checked')) {
      $('#highlight_picture_folder, #highlight_picture_name').removeAttr('disabled')
    } else {
      $('#highlight_picture_folder, #highlight_picture_name').attr('disabled', 'disabled')
    }
  })

  // activate/deactivate highlight
  $('#highlight_is_active').click(function() {
    if ($(this).attr('checked')) {
      $('#highlight_document_id, #highlight_show_picture, #highlight_replacement_title, #highlight_replacement_lead').removeAttr('disabled')
      if ($('#highlight_show_picture').attr('checked')) $('#highlight_picture_folder, #highlight_picture_name').removeAttr('disabled')
    } else {
      $('#highlight_document_id, #highlight_picture_folder, #highlight_picture_name, #highlight_show_picture, #highlight_replacement_title, #highlight_replacement_lead').attr('disabled', 'disabled')
    }
  })


  // AD DISABLE ICON (in ACTIVE ADS view)

  $('#ads.active p.ad img.disable-icon')
    // by default hide
    .css('display', 'none')
    // disable by AJAX call
    .click(function() {
      var html_id = $(this).attr('id')
      var id = html_id.split(/\-/)[2]
      $.ajax({
        url: '/reklamy/wylacz',
        data: 'id=' + id,
        beforeSend: function() {
          $('#' + html_id).hide().parent().attach_spinner()
        },
        success: function(json) {
          if (json.status == 'success') {
            $('#' + html_id).parent().parent().fadeOut(500)
          }
        }
      })
    })

  // show when hovering over the ad
  $('#ads.active p.ad').hover(
    function() { $(this).find('img.disable-icon').css('display', 'inline') },
    function() { $(this).find('img.disable-icon').css('display', 'none') }
  )


  // CLASSIFIEDS & COMMENTS & FIRMS

  // 'ukryj' 'usuń' 'przywróć' buttons (show confirmation message)
  $('#classifieds p.commands a[href="#"], #comments p.commands a[href="#"], #firms p.commands a[href="#"]').click(function() {
    var id = $(this).parent().parent().attr('id').split(/-/)[1]
    var action = $(this).attr('class')
    var controller = $(this).parent().parent().find('p.confirmation').attr('id').split(/-/)[0]
    $('#' + controller + '-' + action + '-' + id).slideToggle(100)
    return false
  })

  // 'NIE' buttons
  $('#classifieds p.confirmation input.no, #comments p.confirmation input.no, #firms p.confirmation input.no').click(function() {
    $(this).parent().slideToggle(100)
  })

  // 'TAK' buttons
  $('#classifieds p.confirmation input.yes, #comments p.confirmation input.yes, #firms p.confirmation input.yes').click(function() {
    var node_id = $(this).parent().parent().attr('id') // komentarz-7810
    var html_id = $(this).parent().attr('id') // komentarze-usun-7810
    var params = html_id.split(/\-/)
    var controller = params[0]
    var action = params[1]
    var id = params[2]

    // RESTful
    if (action == 'destroy') {
      var request_data = {'_method' : 'DELETE'}
      var request_url = '/' + controller + '/' + id
    } else if (action == 'accept') {
      var request_data = {'_method' : 'PUT'}
      var request_url = '/' + controller + '/' + id + '/zaakceptuj'
    } else if (action == 'reject') {
      var request_data = {'_method' : 'PUT'}
      var request_url = '/' + controller + '/' + id + '/odrzuc'
    } else {
      // old-school
      var request_data = {'id' : id}
      var request_url = '/' + controller + '/' + action
    }

    // AJAX
    $.ajax({
      url: request_url,
      data: request_data,
      beforeSend: function() {
        $('#' + html_id + ' span').remove()
        $('#' + html_id).attach_spinner()
      },
      success: function(json) {
        if (json.status == 'success') {
          $('#' + node_id).fadeOut(500)
        }
        if (json.status == 'error') {
          $('#' + html_id + ' img').remove()
          $('#' + html_id).append('<span>' + json.message + '</span>')
        }
      }
    })
  })

})
