/*     
	February 2009
	Javascript functions for form validations
	Copyright (C) 2009 Tim Boormans, Direct Web Solutions. www.directwebsolutions.nl
*/

function is_valid_emailaddress($val) {
	// regular email address: inf-_o@subdomain.domain.travel
	var isValid = true;
	var Regex =/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,7})+$/;
	if(!Regex.test($val)){isValid = false;}		
	return isValid;
}

function is_valid_zipcode($val) {
	// dutch zipcode: 1234AB
	var isValid = true;
	var Regex = /^(\d{4})+([a-zA-Z]{2})+$/;
	if(!Regex.test($val)){isValid = false;}
	return isValid;
}

function is_numeric($val) {
	// check for numeric values like phone numbers. Throw true for empty values
	var isValid = true;
	var Regex = /^([0-9]{0,20})+$/;
	if(!Regex.test($val)){isValid = false;}
	return isValid;
}

function is_empty($val) {
	// checks for empty strings, 0 characters long
	str = new String($val);
	var isValid;
	
	if(str.length == 0)
		isValid = true;
	else
		isValid = false;
	return isValid;
}

function do_passwords_match($password1, $password2) {
	// checks for the password to be the same, and being strong enough
	// this functions makes it possible to do real checks, simple checks are
	// returning wrong results if the string has the same length with other characters
	str1 = new String($password1);
	str2 = new String($password2);
	var isValid;
	
	if(str1.length == str2.length) {
		// strings are the same length, check for the characters
		var $error = false;
		
		for($i = 0; $i < str1.length; $i++) {
			if(str1.charAt($i) != str2.charAt($i)) {
				$error = true;
			}
		}
		
		if($error) {
			// found a different character
			isValid = false;
		} else {
			// found only the same characters
			isValid = true;
		}
	} else {
		isValid = false;
	}
	
	return isValid;
}

function same_strings($str1, $str2) {
	// Checks two string for duplicateness using the password check function
	return do_passwords_match($str1, $str2);
}

function errmsg(message) {
	// Create errors message using default status messages for form fields
	if(same_strings(message, "_required")) {
		message = "Dit veld is verplicht";
	} else if(same_strings(message, "_numbers")) {
		message = "Alleen cijfers zijn toegestaan";
	} else if(same_strings(message, "_wrong")) {
		message = "Foutieve invoer";
	}
	
	return " &lt; " + message + " &gt;";
}

function errormsg(message) {
	// function to overcome typo errors
	return errmsg(message);
}

function textarea_limit(textarea_id, character_limit, status_span) {
	var text = $('#'+textarea_id).val(); 
	var textlength = text.length;
	if(textlength > character_limit) {
		$('#' + status_span).html( errmsg('Je kunt maximaal '+character_limit+' tekens typen') );
		$('#'+textarea_id).val(text.substr(0,character_limit));
		return false;
	} else {
		$('#' + status_span).html( errmsg('Je hebt nog '+ (character_limit - textlength) +' tekens over') );
		return true;
	}
}

/* $(":checkbox[name='boxes[]']:checked") */
