// CVS: $Id: form_validation_functions.js,v 1.1 2005/10/20 08:43:12 edward Exp $

// Generic form validation functions
// Include before any of the form validation scripts
function validate_text_field(text, minLength) {
	if (text.length < minLength)
		return false;
	return true;
}

function validate_text_field(text, minLength, maxLength) {
	if (text.length < minLength || text.length > maxLength)
		return false;
	return true;
}

function validate_email_address(email, maxLength) {
	if (email.length > maxLength)
		return false;
	
	var at_position = email.indexOf("@");
	if (at_position > 0) {
		var dot_position = email.indexOf(".", at_position);
		if ((dot_position > at_position+1) && (email.length > dot_position+1))
			return true;
	}
	
	return false;
}

// Validate a single select input (usually a drop-down)
// User must have selected an option different from the default NULL/blank value
function validate_select_single(select_array) {
	var opts = select_array.options;
	for (var i = 0; i < opts.length; i++) {
		if ((opts[i].selected) && (opts[i].value != "NULL") && (opts[i].value != "null"))
			return true;
	}
	return false;
}

// Validate a multiple select box
// User must have selected at least minSelected items
function validate_select_multiple(select_array, minSelected) {
	var opts = select_array.options;
	var num_selected = 0;
	for (var i = 0; i < opts.length; i++) {
		if (opts[i].selected)
			num_selected++;
		if (num_selected >= minSelected)
			return true;
	}
	return false;
}

// Check one of the radio options is selected
function validate_radio_group(radio_group) {
	for (var i = 0; i < radio_group.length; i++) {
		if (radio_group[i].checked) // True if it is selected
			return true;
	}
	return false;
}

// Check at least one of the checkboxes is selected
function validate_checkbox_group(checkbox_group) {
	for (var i = 0; i < checkbox_group.length; i++) {
		if (checkbox_group[i].checked) // True if it is selected
			return true;
	}
	return false;
}

// Check it is a valid numerical price
function validate_price_field(price_str) {
	if (price_str.length < 1)
		return false;
	// Reg exp: Will match up to 8 digits, optionally followed by a decimal point and a further 2 digits
	var reg_exp = /^\d{1,8}(\.\d{2})?$/;
	if (price_str.search(reg_exp) == -1)
		return false;
	return true;
}

function validate_price(part_number, pricing_qty, end_user_price, dist_price) {
	// If none are set, the price is empty
	if ((part_number.length == 0) && (pricing_qty.length == 0) && (end_user_price.length == 0) && (dist_price.length == 0))
		return "NOT SET";

	if (!validate_text_field(part_number, 1, 50))
		return "PART_NUM_ERROR";
	if (!validate_text_field(pricing_qty, 1, 30))
		return "PRICING_QTY_ERROR";
	if (!validate_price_field(end_user_price))
		return "END_USER_PRICE_ERROR";
	if (!validate_price_field(dist_price))
		return "DIST_PRICE_ERROR";

	return "OK";
}
