$.extend({
	param: function( a, nest_in ) {
		var s = [ ];
		// check for nest
		if (typeof nest_in == 'undefined') nest_in = false;
		
		function nested(key) {
			if (nest_in)
				return nest_in + '[' + key + ']';
			else
				return key;
		}
		function add( key, value ){
			key = nested(key)
			s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
		};
		// If an array was passed in, assume that it is an array
		// of form elements
		if ( jQuery.isArray(a) || a.jquery )
			// Serialize the form elements
			jQuery.each( a, function(){
				add( this.name, this.value );
			});

		// Otherwise, assume that it's an object of key/value pairs
		else
			// Serialize the key/values
			for ( var j in a )
				// If the value is an array then the key names need to be repeated
				if ( jQuery.isArray(a[j]) )
					jQuery.each( a[j], function(){
						add( j, this );
					});
				else if (a[j].constructor == Object)
					s.push($.param(a[j], nested(j)));
				else
					add( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] );

		// Return the resulting serialization
		return s.join("&").replace(/%20/g, "+");
	}
});

jQuery(function($) {
  $('#upload_images').MultiFile({
	  list: "#uploaded_images",
	  STRING: {
	    remove: 'remove'
	  }
  })
  
  function errorCallback(request, status, exception) {

  };
  
  function publish() {
    var advertData = $.param({
      'advert' : { 'published': 1 },
      'authenticity_token' : authToken()
    });

    updateStatus($(this), advertData, "Your listing has been published.");
    return false;
  };
  
  function unpublish() {
    var advertData = $.param({
      'advert' : { 'published': 0 },
      'authenticity_token' : authToken()
    });

    updateStatus($(this), advertData, "Your listing has been withdrawn.");
    return false;
  };
  
  function updateStatus(updating, advertData, message) {
    if(typeof message == 'undefined'){
      message = "Your listing has been updated!"
    }
    $.ajax({
      data: advertData,
      dataType: 'script',
      success:function(response, status) {
        $('div.notice').remove();
        updating.parents('li.listing, div.listing')
                .find('a.publish').unbind('click', publish).andSelf()
                .find('a.unpublish').unbind('click', unpublish).andSelf()
                .find('a.destroy').unbind('click', destroy).andSelf()
                .find('div.meta-menu').remove().andSelf()
                .append("<div class=\"notice\">"+message+"</div>").andSelf()
                .find('div.description').after(response.toString()).andSelf()
                .find('a.publish').click(publish).andSelf()
                .find('a.unpublish').click(unpublish).andSelf()
                .find('a.destroy').click(destroy);

        setTimeout(function() {
          $('div.notice').fadeOut('fast', function() {
            $(this).remove();
          });
        }, 2000);
      },
      error: errorCallback, 
      type: 'PUT', 
      url: updating.attr('href')
    });
  };
  
  function destroy() {
    if (confirm("Are you sure you want to delete this listing?")) {
      $this = $(this);
      $.ajax({
        dataType: 'json',
        success: function(response, status) {
          $this.parents('li.advert').slideUp(200, function() {
            $(this).remove();
          });
        },
        error: errorCallback,
        type: 'DELETE',
        url: $this.attr('href')
      });
    };
    return false;
  }
  
  function destroyImage() {
    if (confirm("Are you sure you would like to remove this image?")) {
      var $this = $(this);
      $.ajax({
        dataType: 'json',
        complete: function(response, status) {
          $this.parent('div').fadeOut('fast', function() {
            $(this).remove();
          });
        },
        type: 'DELETE',
        url: $this.attr('href')
      });
    };
	  return false;
	}
	
	function updateAcreField() {
	  var acres = ($('#advert_height').val() * $('#advert_width').val())/4840
    $('#advert_acres').val(acres);
	};
	
  // updateAcreField();
	$('body.adverts select.size').change(updateAcreField);
  
  $('body.adverts #advert_acres').change(function(){
    var size = $('#advert_acres').val()*4840;
    var length = Math.round(Math.sqrt(size));
    $('#advert_height').val(length);
    $('#advert_width').val(length);
  });
  
  $('body.adverts a.publish').click(publish);
  $('body.adverts a.unpublish').click(unpublish);
  $('body.adverts a.destroy').click(destroy);
  
  $('body.users a.publish').click(publish);
  $('body.users a.unpublish').click(unpublish);
  $('body.users a.destroy').click(destroy);
  
  $('a.remove-uploaded-file').click(destroyImage);
});
    