$(document).ready(function (){
   
   $('#add_set a').toggle(function() {
       $('#picture_collection_form').show();
       $(this).text('Nevermind');
   }, function() {
       $('#picture_collection_form').hide();
       $(this).text('Add Set');
   });
   
   $("#add_picture_to_set").toggle(function() {
       $('#add_picture_to_set_form').show();
       $(this).text('Nope');
   }, function(){
       $('#add_picture_to_set_form').hide();
       $(this).text('Add Picture to Set');
   });
   
   $('.add_item').live('click', function() {

       var menu_link = $(this).find('a');
       var menu_form = $(this).find('.add_menu');
       
       menu_link.hide();
       menu_form.show();
       
   });
   
   $('#picture_collection_form form').submit(function() {
       var _self = $(this);
       var form_options = {
           dataType     : 'json',
           success      : function(json) {

               if(json.success) {                   
                   var url = '/' + json.username + '/pictures/collections/' + json.set_slug + '/';
                   $(location).attr('href', url);
               } else {
                   // TODO inform the user that it failed
                   // For example, like below:
                   // for (item in json.errors)
                   // {
                   //     // Make sure that the error doesn't already exist by checking length of items
                   //     if (!(_self.find('#error_'+item).length > 0))
                   //     {
                   //         _self.find('input[name='+item+']').before('<p id="error_'+item+'" class="error">'+json.errors[item]+'</p>');
                   //     }
                   // }
               }
               
           }
       }
       
       $(this).ajaxSubmit(form_options);
       return false;
              
   });
   
   $('#add_picture_to_set_form form').submit(function() {
       
       var form_options = {
           dataType : 'json',
           success  : function(json) {
               if(json.success) {
                   window.location.reload(true);
               }
           }
       }
       
       $(this).ajaxSubmit(form_options);
       return false;
       
   });

});