/*

	ivFormValidator is an easy to use form validatior based on the jquery framework
	
	Author: Ingo Volkmann www.godiv.de
	
	set the variables at the top of the function according to your needs

	include this file in the head section of your website after the jquery include
		<script type="text/javascript" language="javascript" src="scripts/iv_form_validation.js"></script>
	
	the form you'll check needs the class="ivFormValidator"
	all fields you wanna check needs the class named like the requiredClassName variable in the top of the function
	to add options like compare or email syntax check, add the respective class names as a 2nd or 3rd class name of the input fields
	the script will add all needed event listeners, so all you need to do is to create the HTML markup
	
*/


function ivFormValidator () {
	
	// name of the class to identify the fields you'll get checked
	this.requiredClassName = 'required';
	
	// to check for a valid email syntax, the field must have a class name
	this.checkEmailSyntaxClassName = 'email';
	
	// to check the entry for a valid number (eg phone number) define the class name here - only numbers will be allowed - something like "000 / 000" will be invalid
	this.checkValidNumberClassName = 'number';
	
	// define the class name which will be the identifier to compare - the name here needs a suffix in the class attribute like this: compare_t - set the _t to all fields you'll check against each other - the t can also be an other character of your choise - if you wish to compare more than one group, choose a different suffix for each group
	this.compareClassName = 'compare';
	
	// the message the user will get, if one or more fields are not correctly filled out
	this.emptyErrorMessage = 'This field is required!';
	
	// the message the user will get, if compared fields are not equal
	this.compareErrorMessage = 'These entries does not match!';
	
	// the message the user will get, if checkbox is not checked
	this.checkboxErrorMessage = 'You need to check this field!';
	
	// the message the user will get, if none radio button is checked
	this.radioErrorMessage = 'You need to check one of these fields!';
	
	// the message the user will get, if the email syntax or the given value isn't a number 
	this.syntaxErrorMessage = 'The syntax of this entry is invalid!';
	
	// the message the user will get, if the value isn't a number 
	this.numberErrorMessage = 'This value must be a number!';
	
	// define custom error message colors
	this.emptyColor = '#CC0000';			// if the input field is emtpy
	this.compareColor = '#CC6600';			// if the entries does not match
	this.checkboxRadioColor = '#CC0000';	// if the checkbox or none of the radio buttons is checked
	this.emailSyntaxColor = '#990000';		// if the email syntax is invalid
	this.numberColor = '#996666';			// if the entry is not a number
	
	/* 
	
	DO NOT CHANGE ANYTHING BELOW THIS EXCEPT YOU REALLY KNOW WHAT YOU ARE DOING 
		
	*/
	
	// init validator
	this.ivInitFormValidator = function () {
		$('body').append('<style type="text/css">.ivFVerrorEmpty { color:' + this.emptyColor + '; } .ivFVerrorMatch { color:' + this.compareColor + '; } .ivFVerrorCheck { color:' + this.checkboxRadioColor + '; } .ivFVerrorSyntax { color:' + this.emailSyntaxColor + '; } .ivFVerrorNumber { color:' + this.numberColor + '; }</style>');
		$(".ivFormValidator").submit(function(){ 
			return objIvFormValidator.ivFVvalidate(this); 
		});	
	}
	
	// validate
	this.ivFVvalidate = function (form) {
		// set id
		if ($(form).attr('id') == '' || $(form).attr('id') == undefined) {
			var now = new Date();
			var timestamp = now.getTime();
			$(form).attr('id', 'f_' + timestamp);
		}
		
		// clear former validation
		$("#" + $(form).attr('id') + " div").remove(".ivFVerrorEmpty");
		$("#" + $(form).attr('id') + " div").remove(".ivFVerrorMatch");
		$("#" + $(form).attr('id') + " div").remove(".ivFVerrorCheck");
		$("#" + $(form).attr('id') + " div").remove(".ivFVerrorSyntax");
		$("#" + $(form).attr('id') + " div").remove(".ivFVerrorNumber");
		$("#" + $(form).attr('id') + " ." + objIvFormValidator.requiredClassName).removeClass(".ivFVfocus");
		
		var boolReturn = true;
		var arrCompareGroups = new Array();
		var arrRadioGroups = new Array();
		
		$("#" + $(form).attr('id') + " ." + objIvFormValidator.requiredClassName).each(function(i) {
			// empty
			if ($.trim($(this).val()) == '') {
				$(this).before('<div class="ivFVerrorEmpty">' + objIvFormValidator.emptyErrorMessage + '</div>');
				$(this).addClass('ivFVfocus');
				boolReturn = false;
			}
			// compare
			if ($(this).attr('class').indexOf(objIvFormValidator.compareClassName) != -1) {
				var arrClasses = $(this).attr('class').split(' ');
				for (var a = 0; a < arrClasses.length; a++) {
					if (arrClasses[a].indexOf(objIvFormValidator.compareClassName) != -1) {
						var group = objIvFormValidator.strReplace(objIvFormValidator.compareClassName, '', arrClasses[a]);
						if (!objIvFormValidator.inArray(arrCompareGroups, group)) {
							void arrCompareGroups.push(group);
						}
					}
				}
			}
			// email
			if ($(this).attr('class').indexOf(objIvFormValidator.checkEmailSyntaxClassName) != -1) {
				var strReg = "^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$";
				var regex = new RegExp(strReg);
				if (!regex.test($(this).val())) {
					$(this).before('<div class="ivFVerrorSyntax">' + objIvFormValidator.syntaxErrorMessage + '</div>');
					$(this).addClass('ivFVfocus');
					boolReturn = false;
				}
			}
			// number
			if ($(this).attr('class').indexOf(objIvFormValidator.checkValidNumberClassName) != -1) {
				if ($.trim($(this).val()) == '' || isNaN($(this).val())) {
					$(this).before('<div class="ivFVerrorNumber">' + objIvFormValidator.numberErrorMessage + '</div>');
					$(this).addClass('ivFVfocus');
					boolReturn = false;
				}
			}
			// checkboxes
			if ($(this).attr('type').toLowerCase() == 'checkbox' && !$(this).attr('checked')) {
				$(this).before('<div class="ivFVerrorCheck">' + objIvFormValidator.checkboxErrorMessage + '</div>');
				$(this).addClass('ivFVfocus');
				boolReturn = false;
			}
			// radio
			if ($(this).attr('type').toLowerCase() == 'radio') {
				var group = $(this).attr('name');
				$(this).addClass('ivFVradio_' + group);
				if (!objIvFormValidator.inArray(arrRadioGroups, group)) {
					void arrRadioGroups.push(group);
				}
			}
		});
		
		// compare
		var arrCompareGroupsResults = new Array();
		
		for (var a = 0; a < arrCompareGroups.length; a++) {
			var arrCompareElements = new Array();
			arrCompareGroupsResults[arrCompareGroups[a]] = true;
			$("#" + $(form).attr('id') + " ." + objIvFormValidator.compareClassName + arrCompareGroups[a]).each(function(i) {
				void arrCompareElements.push($(this).val());
			});
			$("#" + $(form).attr('id') + " ." + objIvFormValidator.compareClassName + arrCompareGroups[a]).each(function(i) {
				for (var b = 0; b < arrCompareElements.length; b++) {
					if ($(this).val() != arrCompareElements[b]) {
						arrCompareGroupsResults[arrCompareGroups[a]] = false;
					}
				}
			});
		}
		
		for (var i in arrCompareGroupsResults) {
			if (!arrCompareGroupsResults[i]) {
				$("#" + $(form).attr('id') + " ." + objIvFormValidator.compareClassName + i).each(function(i) {
					$(this).before('<div class="ivFVerrorMatch">' + objIvFormValidator.compareErrorMessage + '</div>');
					$(this).addClass('ivFVfocus');
					boolReturn = false;
				});
			}
		}
		
		// radio
		var arrRadioGroupsResults = new Array();
		
		for (var a = 0; a < arrRadioGroups.length; a++) {
			arrRadioGroupsResults[arrRadioGroups[a]] = false;
			$("#" + $(form).attr('id') + " ." + 'ivFVradio_' + arrRadioGroups[a]).each(function(i) {
				if ($(this).attr('checked')) {
					arrRadioGroupsResults[arrRadioGroups[a]] = true;
				}
			});
		}
		
		for (var i in arrRadioGroupsResults) {
			if (!arrRadioGroupsResults[i]) {
				$("#" + $(form).attr('id') + " ." + 'ivFVradio_' + i).each(function(i) {
					$(this).before('<div class="ivFVerrorMatch">' + objIvFormValidator.radioErrorMessage + '</div>');
					$(this).addClass('ivFVfocus');
					boolReturn = false;
				});
			}
		}
		
		// focus
		var boolFirstElement = false;

		$("#" + $(form).attr('id') + " ." + objIvFormValidator.requiredClassName).each(function(i) {
			if ($(this).attr('class').indexOf('ivFVfocus') != -1 && !boolFirstElement) {
				boolFirstElement = true;
				this.focus();
				var scrollTop = $(document).scrollTop();
				$(document).scrollTop(scrollTop-50);
			}
		});
		
		return boolReturn;
		
	}
	
	// str_replace
	this.strReplace = function (search, replace, subject) {
		return subject.split(search).join(replace);
	}

	// in_array
	this.inArray = function (array, value) {
		for( var i=0; i < array.length; i++ )
			if( array[i] == value )
				return true;
		return false;
	}
	
}

// init object
var objIvFormValidator = new ivFormValidator();

// load validator
$(document).ready(function(){
	
	window.setTimeout("objIvFormValidator.ivInitFormValidator();", 200);
	
});


