var arrValidations = new Array();
var fieldValidationIndexes = Array(); // this is just a helper for grouping validations by fieldname

function addValidation(sElementName, sElementType, sValidationType, sErrorText, sExtendedParameters) {
	var validationIndex = fieldValidationIndexes.indexOf(sElementName);
	if ( validationIndex == -1 ) {
		fieldValidationIndexes.push(sElementName);
		validationIndex = fieldValidationIndexes.length - 1;
		arrValidations.push(new Array());
	}

	var validation = new Object();
	validation.elementName = sElementName;
	validation.ValidationType = sValidationType;
	validation.ElementType = sElementType;
	validation.ErrorText = sErrorText;
	validation.ExtendedParameters = sExtendedParameters;
	arrValidations[validationIndex].push(validation);
}

function Validate(arrValidations, fromHiddenTool) {
	var bError;
	var bFormIsValid = true;

	var sErrorMessage = "";

	// find the ids of all hidden tools (new node tool, search tool) if this is not a "new node" or "Search tool" validation
	var toolIds = new Array();
	if(fromHiddenTool!=true) {
		// new node tools and
		var spans = document.forms[0].getElementsByTagName("SPAN")
		for(var i=0; i<spans.length; i++) {
			if(spans[i].id.indexOf("NewNodeTool")>=0 || spans[i].id.indexOf("SearchTool")>=0 || spans[i].id.indexOf("PopupWindow")>=0) {
				toolIds.push(spans[i].id);
			}
		}
	}
	

	// traverse the elements with validations
	// for(var sElementName in arrValidations) {
	for ( var j = 0; j < arrValidations.length; j++ ) {
		// take elementName from first entry
		sElementName = arrValidations[j][0].elementName;
		// ignore this element because it belongs to a hidden tool?
		if(fromHiddenTool!=true) {
			var ignore = false;
			// traverse the hidden tools
			for(var i=0; i<toolIds.length; i++) {
				if(document.getElementById(toolIds[i]).contains(document.forms[0][sElementName])) {
					// the element is contained in a hidden tool
					ignore = true;
					break;
				}
			}
			if(ignore==true) {
				// ignore the validation
//				alert("ignoring " + sElementName + " in validation");
				continue;
			}					
		}
		
		bError = false;
		// traverse the validation types of the element
		// for(var i in arrValidations[sElementName]) {
		for ( var i = 0; i < arrValidations[j].length; i++ ) {
			var validation = arrValidations[j][i];
			var sElementName = validation.elementName;
			// TODO: Add validation types
			switch(validation.ValidationType){
				case 'NotEmpty':
					// validate the element (the element type name is at index 0 in the array arrValidations[sElementName][sValidationType])
					bError = ValidateNotEmpty(sElementName, validation.ElementType);
					break;
				case 'Numeric':
					// validate the element (the element type name is at index 0 in the array arrValidations[sElementName][sValidationType])
					bError = ValidateNumeric(sElementName, validation.ElementType);
					break;
				case 'RegularExpression':
					// validate the element (the element type name is at index 0 in the array arrValidations[sElementName][sValidationType])
					bError = ValidateRegularExpression(sElementName, validation.ElementType, validation.ExtendedParameters);
					break;
				case 'RegularExpressionNonMatch':
					// validate the element (the element type name is at index 0 in the array arrValidations[sElementName][sValidationType])
					bError = ValidateRegularExpressionNonMatch(sElementName, validation.ElementType, validation.ExtendedParameters);
					break;
				case 'AllowedFileTypes':
					bError = ValidateFileTypeAllowed(sElementName,validation.ExtendedParameters);
					break;
			}
			if(bError) {
				// the validation failed - show error text (at index 1 in the array arrValidations[sElementName][sValidationType])
//				debug(arrValidations[sElementName][sValidationType][1]);
//				document.getElementById(sElementName+'_errormessage').innerHTML = arrValidations[sElementName][sValidationType][1];
				// TODO: Formatting!
				sErrorMessage = sErrorMessage + "<li>" + validation.ErrorText + "</li>";
				// the whole form failed to validate!
				bFormIsValid = false;
			}
		}
		if(bError==false) {
			// the element validation succeded - make sure the element error message is empty (if other elements fails to validate)
//			document.getElementById(sElementName+'_errormessage').innerHTML = '';
		}
	}

	if(bFormIsValid==false) {
		GetPane().HidePopupTool();
		sErrorMessage = "<ul>"+sErrorMessage+"</ul>";
		// append the errormessage to the localized validation error text (from main page)
//		sErrorMessage = "Please correct the following errors before continuing:<br/><br/>" + sErrorMessage;
		sErrorMessage = parent.TextValidationErrorText + sErrorMessage;
		// show warning (warning title is localized on main page)
		GetPane().Alert(parent.TextValidationErrorTitle, sErrorMessage, true);
	}
	return bFormIsValid;
}

