/*
 * 	FormPop - jQuery plugin
 *	written by Jake Holman
 *	http://www.jakeisonline.com/development/formpop
 *
 *	Copyright (c) 2009 Jake Holman (http://www.jakeisonline.com)
 *	Dual licensed under the MIT (MIT-LICENSE.txt)
 *	and GPL (GPL-LICENSE.txt) licenses.
 *
 *	Built for jQuery library
 *	http://jquery.com
 *
 */

(function($){  
  
	$.fn.formpop = function(){ 	
	
		return this.each(function() {
			  
			doForm(this);   
						  
			function doForm(element){  
			 
				// Find the query string in the URL
				var query = window.location.search.substring(1);
				// The split value of the URL Parameter String is '&'
				var parms = query.split('&');
				
				// Define the array we're going to use to put all the URL Parameters into, key => value
				var queryParam = new Array();
				
				// Let's go ahead and grab the parameters from the URL now.
				getParameters(element);
			  
				function getParameters(element) {
				
					// Loop through the Parameter
					for (var i=0; i<parms.length; i++) {
						var pos = parms[i].indexOf('=');
						if (pos > 0) {
							// The Key starts 0 symbols after the '&' and ends 1 symbols before the '='
							var key = parms[i].substring(0,pos);
							// The Value starts 0 symbols after the '=' and ends 1 symbols before the '='
							var val = parms[i].substring(pos+1);
							queryParam[key] = val;
						} else { return false; /* no point going any further if there's no parameters */ }
					}
					
					// Ok, we grabbed some parameters so lets attempt to populate the form
					populateForm(element);
					
				}
				
				function populateForm(element) {
					// We're only going to iterate through the input elements, saves on processing.
					$(":input", element).each(function() {
					
						// If the type of element is a 'text', then... 
						if(this.type === 'text') {			
							// Check if there is a value for this field within the Parameters
							if(typeof(queryParam[this.id]) != 'undefined') {
								// There is, so lets remove any URL encoding
								text = unescape(queryParam[this.id]);
								text = text.replace(/%26/g,'&');
								$(this).val(text);
							}
						}
						
					});
				}
			};  	  
		});  
	};

	// iteration ended.
	return this;
  
})(jQuery);  