/*
GreenJack v1.0.1 - Expression Engine FreeForm with AJAX
by Mark Cianciulli of Greenhouse Studio - Jacksonville, Florida

Copyright 2009 Greenhouse Studio

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
	
Read all about this script and check for updates here:
http://www.gogreenhouse.com/software/greenjack

Send us any modifications you do to the script, so we can add it to the base code.

- Requires Expression Engine - http://expressionengine.com
- Requires the FreeForm module for EE - http://www.solspace.com/software/detail/freeform/
- Requires on JQuery Min : http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
- Requires on JQuery Form : http://jquery.malsup.com/form/jquery.form.js
*/

// Settings
var _createHiddenDiv = true;						// If set to false, you will need to add this to your template
var _redirectToThankYouTemplate = false;				// if you want to redirect to a thank you template path to redirect to
var _toggleThankYouDiv = true;						// set to true, the form will be replaced by the thank you message
var _thankYouTemplatePath = '/software/thankyou';			// if _redirectToThankYou is set to true - thank you template path to redirect to
var _thankYouDiv = 'thankyouhidden';					// Div to display thank you message
var _formDiv = 'demoform';						// Div containing the form
var _UseFormIDs = false;						// if true, the form_id attr needs to be added to the exp:freeform:form. False for just one from per page
var _formID = 'contact-form'; 						// this is the ID of the freeform :: add attribute form_id="" to the exp:freeform:form
var _showErrorMessages = true;						// Show error messages generated by FreeForm
var _showErrorFormClass = true;						// Changes class on field to show an error
var _showErrorLabels = true;						// Changes class on label to show an error
var _errorClass = 'error'; 						// css class to show the form field had an error
var _errorLabelClass = 'errorlabel'; 					// css class to show the form field had an error
var _onSubmitMessage = 'Sending...';
var _validateField = 'rel';						// this is the customer attribute added to the form fields that is required
var _labelPrefix = 'label_'; 						// this is the id of the element to display the error message for that field
var _fieldErrorMessagePrefix = 'error_'; 				// this is the id of the element to display the error message for that field
var _hiddenDivWithFFErrors = 'ffajaxreturn';				// this is the hidden div that the ajax call will load the FreeForm errors into


$(document).ready(function(){
	// Create Array Of Required Fields
	var _formFieldsRequired = new Array();
	// Store Submit Button Value;
	var _submitButtonValueOrg = $('input[type=submit]').val();
	// Create Hidden Div for FreeForm Error Messages
	if (_createHiddenDiv) $('body').append('<div id="'+_hiddenDivWithFFErrors+'" style="display:none;"></div>');
	// Get required fields - build array		
	$(':input['+ _validateField +']').each(function(i) {
		_formFieldsRequired[i] = $(this).attr(_validateField);
	});		
	// Submit form
	if (_UseFormIDs) {_theFormIs='#'+_formID} else {_theFormIs='form'}
	$(_theFormIs).ajaxForm({  
		target: '#'+_hiddenDivWithFFErrors, 
		beforeSubmit:function() {			
			$(':input['+ _validateField +']').each(function(i) {
				$(this).removeClass(_errorClass);
				_field = $(this).attr(_validateField);
				$('#' + _labelPrefix + _field).removeClass(_errorLabelClass);
				$('#' + _fieldErrorMessagePrefix + _field).empty();
				// Disable Submit Button
				$('input[type=submit]').attr('disabled', 'disabled').val(_onSubmitMessage);
			});	
	},
	success:function(response) {
		if (response=="success") {
			$(_theFormIs).resetForm();
			if (_redirectToThankYouTemplate) {
				window.location = _thankYouTemplatePath;
			} else {
				if (_toggleThankYouDiv) {
					$('#'+_thankYouDiv).load(_thankYouTemplatePath,
						function () {
							$('#'+_formDiv).fadeOut('slow',
								function () {
									$('#'+_thankYouDiv).fadeIn('slow');
						}); 
					}); 
				} else {
					$('#'+_thankYouDiv).load(_thankYouTemplatePath);
					$('#'+_thankYouDiv).css({'display' : 'inline'});
				}
				
				
			}
			
		} else {
			// Loop through required fields
			$(_formFieldsRequired).each(function(e) {			
				// Set Field Checking
				var _check = _formFieldsRequired[e];
				var myRegExp = new RegExp(_check, 'gi');
				// Loop through error list from freeform
				$('#'+_hiddenDivWithFFErrors+' #content ul li').each(function(i) {
					// Compare Field to Error Message
					// 2009.12.11 : [FIX] the fix : added .replace(/ /g,'_') to $(this).html() to replace spaces with underscores so it can validate on multiple word labels				
					if ( $(this).html().replace(/ /g,'_').search(myRegExp) > 0 ) {
						// Show Errors on Form
						_errormessage = $(this).html();
						if (_showErrorFormClass) $('input[name='+_check+']').addClass(_errorClass).fadeIn('slow');
						if (_showErrorMessages) $('#' + _fieldErrorMessagePrefix + _check).html(_errormessage).fadeIn('slow');
						if (_showErrorLabels) $('#' + _labelPrefix + _check).addClass(_errorLabelClass).fadeIn('slow');
						return false;
					} 
				});
			});
			// Enable Submit Button
			$('input[type=submit]').attr('disabled', '').val(_submitButtonValueOrg);
			// Clear the hidden div
			$('#'+_hiddenDivWithFFErrors).empty();		
		}		
	  }
	});
});
