/**
 * The contact form is validated and submitted here.
 *
 * @module FrancesTwiddy
 * @class Contact
 * @author Dan Whitfield
 */
var Contact = 
{
	/**
	 * Has the form passed validation?
	 *
	 * @property _submissionPossible
	 * @type Bool
	 * @private
	 */
	_submissionPossible: true,
	
	
	/**
	 * Store all the validation errors for display.
	 *
	 * @property _validationErrors
	 * @type Array
	 * @private
	 */
	_validationErrors: [],
	
	
	/**
	 * Store all the passed fields.
	 *
	 * @property _passedFields
	 * @type Object
	 * @private
	 */
	_passedFields: {},
	
	
	/**
	 * Store all form elements for looping.
	 *
	 * @property _allFormElements
	 * @type Array
	 * @private
	 */
	_allFormElements: null,
	
	
	/**
	 * The total form elements to loop.
	 *
	 * @property _totalFormElements
	 * @type Int
	 * @private
	 */
	_totalFormElements: 0,
	
	
	/**
	 * Handles all form submissions.
	 *
	 * @method submitForm
	 * @public
	 * @param {String} formId
	 */
	submitForm: function(formId)
	{
		this._submissionPossible = true;
		this._validationErrors = [];
		this._passedFields = {};
		
		this._allFormElements = $("#" + formId).find("input, textarea");
		this._totalFormElements = this._allFormElements.length;
		
		Utils.debugConsole("this._totalFormElements: ", this._totalFormElements);
		
		// Validation loop.
		for(var i = 0; i < this._totalFormElements; i++)
		{
			var elementHandle = this._allFormElements[i];
			var elementType   = $(elementHandle).attr("type");
			var fieldName     = $(elementHandle).prev().html();
			var methodName    = '_check' + Utils.capitaliseFirstLetter(elementType);
			
			// Each field type can have it's own validation..
			if(typeof this[methodName] === "function")
			{
				var elementValid = this[methodName](elementHandle);
				
				if(elementValid === false && $(elementHandle).hasClass("required"))
				{
					Utils.debugConsole("invalid field: " + fieldName);
					this._submissionPossible = false;
					this._validationErrors[this._validationErrors.length] = fieldName + " - requires a valid " + fieldName.toLowerCase() + "!";
					continue;
				}
				
				Utils.debugConsole("valid field: " + fieldName);
				
				// Store this element and it's value if passed.
				this._passedFields[fieldName] = elementValid;
			}
		}
		
		if(this._submissionPossible === true)
		{
			this._processSubmission();
		}
		else
		{
			this._processSubmissionFailure();
		}
	},
	
	
	/**
	 * Handles successful submissions.
	 *
	 * @method _processSubmission
	 * @private
	 */
	_processSubmission: function()
	{
		Utils.debugConsole("processing form submission");
		
		Utils.toggleActivityIndicator();
			
		var paramsObject = {
			ajax: 1
		};
		
		// Get a request string ready.
		for(var fieldName in this._passedFields)
		{
			var key = fieldName.toLowerCase();
			var val = escape(this._passedFields[fieldName]);
			
			paramsObject[key] = val;
		}
		
		var that 	   = this;
		var requestUrl = Utils.buildRequestUrl(paramsObject);
		
		Utils.debugConsole("sending form data: ", paramsObject);
		
		// Make the call to send the email.
		Utils.makeRequest(requestUrl, function(response)
		{	
			if(response)
			{
				new Boxy("<p>" + response.message + "</p>",
				{
					title: response.title
				});
				
				that._clearContactFormFields();
				
				if(!Modernizr.input.placeholder)
				{
					$("#contactForm label").css(
					{
						"line-height": "24px"
					});
				}
			}
			
			Utils.toggleActivityIndicator();
		});
	},
	
	
	/**
	 * Handles unsuccessful submissions.
	 *
	 * @method _processSubmissionFailure
	 * @private
	 */
	_processSubmissionFailure: function()
	{
		var errorList = "";
		var totalErrors = this._validationErrors.length;
		
		// Generate the error HTML list.
		for(var i = 0; i < totalErrors; i++)
		{
			if(this._validationErrors[i] != "")
			{
				errorList += "<li>" + this._validationErrors[i] + "</li>";
			}
		}
		
		new Boxy("<div id='contactValidationErrors'><ul>" + errorList + "</ul><div>",
		{
			title: "There has been a problem!"
		});
	},
	
	
	/**
	 * Prepare the contact form.
	 *
	 * @method prepareContactForm
	 * @public
	 */
	prepareContactForm: function()
	{
		this._clearContactFormFields();
	},
	
	
	/**
	 * Clear all form fields.
	 *
	 * @method _clearContactFormFields
	 * @private
	 */
	_clearContactFormFields: function()
	{
		$("#contactForm input, #contactForm textarea").each(function()
		{
			if($(this).attr("id") !== "submit")
			{
				$(this).val("");
			}
		});
	},
	
	
	/**
	 * Text area validation.
	 *
	 * @method _checkTextarea
	 * @private
	 * @param {Object} textareaHandle
	 */
	_checkTextarea: function(textareaHandle)
	{
		var valid = false;
		
		if($(textareaHandle).val() !== "")
		{
			valid = $(textareaHandle).val();
		}
		
		return valid;
	},
	
	
	/**
	 * Text box validation.
	 *
	 * @method _checkText
	 * @private
	 * @param {Object} textHandle
	 */
	_checkText: function(textHandle)
	{
		var valid = false;
		var emailRegex = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
		var value = $(textHandle).val();
		
		if(value !== "")
		{
			if(($(textHandle).attr("id") === "email" && value.match(emailRegex) !== null) || $(textHandle).attr("id") !== "email")
			{
				valid = value;
			}
		}
		
		return valid;
	},
	
	
	/**
	 * Email box validation.
	 *
	 * @method _checkEmail
	 * @private
	 * @param {Object} emailHandle
	 */
	_checkEmail: function(emailHandle)
	{
		var valid = false;
		var emailRegex = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
		var value = $(emailHandle).val();
		
		if(value !== "")
		{
			if(($(emailHandle).attr("id") === "email" && value.match(emailRegex) !== null) || $(emailHandle).attr("id") !== "email")
			{
				valid = value;
			}
		}
		
		return valid;
	}
};