function ValidateNotEmpty(sElementName, sElementType) {
	var bError = false;
	// TODO: Add element types
	switch(sElementType) {
		
		case 'TextBox':
		case 'TextArea':
		case 'PasswordBox':
		case 'VisualEditor':
		case 'Dropdown':
//			alert("document.forms[0][sElementName].value = " +document.forms[0][sElementName].value);
			if(document.forms[0][sElementName].value==''){
				bError = true;
			}
			break;
	}
//	debug("value: "+eval('document.forms[0].'+sElementName+'.value'));
//	debug("ValidateNotEmpty: "+sElementName+", "+sElementType+": "+bError);
	return bError;
}

// validate: numeric or empty
function ValidateNumeric(sElementName, sElementType) {
	var bError = false;
	// TODO: Add element types
	switch(sElementType) {
		case 'TextBox':
		case 'TextArea':
		case 'VisualEditor':
		case 'PasswordBox':
			if(document.forms[0][sElementName].value!=''){
				bError = isNaN(document.forms[0][sElementName].value);
			}
			break;
	}
//	debug("value: "+eval('document.forms[0].'+sElementName+'.value'));
//	debug("ValidateNotEmpty: "+sElementName+", "+sElementType+": "+bError);
	return bError;
}

function ValidateRegularExpression(sElementName, sElementType, sRegEx) {
	var bError = false;
	// TODO: Add element types
	switch(sElementType) {
		case 'TextBox':
		case 'TextArea':
		case 'VisualEditor':
		case 'PasswordBox':
			var sValue = document.forms[0][sElementName].value;
			var regExValidation = eval('new RegExp(/'+sRegEx+'/)');
			bError = !regExValidation.test(sValue);
			break;
	}
//	debug("value: "+eval('document.forms[0].'+sElementName+'.value'));
//	debug("ValidateNotEmpty: "+sElementName+", "+sElementType+": "+bError);
	return bError;
}

function ValidateRegularExpressionNonMatch(sElementName, sElementType, sRegEx) {
	var bError = false;
	// TODO: Add element types
	switch(sElementType) {
		case 'TextBox':
		case 'TextArea':
		case 'VisualEditor':
		case 'PasswordBox':
			var sValue = document.forms[0][sElementName].value;
			var regExValidation = eval('new RegExp(/'+sRegEx+'/)');
			bError = regExValidation.test(sValue);
			break;
	}
//	debug("value: "+eval('document.forms[0].'+sElementName+'.value'));
//	debug("ValidateNotEmpty: "+sElementName+", "+sElementType+": "+bError);
	return bError;
}


function ValidateFileTypeAllowed(elementName,fileTypes){
	var error = false;
	//get the selected file name
	var fileName = document.forms[0][elementName].value;
	//prepare the list of allowed filetypes
	fileTypes = "," + fileTypes + ","
	fileTypes = fileTypes.toLowerCase();
	if (fileName != ''){
		//get the extension
		arrDots = fileName.split(".")
		//get the part AFTER the LAST period.
		var extension = arrDots[arrDots.length-1].toLowerCase();
		//check if the extension is in the list of allowed file types
		if (fileTypes.indexOf("," + extension + ",") < 0){
			error=true;
		}
	}
	return error;
}




