$(document).ready( function() {

	/**
	 * Customize this function as you wish!
     * Add your validation below the email if.
     *
     * Change the behaviour of the plugin by editing this line:
     * 		$(this).blur( function() { validateField(this) } );
     * To:
     *      $(this).keyup( function() { validateField(this) } );
     *
     *  You can find it around the line number 64.
	 */
	function validateField(field) {
		var error = false;
		
		// required fields
		if ($(field).attr("class").indexOf("required") != -1) {
			if (!$(field).val().length)
				error = true;
		}
		// numeric fields
		if ($(field).attr("class").indexOf("numeric") != -1) {
			if (!/^[0-9]*$/.test($(field).val()))
				error = true;
		}

		// phone fields
		if ($(field).attr("class").indexOf("zip") != -1) {
				var phone=$(field).val();
				var numbers="1234567890";
				var phoneChars="-";
				var validDigits=0;
					
				for (var str_pos=0; str_pos < phone.length; ++str_pos) {
					var c = phone.charAt(str_pos);
					if (numbers.indexOf(c) == -1 && phoneChars.indexOf(c) == -1) {
						error = true;
					}
					if (numbers.indexOf(c) >= 0){
						validDigits++;
					}
				}
				if(validDigits != 5 && validDigits != 9){
					error = true;
				}
		}

		// phone fields
		if ($(field).attr("class").indexOf("phone") != -1) {
				var phone=$(field).val();
				var numbers="1234567890";
				var phoneChars=".()-xX ";
				var validDigits=0;
				//if (ID.length != 6) {
				//    FV_Errmsg.setDetail("Agent ID is a 6 digit number");
				//    return false;
				//}
					
				for (var str_pos=0; str_pos < phone.length; ++str_pos) {
					var c = phone.charAt(str_pos);
					if (numbers.indexOf(c) == -1 && phoneChars.indexOf(c) == -1) {
						error = true;
					}
					if (numbers.indexOf(c) >= 0){
						validDigits++;
					}
				}
				if(validDigits < 10){
					error = true;
				}
		}

		// characters (letters)
		if ($(field).attr("class").indexOf("character") != -1) {
			if (!/^[a-zA-ZöÖäÄåÅ]*$/.test($(field).val()))
				error = true;
		}
		// emails
		if ($(field).attr("class").indexOf("email") != -1) {
			if (!/^[a-zA-Z0-9]{1}([\._a-zA-Z0-9-]+)(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-z0-9-]+){1,3}$/.test($(field).val()))
				error = true;
		}
		
		if (error) {
			$(field).parent().addClass("error");
		} else {
			$(field).parent().removeClass("error");
		}
		
		return !error;
	}
	
	$("form").each( function() {
		// handle submissions without filling any field
		$(this).submit(function () {
			var validationError = false;
			// for each field test it
			$("input, select, textarea", this).each( function() {
				if ($(this).attr("class")) {
					if (!validateField(this))
						validationError = true;
				}
			});
			return !validationError;
		});
	
		// handle changes on the fly
		$("input, select, textarea", this).each( function() {
			if ($(this).attr("class")) {
				$(this).blur( function() { validateField(this) } );
    			}
		});
	});
});
