/*-----------------------------------------------------------------------------------------------
form validation
Author: VisualBlaze
Client: Hoaglin Companies
Descrip: contact form w/ajax submission [js enabled browsers only -> non js fallback to FS]
!! -> be sure to add classs="m" to ALL mandatory fields
-------------------------------------------------------------------------------------------------*/

function formSubmit(formObj) {
	jQuery(document).ready(function() {
		//html for feedback  container that is appended
		var feedbackHTML = "<div class=\"formFeedback\"></div>";
		var nullAllowList = new Array(); //array of elements that are allowed to be null -> data gathered from rel="m"(m=mandatory)
		var errorList = new Array(); //array of elements that fail validate test and not in nullAllowList
		var nullAllow = true; //variable for determining error element in nullAllow loop
	
		//get all input fields of type text
		var formFields = $(formObj).find("input:text");
		
		//loop to assign clearField function to elements + add non-required elements to nullAllowList
		jQuery.each(formFields, function() {
			//check if element has class=m [mandatory field]-> if false add element to nullAllowList
			if(!$(this).is("."+"m")) {
            	nullAllowList.push($(this));
            }
		});
		
		//loop through inputs to check for validity and add error class if not complete
		jQuery.each(formFields, function() {
			if($(this).attr("value") == "" || $(this).attr("value") == "Required" || $(this).attr("value") == $(this)[0].defaultValue) {
				//current loop element has no value so loop through nullAllowList to see if its allowed null
				for(x=0;x<= (nullAllowList.length -1);x++){
					if($(this).attr("id") == $(nullAllowList[x]).attr("id")) {
						//this input is on the nullAllowList so break loop and set nullAllow to true
						nullAllow = true;
						break;	//bomb out of loop as no need to do further checks
						//alert("elementNullAllow: "+$(this).attr("id"));
					}else{
						//this element is null and not on nullAllowList so fail it
						nullAllow = false;
						//alert("this field is NOT allowed to be null: "+$(this).attr("id")+" "+$(nullAllowList[x]).attr("id"));
					}
				}
				//assign error based attr if input fails null test
				if(!nullAllow) {
					$(this).addClass("error");
					$(this).attr("value", "Required");
					//assign this element to the array holding elements that failed validation
					errorList.push($(this));
				}
			}
		});
		//alert("errorList "+errorList.length);
		
		if(errorList.length == 0) { //no elements in error list means no elements errored out [were null]
			//alert("inside ajax");
			//append feedback
			changeForm($(formObj),"sending",feedbackHTML,'<h3>Sending...</h3><p>Your information is being sent.</p>');
			
			//form data
			var formData = $(formObj).serialize();
			//formType->check which form this is and send to correct handler
			var handlerPath = $(formObj).find("input[name=themePath]").attr("value")+"/formHandler.php";
			
			//ajax to post data to handler
			$.ajax({
				type: "POST",
				url: handlerPath,
				data: formData,
				success: function(html){
					//show success message
					if(html == "Information Sent!") {
						changeForm($(formObj),"sent",feedbackHTML,'<h3>Form Sent!</h3><p>Your information has been sent.</p>');
					}else{
	
						changeForm($(formObj),"error",feedbackHTML,'<h3>Form Error</h3><p>'+html+'</p>');
					}	
					//hide box, reset field in reset function
					//use 'closure' to get to work properly
					setTimeout(function(){resetForm(formObj); parameter = null},4000);
				}
			});
		}else{
			//errors in form so do nothing->error fields are marked from .each loop above
			changeForm($(formObj),"error",feedbackHTML,'<h3>Form Issue</h3><p>Please correct the fields marked red </p><p><a href="">< back to form</a></p>');
			setTimeout(function(){errorReset(formObj); parameter = null},4000);//move back to form from error
		}
	});
	//stop from moving to handler
	return false;
}

//moves back to form post error msg
function errorReset(formObj) {
	jQuery(document).ready(function() {
		$(formObj).removeAttr('class');
		$('.formFeedback').remove();
		//show form
		$(formObj).find('#formFields').css("display","block");
	});
}

//used for [error/sending/sent] form message showing
function changeForm(formObj,type,feedbackHTML,msgString) {
	jQuery(document).ready(function() {
		$('.formFeedback').remove();//reset feedbackHTML if already on page
		$(formObj).removeAttr('class');
		$(formObj).find('#formFields').css("display","none");//hide form
		$(formObj).append(feedbackHTML);//show error message
		$(formObj).addClass(type); //type of form change [error/sending/sent]
		$('.formFeedback').append(msgString);//message to be used
		
		//add reset link click if this is error case
		var resetLink = $('.formFeedback a');
		if(resetLink) {
			//set href to javascript:void(0);
			$(resetLink).attr('href', 'javascript:void(0);');
			$(resetLink).bind('click',function(){
			    errorReset($(formObj));
			    return false;
			 });
		}
	});	
}


function resetForm(formObj) {
	jQuery(document).ready(function() {
		//re-declare formFields variable [separate function can read submits var]
		var formFields = $(formObj).find("input:text");
		var textareas = $(formObj).find("textarea");
		
		//reset all input values
		jQuery.each(formFields, function() {
			$(this).attr("value","");
			if($(this).hasClass('error')){
				$(this).removeClass('error');
			}
		});
		jQuery.each(textareas, function() {
			$(this).attr("value","");
		});
		
		//remove html for feedback div
		$('.formFeedback').remove();
		
		//remove form classes controlling bg images
		$(formObj).removeAttr('class');
		
		//show form
		$(formObj).find('#formFields').css("display","block");
	});
}

