// JavaScript Document: project validation helpers.
// #INCLUDE('jquery.js')
// #INCLUDE('validations.js')
// @version 3.0

/**
	Helper function that return TRUE/FALSE.
	@param $l the label object.
	@param $m the error message object.
*/
function isValid($l, $m, b) {
	if(b) {
		$l.removeClass(ErrorClass);
		$m.removeClass(ErrorClass);
	} else {
		$l.addClass(ErrorClass);
		$m.addClass(ErrorClass);
	}
	return b;
}

// Return a jquery object of the element that shows/reflects the error.
function getErrorDisplay(widgetId) {
	return $("#"+ElementPrefix+widgetId);
}

// Return the jquery object of the error message.
function getErrorMessage(widgetId) {
	return $("#"+MessagePrefix+widgetId);
}

// Returns a jquery object.
function getWidget(widgetId) {
	var $widget = $("#"+widgetId);
	$widget.val(trim($widget.val()));
	return $widget;
}

// ---- Common Validators -----------------------------
// NOTE: All validators must return true if valid, false otherwise.

/**
	check if a field is not empty.
	@return true if not empty, false if invalid.
*/
function validate_notEmpty(widgetId) {
	var $widget = getWidget(widgetId);
	var $l = getErrorDisplay(widgetId);
	var $m = getErrorMessage(widgetId);
	
	var v = $widget.val();
	return isValid($l, $m, (v!=''));
}

//generic validator: check if a password field is empty or not.
function validate_password(widgetId) {
	var $widget =  $("#"+widgetId);
	var $l = getErrorDisplay(widgetId);
	var $m = getErrorMessage(widgetId);
	
	var v = $widget.val();
	return isValid($l, $m, (v!=''));
}


// email validator.
function validate_email(widgetId) {
	var $widget = getWidget(widgetId);
	var $l = getErrorDisplay(widgetId);
	var $m = getErrorMessage(widgetId);
	var v = $widget.val();
	
	if(v!='' && isEmail(v)) {
		// are there 2 or 3 letters following the dot?
		s = v;
		s = s.substring(s.lastIndexOf('.')+1);
		if(s.length==2 || s.length==3) {
			return isValid($l, $m, true);
		}
	}
	return isValid($l, $m, false);
}

// URL validator.
function validate_url(widgetId) {
	var $widget = getWidget(widgetId);
	var $l = getErrorDisplay(widgetId);
	var $m = getErrorMessage(widgetId);
	
	return isValid($l, $m, isURL($widget.val()) );
}

