(function($) {
  var checkIt = setInterval(function() {
    if ($.mw && $.mw.binder) {
      var photoEditor = $.mw.binder({
        bind: function($scope) {
          $(".mw_photo_delete", $scope).click(function(e) {
            if (!confirm("Do you really want to delete this photo?")) 
            {
              return e.preventDefault();
            }
          });
          $('.full_res').click(function(e) {
            window.open(this.href);
            return e.preventDefault();
          });
          $(".mw_photo_edit_action", $scope).click(function(e) {
            e.preventDefault();
            var action = this.href;
            $.get(action, function(data) {
              $("IMG.mwphoto", $scope).each(function() {          
                this.src = this.src+'?'+Math.random();
                $(this).css({'width':'auto','height':'auto'});
              });
            });
          });      
        }
      });
      clearInterval(checkIt);
    }
  }, 10);

  $(function() {
    if (!$.mw.photoSettings) {
      alert('The settings haven\'t been set');
    };
    $("#mw_photo_gallery_edit_form input.delete").click(function(e) {
      if (!confirm("Do you really want to delete this gallery?  This will delete all subgalleries, and may leave 'orphaned' photos."))
      {
        return e.preventDefault();
      }
    });
    // Gallery Ordering
    if ($.fn.sortable && $('.mw_photo_list').length && $('.mw_photo_list a.edit').length) {
      var $ajaxNotifier = $('Updating order for gallery');
      $("<div>To change the order of photos, click and drag.</div>").insertBefore($(".mw_photo_list"));
      $(".mw_photo_list").sortable({update: function() {
        var order = [];
        var galleryid = $('.mw_photo_list')[0].id.replace(/^mw_photo_gallery_/, '');
        $(".mw_photo_list .photo").each(function() {
          order.push(this.id.replace(/^mw_photo_/, ''));
        });
        $ajaxNotifier.insertBefore($('.mw_photo_list'));
        $.ajax({
          type: 'POST',
          url: $.mw.photoSettings.orderUrl.replace(/_id/, galleryid),
          dataType: 'json',
          data: {'order':order.join(':') },
          success: function(data) {
            $ajaxNotifier.remove();
          },
          error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert('There was an error when trying to update order');
          }
        });
      }});
      
    }
    
    $('.mw_photo_list .photo .edit').formLink({
      postEdit: function(event, data) {
        var $photo = $(this).closest('.photo').find('img');
        var old = $photo.attr('src');
        $photo.attr('src', old+(old.indexOf('?')>0?'&':'?')+'cc='+new Date()).css({'width':'auto', height: 'auto'});        
      },
      saved: function(event, data) {
        console.log(data);
        if (data.deleted) {
          $photo.remove();
        }
      }
    });
  });
})(jQuery);
