(function ($) {
  //create ajax commands to be used from the drupal ajax api
  Drupal.ajax.prototype.commands['getBlock'] = function(ajax, response, status) {
    var box = $(this).parents('.boxes-box');
    data = response;
    $.ajax({
      type: "GET",
      url: data.url,
      data: { 'boxes_delta': data.delta },
      global: true,
      success: function(response, status) {
        if($('#boxes-box-form').dialog('isOpen')){
          $('#boxes-box-form').dialog('close');
        }
        $('.hasPopup').removeClass('hasPopup');
        box.removeClass('boxes-box-editing').find('.box-editor').remove().end().find('.boxes-box-content').show();
        ajax.success(response, status);
      },
      error: Drupal.ajax.error,
      dataType: 'json'
    });
  };
  Drupal.ajax.prototype.commands['showBoxForm'] = function(ajax, response, status) {
    if(!$('#boxes-box-form').size() || !$('#boxes-box-form').dialog('isOpen')){
      Drupal.ajax.prototype.commands.insert(ajax, response, status);
      $(response.selector).addClass('hasPopup');
      $('#boxes-box-form')
        .dialog({
          modal : true,
          close: function(e){
            //handle someone closing the box without clicking any buttons
            if (Drupal.wysiwygDetach && $('.wysiwyg', this).val()) {
              var item = $('.wysiwyg', this)[0];
              var params = Drupal.settings.wysiwyg.triggers[item.id];
              Drupal.wysiwygDetach(this, params['format'+$(item).val()])
            }

            $(response.selector).removeClass('hasPopup').html(Drupal.t('Loading...'));
            $('.boxes-ajax.use-ajax-submit.form-submit[value="Cancel"]').click();
            $(this).dialog('destroy').remove();
          },
          open: function(ui, event){
            $(this).siblings('.ui-dialog-titlebar').children('.ui-dialog-titlebar-close').click(function(e){
              $('.boxes-ajax.use-ajax-submit.form-submit[value="Cancel"]').click();
            });
          },
          width: Math.min($(window).width() * .75, 750),
          height: Math.min($(window).height() * .75, 750),
          title : Drupal.t('Edit Box')
        });  
    } else {
      //change the selector to just update the current form - in place (in the popup)
      response.selector = '#boxes-box-form';
      Drupal.ajax.prototype.commands.insert(ajax, response, status);
    }
    
  };

  Drupal.behaviors.boxes = { 
    attach: function(context, settings) {
      $('div.boxes-box-controls a:not(.boxes-processed)')
        .addClass('boxes-processed')
        .click(function() {
          // If we are not using edit-in-place, bail.
          if (this.href.indexOf('/admin/structure/block/manage/boxes/') != -1) {
            return;
          }
          var box = $(this).parents('.boxes-box');
          if (box.is('.boxes-box-editing')) {
            box.removeClass('boxes-box-editing').find('.box-editor').remove().end().find('.boxes-box-content').show();
          }
          else {
            // Show editing form - the form itself gets loaded via ajax..
            box.find('.boxes-box-content').hide().end().addClass('boxes-box-editing').prepend('<div class="box-editor"><div class="swirly"></div></div>');
          }
          return false;
        });
   
      Drupal.ajax.prototype.commands['preReplaceContextBlock'] = function(ajax, response, status) {
        data = response
        Drupal.settings.boxes = Drupal.settings.boxes || {};
        var e = $('#' + data.id + ' a.context-block:first').clone();
        Drupal.settings.boxes[data.id] =  e;
      };

      Drupal.ajax.prototype.commands['postReplaceContextBlock'] = function(ajax, response, status) {
        data = response
        $('#' + data.id).append(Drupal.settings.boxes[data.id]);
        $('form.context-editor.context-editing').each(function() {
          var id = $(this).attr('id');
          if (Drupal.contextBlockEditor[id]) {
            Drupal.contextBlockEditor[id].initBlocks($('#' + data.id));
          }
        });
      };
      //If we have a contextual link to configure the block lets get rid of that and move our edit link
      //to the contextual dropdown
      $('.boxes-box-controls', context).each(function () {
        // See if we are within a panel.
        if ($(this).parent().parent().hasClass("pane-content")) {
          $(this).hide();
        }
        if($(this).parents(".block").find(".block-configure").length > 0) {
          $(this).parents(".block").find(".block-configure").after($(this).find("li.edit"));
          $(this).parents(".block").find(".block-configure").detach();
        }
      });

      // Submit box form if Enter is pressed
      $('#boxes-box-form input').keydown(function (e) {
        if (!e) {
          e = window.event;
        }
        // Enter
        if (e.keyCode == 13) {
          e.preventDefault();
          // Save is always the first button (see boxes.module)
          $('.boxes-ajax.use-ajax-submit.form-submit:first').click();
        }
      });

      //apply the popup form to 'add boxes' also  
      $('.boxes-box-editing .box-editor #boxes-box-form').not('.processed').addClass('processed').dialog({
        modal : true,
        close: function(e){
           //handle someone closing the box without clicking any buttons
           $(this).remove();
        },
        open: function(event, ui) { 
          //hide the close button on add on the popup to prevent various annoying errors
          $(this).siblings('.ui-dialog-titlebar').children('.ui-dialog-titlebar-close').hide();
        },
        width: Math.min($(window).width() * .75, 750),
        height: Math.min($(window).height() * .75, 750),
        title : Drupal.t('Configure Box')
      });
    }
  
  };
})(jQuery);
