//GENERIC VALIDATION

//CONSTANTS
var ALPHA 			= 'alpha';
var NUMERIC 		= "numeric";
var ALPHANUMERIC 	= "alphanumeric"; 

var alertElement	= null;

//This function required JQUERY
function validateInputField( fieldID, type, required, length, parent){
	var bool		= true;
	var context     = (parent == null)?'body':parent;
	var field 		= $(context).find("input#" +  fieldID);
	var value 		= field.val();
	var isEmpty 	= (value == null || value == "");
		
	//1. Validate if is empty and required 
	if(required && isEmpty) bool = false;
		
	//2. Validate if is not required and is empty
	if(!required && isEmpty) bool = true;
		
	//3. Validate value
	if(!isEmpty && bool){		
		switch(type){
			case ALPHA:
				bool = validatedAlpha(value);				
				break;
				
			case NUMERIC:
				bool = !isNaN(value);
				break;
				
			case ALPHANUMERIC:
				//THIS TYPE ALLOW ANYTHING CHARACTER AS VALUE OF THE FIELD
				break;
		}
		
		if(length != null && bool){
			bool = (value.length == length);
		}
	}
	
	//4. Display alert icon if it was configured using setAlertElement.
	if(alertElement && !bool){
		displayIconAlert(fieldID);
	}
	

	return bool;
}

function validateSelectField( fieldID, required ){
	var bool		= true;
	var field 		= $("select#" +  fieldID + " option:selected");
	var value 		= field.val();
	var isEmpty 	= (value == null || value == "");
	
	//1. Validate if is empty and required 
	if(required && isEmpty) bool = false;
		
	//2. Validate if is not required and is empty
	if(!required && isEmpty) bool = true;
	
	//3. Display alert icon if it was configured using setAlertElement.
	if(alertElement && !bool){
		displayIconAlert(fieldID);
	}	
	
	return bool;
}


function setAlertElement(alertID){
	alertElement = $(alertID);
}

function displayIconAlert(fieldID){
	var id		  = "_genAlertIcon";
	var label 	  = $("label[for=" + fieldID + "]");
	if(label.children("." + id).length == 0){
		var alertIcon = alertElement.clone(true);
		alertIcon.css("visibility","visible");
		alertIcon.attr("class", id);
		label.append(alertIcon);
	}
	
}

function removeIconAlerts(){
	$("._genAlertIcon").remove();
}


function validatedAlpha(string){
	var bool   = true;
	var length = string.length;
	for(var i=0; i<length; i++)	{
	  var character	 = string.charAt(i);
	  var chrCode	 = character.charCodeAt(0);
	  if((chrCode > 64 && chrCode<91) || (chrCode > 96 && chrCode<123)){
	  }else{
		  bool = false;
		  break;
	  }
	}
	return bool;
}