/*
GreenJack v1.0 - 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 _redirectToThankYouTemplatec = false;				// if you want to redirect to a thank you template path to redirect to
var _toggleThankYouDivc = false;						// set to true, the form will be replaced by the thank you message

var _thankYouTemplatePathc = '/chat/thankyou';			// if _redirectToThankYou is set to true - thank you template path to redirect to
var _thankYouDivc = 'thankyouhidden';					// Div to display thank you message

var _formDivc = 'contactform';						// Div containing the form

var _UseFormIDsc = true;						// if true, the form_id attr needs to be added to the exp:freeform:form. False for just one from per page

var _formIDc = 'comment_form'; 						// this is the ID of the freeform :: add attribute form_id="" to the exp:freeform:form


var _showErrorMessagesc = true;						// Show error messages generated by FreeForm
var _showErrorFormClassc = true;						// Changes class on field to show an error
var _showErrorLabelsc = false;						// Changes class on label to show an error
var _errorClassc = 'error'; 						// css class to show the form field had an error
var _errorLabelClassc = 'errorlabel'; 					// css class to show the form field had an error
var _onSubmitMessagec = 'SUBMITTING';
var _validateFieldc = 'rel';						// this is the customer attribute added to the form fields that is required
var _labelPrefixc = 'floatin'; 						// this is the id of the element to display the error message for that field
var _fieldErrorMessagePrefixc = 'error_'; 				// this is the id of the element to display the error message for that field
var _hiddenDivWithFFErrorsc = 'ffajaxreturn';				// this is the hidden div that the ajax call will load the FreeForm errors into

var _defaultErrorMessage = 'Oops, you missed something!';


$(document).ready(function(){
	// Create Array Of Required Fields
	var _formFieldsRequiredc = new Array();
	// Store Submit Button Value;
	var _submitButtonValueOrgc = $('input[type=submit]').val();
	
	
	// Create Hidden Div for FreeForm Error Messages
	//if (_createHiddenDiv) $('body').append('<div id="'+_hiddenDivWithFFErrorsc+'" style="display:none;"></div>');
	// Get required fields - build array		
	$(':input['+ _validateFieldc +']').each(function(i) {
		_formFieldsRequiredc[i] = $(this).attr(_validateFieldc);
	});		
	// Submit form
	if (_UseFormIDsc) {_theFormIs='#'+_formIDc} else {_theFormIs='form'}

	
	$(_theFormIs).ajaxForm({  
		target: '#'+_hiddenDivWithFFErrorsc, 
		beforeSubmit:function() {		
			$('#errormessage').css({"display":"none"});	
			$('#hiddennamefield').text($('input[name=name]').val());

			$(':input['+ _validateFieldc +']').each(function(i) {
				$('#errormessage').text(_defaultErrorMessage);
				$(this).removeClass(_errorClassc);
				_field = $(this).attr(_validateFieldc);
				$('#' + _labelPrefixc + _field).removeClass(_errorLabelClassc);
				$('#' + _fieldErrorMessagePrefixc + _field).empty();
				// Disable Submit Button
				
				$('input[type=submit]').attr('disabled', 'disabled').val(_onSubmitMessagec);
				
			});	
			
			// stop submit if no comment is there
			if ($('#comment').val()=='') {
				$('input[type=submit]').attr('disabled', '').val(_submitButtonValueOrgc);
				$('#errormessage').text('You forgot to add a comment!');
				$('#errormessage').fadeIn('slow');
				return false;
			}
	},
	success:function(response) {
		if (response=="success") {
			
			if (_redirectToThankYouTemplatec) {
				window.location = _thankYouTemplatePathc;
			} else {
				if (_toggleThankYouDivc) {
					$('#'+_thankYouDivc).load(_thankYouTemplatePathc,
						function () {
							$('#'+_formDivc).html('');
							$('#contactdear').text('dear '+ $('#hiddennamefield').text());
							$('#contacthearfrom').text('glad to hear from you :)');
							$('#'+_formDivc).html($('#'+_thankYouDivc).fadeIn(800));
					}); 
				} else {
					
					$('#cptext').html($('textarea#comment').val());
					$('#cpreview').text('Your comment is awaiting approval');
					$('#closecpcontainer').text($('input[type=name]').val());
					
					$('#addtothis').css({"display":"none"});

					$('#commentformcontainer').fadeOut('slow', function() {
						$('#commentpreviewcontainer').fadeIn(800);
					});
					
				}
				$(_theFormIs).resetForm();
			}
		} else {
			// Loop through required fields
			$(_formFieldsRequiredc).each(function(e) {			
				// Set Field Checking
				var _check = _formFieldsRequiredc[e];
				var myRegExpc = new RegExp(_check, 'gi');

				// Loop through error list from freeform
				$('#ffajaxreturn #content ul li').each(function(i) {
				
					// Compare Field to Error Message
					if ( $(this).html().replace(/ /g,'_').search(myRegExpc) > 0 ) {
						
						// Show Errors on Form
						_errormessagec = $(this).html();
								
						if (_check=='word') {
							$('input[name=captcha]').addClass(_errorClassc).fadeIn('slow');
						} else {
							$('input[name='+_check+']').addClass(_errorClassc).fadeIn('slow');
						}
						
						if (_showErrorMessagesc) $('#' + _fieldErrorMessagePrefixc + _check).html(_errormessagec).fadeIn('slow');
						return false;
					} 
					$('#errormessage').fadeIn('slow');
				});
			});
			// Enable Submit Button
			$('input[type=submit]').attr('disabled', '').val(_submitButtonValueOrgc);
			// Clear the hidden div
			$('#'+_hiddenDivWithFFErrorsc).empty();		
		}		
	  }
	});
});
