/**
 * Provides various utilities for managing form submission.
 *
 * @copyright SiteCrafting, Inc.
 * @author Nick Williams
 * @version 1.0.0
 */
SC.FormUtils = {
	/**
	 * Serializes an object literal of key-value pairs into a URL-friendly string.
	 *
	 * @param Object params the parameters to be serialized
	 * @param boolean trim whether or not to trim empty values
	 * @return string the serialized result
	 */
	serializeParams: function(params, trim) {
		// Setup
		var result = '';
		var values = [];
		
		trim = trim ? trim : false;
		
		for(var key in params) {
			if(params.hasOwnProperty(key) && key.substr(0, 1) != '_') {
				if(!trim || params[key]) {
					values[values.length] = key + ':' + params[key];
				}
			}
		}
		
		result = values.join('|');
		
		return result;
	},
	
	/**
	 * Unserializes a string of key-value pairs into an object literal.
	 *
	 * @param string params the parameters to be unserialized
	 * @param boolean trim whether or not to trim empty values
	 * @return Object the generated result
	 */
	unserializeParams: function(params, trim) {
		// Setup
		var result = {};
		var values = params.split('|');
		
		trim = trim ? trim : false;
		
		for(var i = 0; i < values.length; i++) {
			var parts = values[i].split(':');
			
			if(!trim || parts[1]) {
				result[parts[0]] = parts[1];
			}
		}
		
		return result;
	},
	
	/**
	 * Enables the interception of form submissions.
	 */
	interceptSubmissions: function() {
		jQuery(function($) {
			$('form').live('submit', function(e) {
				try {
					// Setup
					var target = null;
					var $this = $(this);
					var params = {};

					// Clear Default Values
					$(this).find('input').each(function(index, value) {
						if($(value).attr('title') == $(value).val()) {
							$(value).val('');
						}
					});

					$(this).find('textarea').each(function(index, value) {
						if($(value).attr('title') == $(value).val()) {
							$(value).val('');
						}
					});

					// Validate
					var valid = true;
					var message = 'Your submission could not be processed. Please resolve the following and try again:<ul>';

					$(this).find('input, select, textarea').filter('[data-required]').each(function(key, value) {
						value = $(value);

						if(!$.trim(value.val())) {
							valid = false;

							message += '<li>' + value.data('required') + '</li>';
						}
					});

					message += '</ul>';

					if(!valid) {
						utils.alert('error', message);
						$(this).find('input[type=password]').val('');
					}
					else {
						var form = $this.serializeArray();

						// Assemble Form Data
						$.each(form, function() {
							if(params[this.name]) {
								if(!params[this.name].push) {
									params[this.name] = [params[this.name]];
								}

								params[this.name].push(this.value || '');
							}
							else {
								params[this.name] = this.value || '';
							}
						});

						var parts = $this.attr('action').split('.');
						var method = parts.shift();
						params._action = parts.join('.');

						if(method == 'local') {
							$this.trigger('response', params);
						}
						else if(method == 'ajax') {
							// Submit AJAX Request (based on form's action attribute)
							$.ajax({
								type: 'POST',
								url: 'ajax.php',
								data: params,
								dataType: 'json',
								success: function(data) {
									$this.trigger('response', data);
								}
							});
						}
					}

					$(this).find('input, select, textarea').blur();
					e.preventDefault();
					return false;
				}
				catch(ex) {
					//utils.alert('error', 'An error occurred while processing your submission. Please try again or contact a website administrator.');
					console.log(ex);
					e.preventDefault();
					return false;
				}
			});
		});
	}
};
