/*
	Expression Engine FreeForm with AJAX - 1.1.1
	by Chris Barr of Eject Media
	- http;//chris-barr.com
	- http://ejectmedia.net
	
	Read all about this script and check for updates here:
	http://chris-barr.com/entry/ajax_forms_in_expression_engine_with_freeform/

	This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.
	You may use this for commercial purposes as long as you make the source code avalible and do not
	remove the comments that link back to my site.
	You may modify this script in any way you need.
	- http://creativecommons.org/licenses/by-sa/3.0/us

* Requires Expression Engine - http://expressionengine.com
* Requires the FreeForm module for EE - http://www.solspace.com/software/detail/freeform/
* Based on Mootools 1.11 - http://mootools.net/download
	Requires:
	 - Core
		-Core
	- Class
		- Class
		- Class.Extras
	-Native
		- Array
		- String
		- Function
		- Number
		- Element
	- Element
		- Element.Event
		- Element.Filters
		- Element.Selectors
		- Element.Form
	- Window
		- Window.DomReady
		- Window.Size
	- Effects
		- Fx.Base
		- Fx.CSS
		- Fx.Styles
		- Fx.Elements
		- Fx.Slide
	- Remote
		- XHR
		- Ajax
*/
var EEAjaxForm = {
	init:function(){
		/******************OPTIONS******************/
		//these are the names of the "Label" in FreeForm and the label element name for each input/textarea field
		//for fields that must be validated (such as email), the third parameter must be set to true
		//All of these must be unique and they are case sensitive
		//FreeForm label names may not be contined in another label.
		//For example, if you have "Name" you cannot have "First Name"
		
		var inputs = [
			["Name","name_label", false],
			["Email","email_label", true],
			["Message","message_label", false]
			
			
						
			
		];
		var userResponse=true;//toggles the display of the div that displays messages from FreeForm.  You must create this element
		var userResponseID="user-response";//ID of the div that displays messages from FreeForm.  Only use if userResponse is true
		var containerID = "content"			//ID of the element that contains the form - the main container of the site
		var formID = "my_form"; 			//ID of the form
		var thankYouID="thankyou"; 		//ID of the div to show when the form has been sent
		var errorClass="error"; 				//Name of the class to use when displaying an error
		var overlayID="overlay";			//ID name of the element that dims the screen. (created by this script)
		var loadingID="ajax-loading";		//ID name of the element that show the loading animation. (created by this script)
		var responseID="ajax-response";//ID name of the element that gets the ajax responses loaded into it. (created by this script)
		var debug = false;						//set to true if you want to display messages in the console
		/********************************************/
		//set up sliders for when form succeeds
		var formSlider = new Fx.Slide(formID, {duration:600});
		var thanksSlider = new Fx.Slide(thankYouID, {duration:600}).hide();
		//create the loading elements
		new Element('div',{'id':overlayID}).injectBefore(containerID).setOpacity(0)
		new Element('div',{'id':loadingID}).injectBefore(containerID).setOpacity(0)
		new Element('div',{'id':responseID}).injectBefore(containerID);
		//set up to fade in loading screen
		var loadingFX = new Fx.Elements($$('#'+overlayID, '#'+loadingID), {wait:false, duration:100});
		//add click event to the form
		$(formID).addEvent('submit', function(e) {
			//stop the default browser behaviour of submitting the form
			new Event(e).stop();
			//IE6 can't do the CSS height property correctly, so lets fix this
			if(window.ie6){$(overlayID).setStyle('height',window.getHeight());}
			loadingFX.start({
				'0': {'opacity': 0.8},
				'1': {'opacity': 1}
			});
			this.send({
				update: responseID,
				onComplete: function() {
					//remove loader
					loadingFX.start({
						'0': {'opacity': 0},
						'1': {'opacity': 0}
					});
					//remove errors before checking for errors again
					$each(inputs, function(num,i){$(inputs[i][1]).removeClass(errorClass);});
					if(userResponse){$(userResponseID).empty();}
					if($(responseID).getText()=="success"){
						//clear all error classes
						$$(formID+' label').each(function(lbl){lbl.removeClass(errorClass);});
						//get rid of the userResponse element if you're using it
						if(userResponse){$(userResponseID).remove();}
						//hide the form and how thank you message afterwards
						formSlider.slideOut().chain(function(){thanksSlider.slideIn();});
						if(debug){console.log("AJAX returned: "+$(responseID).getText());}
					}else{
						//check fields if they returned errors
						$$("#"+responseID+" #content ul li").each(function(el,i){
							if(debug){console.log("("+i+") AJAX returned: "+el.getText());}
							if(userResponse){
								if(i==0){new Element('h3').injectInside(userResponseID).setHTML("Form Errors:");}
								new Element('div',{'class':errorClass}).injectInside(userResponseID).setHTML(el.getText());
							;}
							inputs.each(function(input,num){
								if(el.getText().contains(inputs[num][0])){
									//not filled in
									$(inputs[num][1]).addClass(errorClass);
									if(debug){console.log("("+num+") "+inputs[num][1]+" is not filled in!");}
								}else if(inputs[num][2] && el.getText().contains("not valid")){
									//not valid
									$(inputs[num][1]).addClass(errorClass);
									if(debug){console.log("("+num+") "+inputs[num][1]+" is not valid!");}
								}
							})
						});
						//clear out the ajax response div
						$(responseID).empty();
					}
				}
			});
		});
	}
}
window.addEvent('domready', EEAjaxForm.init.bind(EEAjaxForm));