function satifyRadioNotBlank( dom ) {
	var firstClassName = jQuery(dom).attr("class").replace(/ .+$/, "");
  	var sameClassRadios = jQuery("." + firstClassName);
  	checkedRadios = jQuery.grep( sameClassRadios, function ( elem ) {
  		return ( elem.name === dom.name && elem.checked );
  	});
  
  	var parent = jQuery(dom).parent();
  	if (checkedRadios.length === 0) {
    	parent.css({
    		background:"#fcfe9c",
      		border:"1px solid #ababab"
    	});
    	return " is not checked";
  	} else {
	
    	parent.css({
    		background:"#ffffff",
      		border:""
    	});
    	return "";
  	} 
}

function satisfyACondition(condition, value, hasNotBlankCondition) {
	
	var message = "";
	
	if (condition.indexOf("contains") >= 0) {
		
		var containStr = condition.split("-")[1];
		
		var listOfWords = containStr.split(",");
		var hasWord = false;
		for (var ind = 0; ind < listOfWords.length; ind++) {
			if( value.indexOf(listOfWords[ind]) >= 0 ) {
				hasWord = true;
				break;
			}//end if
		}//end for
		
		if(hasWord === false) {
			message = " must contain one of the followings: " + containStr;
			return message;
		}//end if
	}//end if
	
	if (!hasNotBlankCondition && value === "") {
		return "";
	}//end if
	
	if (condition == "not-blank" && value === "") {
		message = " must not be blank";
	}//end if
	
	if (condition == "digits" && Utils.isNumeric(value) === false) {
		message = " must contain digits only";
	}//end if
	
	if (condition == "float" && Utils.isFloat(value) === false) {
		message = " must be a float number";
	}//end if
	
	if (condition == "email" && Utils.isEmail(value) === false) {
		message = " must be a valid email address";
	}//end if
	
	if (condition.indexOf("range") >= 0) {
		var from = parseFloat(condition.split("range")[0]);
		var to = parseFloat(condition.split("range")[1]);
		if (!Utils.isFloat(value)) {
			message = " must be a float number " + from + " to " + to;
		}//end if
		else {
			var fValue = parseFloat(value);
			if ( fValue < from || fValue > to) {
				message = " must have value from " + from + " to " + to;
			}//end if
		}//end if
	}//end if
	
	if (condition == "url" && isUrl(value) === false) {
		message = " must be a valid url";
	}//end if
	
	if (condition.indexOf("unique") >= 0) {

	  	className = condition.split("@")[1];
      	//console.log(condition, className, value);
    	var text;
    	jQuery("." + className).each( function ( i, e ) {
	      	text = jQuery.trim( jQuery(e).text() );
	       	//console.log( text );
	      	if ( text === value) {
	        	message = " must be unique"; 
      		}
    	});
	}

	if (condition.indexOf("size") >= 0) {
		var requiredSize = condition.split("@")[2];
		var operator = condition.split("@")[1];

		if (operator == "=" && value.length != requiredSize) {
			message = " must have size of " + requiredSize; 
		}
		else if (operator == "<=" && value.length > requiredSize) {
			message = " must have size of at most " + requiredSize;
		}
		else if (operator == ">=" && value.length < requiredSize) {
			message = " must have size of at least " + requiredSize;
		}
	}//end if
	
	if (condition.indexOf("sameas") >= 0) {
		var sameAsFieldId = condition.split("@")[1];
		var fieldValue = jQuery("#" + sameAsFieldId).val();
		if (fieldValue != value) {
			message = " must be the same as field " + jQuery("#" + sameAsFieldId).attr("name");
		}//end if
	}//end if
	
	
	if (condition.indexOf("not-url-chars") >= 0) {
		for( var i = 0; i < Utils.url_reserved_characters.length; i++) {
			if( value.indexOf(Utils.url_reserved_characters[i] + "") >= 0) {
				message = " must not contain any character of the following " + Utils.url_reserved_characters;
				break;
			}//end if
		}//end for
	}//end if
	
	
	return message;
}//end satisfyACondition

