function reloadPreview(el) {
   el = $(el);
   img = el.val();
   el.parents('tr').next('tr').find('img').attr('src', img);
}

function correctColorCode(el) {
   el = $(el);
   text = el.val();
   if (text.indexOf('#') != 0) {
      text = "#" + text;
      el.val(text);
   }
}

$(document).ready(function() {
   // Allow image url inputs to preview their image in respective preview container
   $('.img_preview').blur(function() {
      reloadPreview(this);
   })
   
   // Ensure there is a "#" at the beginning of all color codes
   $('.color_input').blur(function() {
      correctColorCode(this);
   })
   
   $('#save_new_category').click(function(e) {
      var name = $('#new_category').val();
      if (name == null && name == "") {
         $('#new_category_error').text("Category name must not be blank.").show();
         return;
      }
      var parent = $('#categories').val();
      if (parent == null) {
         $.postJSON(
            '/categories/new',
            {
               name: name
            },
            function(data) {
               if (data.success) {
                  $('#categories').empty().append(data.categoriesHTML);
               } else {
                  $('#new_category_error').text("Could not save new category.").show();
               }
            }
         );
      } else if (parent.length == 1) {
         parent = parent[0];
         $.postJSON(
            '/categories/new',
            {
               name: name,
               parent: parent
            },
            function(data) {
               if (data.success) {
                  $('#categories').empty().append(data.categoriesHTML);
               } else {
                  $('#new_category_error').text("Could not save new category.").show();
               }
            }
         );
      } else {
         $('#new_category_error').text("Please select only one parent category.").show();
      }
   })
   
   $('#delete_category').click(function(e) {
      cats = $('#categories').val();
      if (cats != null && cats.length > 0) {
         if (confirm("Are you sure you want to delete " + cats.length + " categories? You can't undo this.")) {
            $.postJSON(
               '/categories/destroy',
               {
                  ids: cats.join(",")
               },
               function(data) {
                  if (data.success) {
                     $('#categories').empty().append(data.categoriesHTML);
                  } else {
                     $('#new_category_error').text("Could not delete category.").show();
                  }
               }
            );
         }
      }
   })
})