/*
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 _createHiddenDiv2 = true;						// If set to false, you will need to add this to your template
var _redirectToThankYouTemplate2 = false;				// if you want to redirect to a thank you template path to redirect to
var _toggleThankYouDiv2 = true;						// set to true, the form will be replaced by the thank you message
var _thankYouTemplatePath2 = '/embed/thankyou';			// if _redirectToThankYou is set to true - thank you template path to redirect to
var _thankYouDiv2 = 'thankyouhidden';					// Div to display thank you message
var _formDiv2 = 'formcontainer';						// Div containing the form
var _UseFormIDs2 = true;						// if true, the form_id attr needs to be added to the exp:freeform:form. False for just one from per page
var _formID2 = 'salesform'; 						// this is the ID of the freeform :: add attribute form_id="" to the exp:freeform:form
var _showErrorMessages2 = true;						// Show error messages generated by FreeForm
var _showErrorFormClass2 = false;						// Changes class on field to show an error
var _showErrorLabels2 = true;						// Changes class on label to show an error
var _errorClass2 = 'error'; 						// css class to show the form field had an error
var _errorLabelClass2 = 'errorlabel'; 					// css class to show the form field had an error
var _onSubmitMessage2 = 'Submitting';
var _validateField2 = 'rel';						// this is the customer attribute added to the form fields that is required
var _labelPrefix2 = 'label_'; 						// this is the id of the element to display the error message for that field
var _fieldErrorMessagePrefix2 = 'error_'; 				// this is the id of the element to display the error message for that field
var _hiddenDivWithFFErrors2 = '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 _formFieldsRequired2 = new Array();
	// Store Submit Button Value;
	var _submitButtonValueOrg2 = $('input[type=submit]').val();
	
	// Create Hidden Div for FreeForm Error Messages
	if (_createHiddenDiv2) $('body').append('<div id="'+_hiddenDivWithFFErrors2+'" style="display:none;"></div>');
	// Get required fields - build array		
	$(':input['+ _validateField2 +']').each(function(i) {
		_formFieldsRequired2[i] = $(this).attr(_validateField2);
	});		
	// Submit form
	if (_UseFormIDs2) {_theFormIs2='#'+_formID2} else {_theFormIs2='form'}
	$(_theFormIs2).ajaxForm({  
		target: '#'+_hiddenDivWithFFErrors2, 
		beforeSubmit:function() {			
			$(':input['+ _validateField2 +']').each(function(i) {
				$(this).removeClass(_errorClass2);
				_field2 = $(this).attr(_validateField2);
				$('#' + _labelPrefix2 + _field2).removeClass(_errorLabelClass2);
				$('#' + _fieldErrorMessagePrefix2 + _field2).empty();
				// Disable Submit Button
				
				$('input[type=submit]').attr('disabled', 'disabled').val(_onSubmitMessage2);
				
				
				//$('input[type=submit]').attr('disabled', 'disabled').addClass(_onSubmitMessage2)
			});	
	},
	success:function(response) {
		if (response=="success") {
		
			// do salesforce web-to-lead ::

			var _first_name = $("#first_name").val(); 
			var _last_name = $("#last_name").val(); 
			var _company = $("#company_name").val(); 
			var _email = $("#email").val(); 
			var _phone = $("#phone").val();
			if ($("#company_role").length) { var _role = $("#company_role").val(); } else { var _role = ''; }
			if ($("#employees").length) { 
				var _employees = $("#employees").val();
				if (_employees == '100-1000') {
					_employees = '100';
				}  else if (_employees == '1001-5000') {
					_employees = '1001';
				}  else if (_employees == '5001-10000') { 
					_employees = '5001';
				}
			} else { 
				var _employees = ''; 
			}
			if ($("#dateselect").length) { var _demotime = $("#dateselect").val(); } else { var _demotime = ''; }
			if ($("#customers").length) { var _customers = $("#customers").val(); } else { var _customers = ''; }
			var _description = $("#comments").val();
			if ($("#downloaded").length) { var _download = $("#downloaded").val(); } else { var _download = ''; }
			
			$.post("/embeds/gosalesforce", { 
					first_name:_first_name,
					last_name:_last_name,
					company:_company, 
					email:_email,
					phone:_phone, 
					role:_role, 
					employees:_employees, 
					demotime:_demotime,
					customers:_customers,
					description:_description,
					download:_download
				},
				function(data){
			
					$(_theFormIs2).resetForm();
					//if (_redirectToThankYouTemplate2) {
					//	window.location = _thankYouTemplatePath2;
					//} else {
					//	if (_toggleThankYouDiv2) {
					//		$('#'+_thankYouDiv2).load(_thankYouTemplatePath2,
					//			function () {
									$('#'+_formDiv2).html('');
									$('#'+_formDiv2).html($('#'+_thankYouDiv2).fadeIn(800));
						//	}); 
						//} else {
							//$('#'+_thankYouDiv2).load(_thankYouTemplatePath2);
							//$('#'+_thankYouDiv2).css({'display' : 'inline'});
						//}
					//}
					
			});		
		
			
			
		} else {
			// Loop through required fields
			$(_formFieldsRequired2).each(function(e) {			
				// Set Field Checking
				var _check2 = _formFieldsRequired2[e];
				var myRegExp2 = new RegExp(_check2, 'gi');
				// Loop through error list from freeform
				$('#'+_hiddenDivWithFFErrors2+' #content ul li').each(function(i) {
					// Compare Field to Error Message
					if ( $(this).html().replace(/ /g,'_').search(myRegExp2) > 0 ) {
						// Show Errors on Form
						_errormessage2 = $(this).html();
						if (_showErrorFormClass2) $('input[name='+_check+']').addClass(_errorClass2).fadeIn('slow');
						if (_showErrorMessages2) $('#' + _fieldErrorMessagePrefix2 + _check2).html(_errormessage2).fadeIn('slow');
						if (_showErrorLabels2) $('#' + _labelPrefix2 + _check2).addClass(_errorLabelClass2).fadeIn('slow');
						return false;
					} 
				});
			});
			// Enable Submit Button
			$('input[type=submit]').attr('disabled', '').val(_submitButtonValueOrg2);
			
			// Clear the hidden div
			$('#'+_hiddenDivWithFFErrors2).empty();		
		}		
	  }
	});
});

