// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
$(document).ready(function() {
  $('.has_search_selects select').change(function() {
    $(this).parents('form').submit();
  });

  $('.has_search_selects input[type="checkbox"]').change(function() {
    $(this).parents('form').submit();
  });

  $('#search_results thead a, #search_results .pagination a').live('click', function() {
    $('#search_results').load(this.href);
    return false;
  });

  $('#products_index_search_form #search_name_mask').autocomplete("/admin/products_index/autocomplete", {
    minChars: 3, delay: 2000, width: 200, selectOnly: true
  });

  $('#popular_categories a').click(function(e) {
    e.preventDefault();
    $('#money_cat').val($(this).text());
  });

  $('._product').change(function() {
    var rel = $(this).attr('rel');
    var checked = $(this).attr('checked');
    $("input[type='checkbox'][rel='"+rel+"']").attr('checked', checked);
  });

  $('#templates a').click(function(e) {
    e.preventDefault();
    var rel = $(this).attr('rel');
    $('#message_body').val($('#template_'+rel).html());
  });

  var calculate_cashback = function() {
    var cashback = $('#cash_got').val() - $('#amount').html()
    if (isNaN(cashback)) cashback = '-';
    $('#cashback').html(cashback);
  };

  $('#cash_got').live('keyup', function() {
    calculate_cashback();
  });

  if ($('#cash_got').val() != '') {
    calculate_cashback();
  };

  $('#products ._product').change(function(e) {
    var checked = $(e.target).attr('checked');
    var rel = $(e.target).attr('rel');
    $("#products ._position[rel="+rel+"]").attr('checked', checked);
  });
});

var bikecheck_categories_droppables = function() {
  $('#bikechecks tr').droppable({
    hoverClass: 'drop_hover',
    drop: function(event, ui) {      
      $.ajax({
        type: 'post',
        dataType: 'script',
        data: {
          source: $(ui.draggable).attr('id'),
          target: $(this).attr('id'),
          reorder: $(ui.helper).hasClass('reorder'),
          authenticity_token: window._token
        },
        url: '/admin/bikecheck_categories/drop'
      });
    }
  });

  $('#bikechecks tr ._move').draggable({
    revert: 'invalid',
    helper: function() {
      return "<div class='helper'>"+$(this).attr('rel')+"</div>"
    },
    drag: function(event, ui) {
      if (event.altKey) {
        $(ui.helper).addClass('reorder');
      } else {
        $(ui.helper).removeClass('reorder');
      }
    }
  });
};