function satisfyConditions( dom, conditions, numberOfErrors) {
	
	var satisfy = true;
	var hasNotBlankCondition = false;
	var condition = "";
	for (var i = 0; i < conditions.length; i++) {
		condition = conditions[i];
		if (condition == "not-blank") {
			hasNotBlankCondition = true;
		}//end if
	}//end for
	
	message = "";
	var aMessage = "";
	var fieldErrors = 0;
	
	for ( i = 0; i < conditions.length; i++) {
		condition = conditions[i];
		aMessage = "";
		
	     // Tien Dung
	     // Add radio input validation
		if (dom.type == "checkbox") {
			if (condition == "required" && dom.checked === false) {
				aMessage = " must be checked";
			}//end if
		}//end if
		else {
		
			if (hasNotBlankCondition && dom.type === "radio") {
				aMessage = satifyRadioNotBlank(dom);
			}
			else {
				aMessage = satisfyACondition(condition, jQuery(dom).val(), hasNotBlankCondition);
			}
		}//end else
		  
		 
	  	// Tien Dung
	  	// Keep one error per input.name only
	  	if (arguments.callee.names[dom.name]) {
	    	continue;
	  	}
		  
		if (aMessage !== "") {
			
			numberOfErrors++;
			message += "<br/>" + (numberOfErrors < 10 ? ("&nbsp;&nbsp;" + numberOfErrors) : numberOfErrors) + ":&nbsp;&nbsp;&nbsp;Field "  + jQuery(dom).attr("name") + aMessage;
			fieldErrors++;
	  	  	arguments.callee.names[dom.name] = true;
		}//end if
	}//end for
	
	if (message === "") {
		
		if (typeof jQuery(dom).css("background") != "undefined" && jQuery(dom).css("background") != "#ffffff" && jQuery(dom).css("background").indexOf("rgb(206, 255, 191)") < 0) {
			if (dom.type != "radio" && dom.type != "checkbox") {
				jQuery(dom).css("background", "#ffffff");
			}//end if
			else {
				jQuery(dom).css("background", "#cbdcf0");
			}//end else	
		}//end if
	}//end if
	else {
		jQuery(dom).css("background", "#fcfe9c");
		
	}//end else

	return message + "##" + fieldErrors;
}//end satisfyConditions

function validatePosition( formId ) {
	var locationNames = [];
	jQuery("#" + formId).find("input[@name*=location]").css("background", "rgb(255, 255, 255)");
	jQuery("#" + formId).find("input[@name*=location]").each(function() {
		var locationName = jQuery(this).attr("name").split("[")[0];
		if( locationNames.indexOf(locationName) < 0) {
			locationNames.push( locationName );
		}//end if
	});
	
	var samePos = false;
	// Check pairwise different
	for( var i = 0; i < locationNames.length; i++) {
		var locationName = locationNames[i];
	
		var list1 = jQuery("input[@name*=" + locationName + "]");
		var sameLocation = false;
		for( var j = 0; j != i, j < locationNames.length; j++) {
			
			var clocationName = locationNames[j];
			if( clocationName == locationName ) {
				continue;
			}//end if
			var list2 = jQuery("input[@name*=" + clocationName + "]");
			if( hasSameValue( list1, list2 ) ) {
				list1.css("background", "rgb(206, 255, 191)");
				list2.css("background", "rgb(206, 255, 191)");
				samePos = true;
			}//end if
		}//end for
		
		return samePos;
	}//end for
	
	function hasSameValue( list1, list2 ) {
		var numberOfSame = 0;
		for( var i = 0; i < list1.length; i++) {
			var dom1 = list1.eq(i);
			var dom2 = list2.eq(i);
			var val1 = jQuery.trim( dom1.val() );
			var val2 = jQuery.trim( dom2.val() );
			if( val1 == val2 && val1 != "") {
				numberOfSame++;
			}//end if
		}//end for
		
		if( numberOfSame == list1.length ) {
			return true;
		}//end if
		
		return false;
	}
}

