//
// Created By Chris Richards 2008
// Last Update: October 2009
//
// Seralize a input elements into a key/value pair for AJAX Transport. ($.post)
//	The key is the element id (except for radio buttons which use name.)
//	TextAreas are encoded with encodeURIComponent
//
//  .Net SessionState controls (ids that start with __) are excluded from the result.
//

jQuery.fn.serializeForm = function(){
    //Create an object to hold the data, this is the same type of object that is expected by $.post
    var formparams = {};
    //Loop over each element we have
    this.each(function(){
		//We only care about input controls
        jQuery("input, select, textarea", this).each(function()
		{
			//Local Varaibles
			var jObj = jQuery(this);		//Refrence to the jQuery object
            var name = jObj.attr("id");		//The ID of the element.
			name = "" != name ? name: jObj.attr("name"); //If the ID isn't valid, use the name attribute
            var data = jObj.val();			//The value of the element
			var type = jObj.attr("type");	//Type of input control
            
			//
			// Check for inputs that use the checked paramiter
			//
            if( "checkbox" == type ) 
            {
                if( this.checked ) {
                    formparams[name] = "true";
                } else {
                    formparams[name] = "false";
                }
            } 
            else if ("radio" == type )
            {
				//Radio buttons only care about the checked one
                if( this.checked )
                {
                    formparams[name] = data;
                }
            }
			//
			// These inputs are straightforward
			//
            else {
                //Ignore ASP.NET Crap
                if(! name.match(/__.+/) ) {
                    //Do we already have a value for this?
                    if( formparams[name] === undefined ) {
                        //Add it to our list, encodeURI for TextAreas
                        if( "textarea" == type ) {
                            //encodeURI for TextAreas
                            formparams[name] = encodeURIComponent( data ); //Add it
                        } else {
                            formparams[name] =   data; //Add it
                        }              
                    } else {
                        //Append it, encodeURI for anything we have to append.
                        formparams[name] += "," + encodeURIComponent( data );
                    }
                }
            }
        });
    });
    //Return the completed object.
    return formparams;
};