/*	Author:		Daniel C. Richmond
	File:		validate.js
	Purpose:	form validation
*/
function makeAlert(msg, warning) {
	// creates the popup alert above the text boxes
	var _class = "alert";
	if (warning) {
		// if it's just a warning (in picky mode), also use this class
		// makes grey box rather than red
		_class += " warning";
	}
	// create html to return and inject
	var html = "";
	html += "<div class = \"" + _class + "\">";
	html += msg;
	html += "</div>";
	return html;
}
function kill() {
	// removes element
	$(this).remove();
}		

$(document).ready(
	function() {
		if ( $("#companyType").length > 0 ) {
			if ( $("#companyType").val() == "Other" ) {
				$("#companyType2")
					.addClass("req")
					.parent().parent().show();
			} else {
				$("#companyType2")
					.removeClass("req")
					.parent().parent().hide();
			}	
			$("#companyType").change (
				function ( e ) {
					if ( $(this).val() == "Other" ) {
						$("#companyType2")
							.val("")
							.addClass("req")
							.parent().parent().show();
					} else {
						$("#companyType2")
							.val("")
							.removeClass("req")
							.parent().parent().hide();
					}
				}
			);
		}
		if ( $("#textMsg").length > 0 ) {
			$("#textMsg").change (
				function ( e ) {
					if ( $(e.target).attr("checked") ) {
						$( "#mobile" )
							.addClass( "req" )
							.parent()
							.parent()
							.find( "label" )
							.prepend("<em class = 'imp'>* </em>");
					} else {
						$( "#mobile" )
							.removeClass( "req" )
							.parent()
							.parent()
							.find( "em, .alert" )
							.remove();
					}
				}
			);
		}
		// on validated form submission...
		var myForm = $("form.validate");
		myForm.submit(
			function submit( e ) {
				var isOffers	= ($(this).attr("name") == "offers_form");
				//return false;
				// define fail counts and whether or not to validate non-required typed fields
				var fails	= 0;
				var picky	= $(this).hasClass("picky");
				//
				function matchesMatch() {
					// console.log("testing match in... " + this);
					// checks to see if all "match" classed items are identical
					// returns true/false
					var returner = true;
					var lastValue = "";
					$(".match").each(
						function () {
							// console.log(lastValue);
							if ($(this).val().toUpperCase() != lastValue && lastValue != "") {
								returner = false;
							}
							lastValue = $(this).val().toUpperCase();
							// console.log(lastValue);
						}
					)
					return returner;
				}
				
				if( $( "form" ).attr( "id" ) == "rate-and-comment" ) {
					
				}
				
				
				//
				// for all items to be validated
				// radioCorrect( true );
				if( $( this ).find( "input[type=radio].req" ).length ) {
					var radioGroups		= new Object();
					var indexString		= "";
					$( this ).find( "input[type=radio].req" ).each( function() {
						if( $( this ).attr( "name" ) != indexString ) {
							indexString = $( this ).attr( "name" );
							radioGroups[ indexString ]		= new Array();
						}
						radioGroups[ indexString ].push( $( this ) );
					} );
					
					for( i in radioGroups ) {
						var firstElem			= radioGroups[ i ][ 0 ];
						if( $( "form" ).find( "input[name=" + firstElem.attr( "name" ) + "]:checked").val() || $( "#rate-and-comment #comments" ).val() != "" ) {
							// selected, remove warning
							firstElem
								.parent()
								.find( "div[rel=" + firstElem.attr( "name" ) + "]" )
								.slideUp(250, kill);
							if( $( "#rate-and-comment #comments" ).length ) {
								$( "#rate-and-comment #comments" ).removeClass( "req" );
							}
						} else if( $( "#rate-and-comment #comments" ).val() == "" ) {
							
							if ( firstElem.parent().find( "div[rel=" + firstElem.attr( "name" ) + "]" ).length <= 0 ){
								// not selected, warn
								$( "<div class = \"radio-alert\" rel = \"" + firstElem.attr( "name" ) + "\">This is a required field.</div>" ).insertBefore( firstElem );
								$( "div[rel=" + firstElem.attr( "name" ) + "].radio-alert" ).slideDown(250);
								fails++;
							} else {
								fails++;
							}
							
							if( $( "#rate-and-comment #comments" ).length ) {
								$( "#rate-and-comment #comments" ).addClass( "req" );
							}
						
						}
					};
				}
				
				
				$(this).find("input, textarea, select").each(
					function() {
						// define some basics
						var isSubmit	= ($(this).attr("type") == "submit");
						var isSelect	= (this.nodeName == "SELECT");
						var isHidden	= ($(this).attr("type") == "hidden");
						var isRadio		= ( $( this ).attr( "type" ) == "radio" );
						
						var match		= $(this).hasClass("match");
						var email		= $(this).hasClass("email");
						var zip			= $(this).hasClass("zip");
						var phone		= $(this).hasClass("phone");
						var req			= $(this).hasClass("req");
						var message 	= "";
						var toggle		= $( this ).hasClass( "toggle" );
						var myVal		= $(this).val().toUpperCase();
						var warning		= false;
						//
						
						if(!isHidden) {
							// if a user left a required field blank...
							if (req && myVal == "") {
								// create error message
								message = "This is a required field.";
							}
							
							// if the user entered something into an "email" field...
							if (email && myVal != "") {
								// this field should be an email
								// check for @ and .
								$regEx = /^.+?@.+?\./g;
								if(!myVal.match($regEx)) {
									// not a valid email address
									// if this field IS NOT required, set warning to TRUE
									req ? null : warning = true;
									// create message
									message = "Invalid email address.";
								}
							}						
							
							// if a user entered something into a "phone" field...
							if (phone && myVal != "") {
								// this field should only contain numbers, (), and -
								$regEx = /^([1]{0,1})([-. ]{0,1})(([(]{1})([0-9]{3})([)]{1})|([(]{0})([0-9]{3})([)]{0}))([-. ]{0,1})([0-9]{3})([-. ]{0,1})([0-9]{4})$/g;
								if(!myVal.match($regEx)) {
									// not a valid email address
									// if this field IS NOT required, set warning to TRUE
									req ? null : warning = true;
									// create message
									message = "Invalid phone number.";
								}
							}
							
							// if a user entered something into a "zip" field...
							if (zip && myVal != "") {
								// this field should only contain numbers, (), and -
								$regEx = /^\d{5}$/g;
								if(!myVal.match($regEx)) {
									// not a valid email address
									// if this field IS NOT required, set warning to TRUE
									req ? null : warning = true;
									// create message
									message = "Invalid zip code.";
								}
							}
							
							// if there are confirmation (should-be matching) fields AND the fields DO NOT match...
							if (match && !matchesMatch()) {
								// create message
								message = "Entries must match.";
							}
							
							if( req && isSelect && ( myVal == "" || myVal == "-1" ) ) {
								message = "This is a required field.";
							}
							
							// if message is defined...
							if (message != "" && ( !isSubmit || isRadio ) ) {
								// if the validator is picky or the field is required, increment main fail counter
								(picky || req) ? fails++ : null;
								// if an alert DIV exists...
								if( isRadio ) {
									// radio -- ignore
								} else if( isSelect) {
									if ($(this).parent().find("div.alert").length) {
										// ... set its message to the new error message
										$(this).parent().find("div.alert").html(message);
									} else {
										// ... if not, create an alert DIV and make it slide into view
										$(this).parent().prepend(makeAlert(message, warning));
										$(this)
											.parent()
											.find("div.alert")
											.width( $( this ).width() - 6 )
											.slideDown(250);
									}
								} else {
									if ($(this).parent().find("div.alert").length) {
										// ... set its message to the new error message
										$(this).parent().find("div.alert").html(message);
									} else {
										// ... if not, create an alert DIV and make it slide into view
										$(this).parent().prepend(makeAlert(message, warning));
										$(this).parent().find("div.alert").slideDown(250);
									}
								}
							} else if (!isSubmit && !isRadio) {
								// ... if not, slide it out of view and remove it
								
								$(this).parent().find("div.alert").slideUp(250, kill);
							}
						}
					}
				)
				//return false;
				// if errors have been reported...
				if (fails) {
					// ... deny default form submission functionality
					return false;
				}
				// if we arrive here, all is well -- submit form
				
				if (isOffers) {
					$("#companyTypeHidden").val(
						( $("#companyType").val() == "Other" ? "Other: " + $("#companyType2").val() : $("#companyType").val() )
					);
					$("#fullNameHidden").val(
						( $("#firstName").val() + ' ' + $("#lastName").val() )
					);
				}
				
				$( "form" ).blur();
				waitBox( "Please Wait...", true );
				return true;
			}
		);
	}
);
