/**
 * Requires inclusion: json2.js from json.org
 */

/**
 * Performs the typical ajaxSetup for json calls.
 * 
 * @returns same jquery object it is called
 */
jQuery.fn.jsonSetup = function(errorFn) {

	jQuery.ajaxSetup ({  
	    cache: false,
	    contentType: "application/json",
	    dataType: "json",
	    error: errorFn
	});
	
	return this;
};

/**
 * @returns array of fields in key : value form.
 */
jQuery.fn.toJSONValues = function() {

	if(!this.is("form")){	
		return;
	}
	
	var e = new Object();
    var fields = this.serializeArray();
    jQuery.each(fields, function(i, field){
      e[field.name] = field.value;
    });	

    return e;
};

/**
 * @returns a JSON string with key : value pairs from a form.
 */
jQuery.fn.toJSONEntity = function() {
	
	if(!this.is("form")){	
		return;
	}

	return JSON.stringify( this.toJSONValues() );
};