function validateForm( formId, errorContainer, callback ) {
  	
	jQuery("#" + formId).find("input,textarea").each(function() {
		Utils.removeTrailingSpace(jQuery(this));
	});
	
	jQuery("input[@class*=add-checkbox-when-tick]").click(function() {
		if( jQuery(this).attr("checked") == true) {
			var name = jQuery(this).attr("name").split("]")[0] + "_text" + "]";
			jQuery(this).next().after("<input name = '" + name + "' type = 'input' style = 'width: 80px;' class = 'form-input'></input>");
			jQuery(this).next().next().focus();
		}//end if
		else {
			jQuery(this).next().next().remove();
		}//end else
	});
	
	jQuery("#" + formId).submit(function() {
		satisfyConditions.names = {};

		var submit = true;
		var numberOfErrors = 0;
		var message = "";
		var firstErrorField = null;
		
		if( validatePosition( formId ) ) {
			message = "<br/>1:&nbsp;&nbsp;&nbsp;Position cannot be the same";
			numberOfErrors = 1;
		}//end if
		
		
		jQuery(this).find("input,textarea,select").each(function() {
			
    	/**
    	 * Tien Dung
    	 * strip whitespace of value if value is a string
    	 * Ticket 157286
			 * Add strim action for form fields whose class names contain 'strim'
			 */
			var className = this.className.toLowerCase();
			var val;
			if (className.indexOf('strim') > -1) {
			  val = jQuery(this).val();
			  val = jQuery.trim(val);
			  jQuery(this).val(val);
			}
			
			if ( className.indexOf("strim_aux") > -1) {
				val = jQuery(this).val();
				val = val.replace(/\-|\+|\]|\[|\(|\)|\ /g, "");
				check_val = val.replace(/\./g, "");
				if (Utils.isNumeric(check_val)) {
					val = check_val;
				}//end if
				jQuery(this).val(val);
			}//end if
			
			var classNames = this.className.split(" ");
			for (var j = 0; j < classNames.length; j++) {
				
				className = classNames[j];
				if (className.indexOf("{") >= 0 && className.indexOf("}") >= 0) {
					
					var validationCondition = eval("(" + className + ")");
					
					if (typeof(validationCondition.conditions) != "undefined") {
						
						messageOfThisField = satisfyConditions( this, validationCondition.conditions, numberOfErrors);
						var messages = messageOfThisField.split("##");
						message += messages[0];
						var newNumberOfError = parseInt(messages[1], 10);
						numberOfErrors += newNumberOfError;
						if (newNumberOfError > 0 && firstErrorField === null) {
							firstErrorField = this;
						}//end if
					}//end if
				}//end if
				
			}//end for
					
		});
		
		if (numberOfErrors !== 0) {
			jQuery("#" + errorContainer).html("<b>There are " + numberOfErrors + " error(s)</b>" + message);
			jQuery("#" + errorContainer + "-server").html("  <!--For IE6-->");
			jQuery("#" + errorContainer)[0].className = "error-message";
			jQuery("#" + errorContainer).css("display", "");
			//jQuery("#" + errorContainer).append("<a href = '#" + errorContainer + "' id = '" + errorContainer + "-link'>top</a>");
			//jQuery("#edit-profile-error-link").click();
			if (firstErrorField !== null) {
				jQuery(firstErrorField)[0].focus();
			}//end if
			submit = false;
		}//end if
						
		if (submit === false) {
			//Utils.alert("Please complete or fixed the yellow color fields");
		}//end if
		else {
			jQuery("#" + errorContainer).html("");
			jQuery("#" + errorContainer)[0].className = "";
		}//end else
		
    if (callback && callback instanceof Function) {
      callback();
    }
		return submit;
	});
		
		
		
}//end validateForm
