/**
 * (C) 2008-2009 Marcello Barnaba <vjt@openssl.it>
 * http://sindro.me/
 */
var BusinessRegistration = {

  step_3: function() {
    // Class names must follow the convention:
    //  [size] <type>frame
    // e.g. large photoframe, medium logoframe, photoframe, logoframe
    // 
    $.fn.getThumbSize = function() {
      var size = $(this).attr('class').replace(/\s*\w+frame$/, '');
      if (size.length == 0) size = 'thumb';
      return size;
    }

    // Quite messy, but it works.
    $.fn.getPictureType = function() {
      return $(this).attr('class').replace(/(^|\w*\s*)(\w+)frame$/, '$2');
    }

    $.fn.deleteCurrentPhoto = function(frame, form) {
      // Delete current photo, if it exists
      var business_id = form.find('input[name=business_id]').attr('value');
      frame.find('.change_button').fadeOutAndRemove();

      $.ajax({ url: form.attr('action') + '/' + $(this).attr('rel'), // chunky bacon!
        type: 'DELETE',   data: { business_id: business_id, type: frame.getPictureType() },
        beforeSend: function() { $('#spinner').show('blind'); $(this).fadeOutAndRemove() }
      });
    }

    $.fn.submitPhotoForm = function(frame) {
      $(this).ajaxSubmit({
        dataType  : 'json',  data: { size: frame.getThumbSize(), type: frame.getPictureType() },

        beforeSend: function()     { $('#spinner').show('blind'); },
        error     : function()     {  alert("File non valido!");  },
        complete  : function()     { $('#spinner').hide('blind'); },
        success   : function(data) {
          $(this).blankFields();
          frame.html('<img src="' +data.href+ '" rel="' +data.id+ '"/>');
          $('.change_button:first').clone().appendTo(frame).fadeIn('fast');
        }
      });
    }

    $('[class$=frame]').ajaxFormUpload({
      form: '#ajax_upload',
      linked: 'form.edit_business',
      upload: function(frame, form) {
        frame.find('img[rel]').deleteCurrentPhoto(frame, form);

        // Set photo position using the `rel` attribute of the hovered frame
        form.find('#photo_position').attr('value', frame.attr('rel'));

        // submit tha form! chunky bacon!
        form.submitPhotoForm(frame);
      }
    });

    $(document).ready(function() {
      //show change_button divs on currently loaded images
      $('.change_button:first').clone().
        appendTo($('.photoframe img[rel], .logoframe img[rel]').parent());
      $('.change_button:gt(0)').fadeIn();
    });
  }
}
