// BF Form Validation functions
// Written by Joseph Pitt
// With reference from AppleŽ webcontent guide


var linesAlreadyAlerted;
var noErrors = true;

function validateForm() {
	var why = "";
	noErrors = true;
	
	linesAlreadyAlerted = new Object();
	
	//-----------------------------------------------------------------------------+
	$('[required="true"], [maxLength], [minLength], .maxByLineAvailable, .has_multi_text input[type="text"], .has_multi_text textarea').each(function(index) {
	
		var thisWarnDiv = $(this).parent();
		var theType = $(this).get(0).nodeName;//$(this).attr("tagName");
		var richText = $(this).hasClass("richTextArea");
		var theID = $(this).attr("id");
		var isRequired;
		if ( $(this)[0].getAttribute("required") == "true") {
			isRequired = true;
		} else {
			isRequired = false;
		}
		var isMultiText = $(this).parent().hasClass("has_multi_text");
		if (isMultiText) {
			isRequired = $(this).parent().hasClass("required");
		}
		var maxByLineAvailable = $(this).hasClass("maxByLineAvailable");
		
		var theValidation = $(this).attr("validation");
		if (theValidation == null) {
			var theValidation = 3;
		} else {
			var theValidation = parseInt(theValidation);
		}
		var theLabel = "NA";
			
		if ( $(this).parent().is(":visible") ) {
		
		//-----------------------------------------------------------++
			if (isMultiText) {
				var thisVal = $(this).val();
				var min_len = $(this).attr("minLength");
				var max_len = $(this).attr("maxLength");
				var classes = $(this).parent()[0].className.split(' ');
				
				for (var i = 0; i < classes.length; i++) {
	        		if ( classes[i].indexOf("multitext_id_") != -1 ) {
	           			var startChar = 13;
	          			var val = classes[i].substring(startChar);
	          		}
	          	}
				var thisObj = multiTextFields[val];
				var theSelector = ("multitext_id_" + thisObj.id);
				var ml = thisObj.maxLines;
				var mc = thisObj.maxCharactersPerLine;
				var overallFieldName = thisObj.overallFieldName;
				
				if ( checkMaxCharactersByLine_multi(thisVal, theID, theLabel, mc, ml, theSelector, overallFieldName, isRequired) != "" ) {
					thisWarnDiv.addClass('warn');
					} else {
						thisWarnDiv.removeClass('warn');
					}
			} else {
			
				if (theType == "SELECT") {
					if (   $(this).children("option:selected").text() == $(this).children("option:first").text()   ) {
						thisWarnDiv.addClass('warn');
						noErrors = false;
					} else {
						thisWarnDiv.removeClass('warn');
					}
				}
				
				if ( (theType == "INPUT") || (theType == "TEXTAREA") ) {
				
					var thisVal = $(this).val();
					var min_len = $(this).attr("minLength");
					var max_len = $(this).attr("maxLength");
					
					if (richText) {
					var instance = CKEDITOR.instances[theID];
					var thisVal = instance.document.getBody().$.innerHTML;
					
						// remove html markup from our string
						//thisVal = thisVal.replace(/<\/?[a-z][a-z0-9]*[^<>]*>/ig, "");
						thisVal = thisVal.replace(/[\n\t\r]+/ig, ""); // remove newlines returns and tabs
						thisVal = thisVal.replace(/<p.*?>/ig, ""); // remove <p ?> tags
			            thisVal = thisVal.replace(/<br><\/p>/ig, "\n"); // replace </p> tags with newline
			            thisVal = thisVal.replace(/<br><\/P>/ig, "\n"); // replace </P> tags with newline
			            thisVal = thisVal.replace(/<\/p>/ig, "\n"); // replace </p> tags with newline
			            thisVal = thisVal.replace(/<\/P>/ig, "\n"); // replace </P> tags with newline
			            thisVal = thisVal.replace(/<span.*?>/ig, ""); // remove <span ?> tags
			            thisVal = thisVal.replace(/<\/span>/ig, ""); // remove </span> tags
			            thisVal = thisVal.replace(/<br>/ig, "\n"); // replace <br> tags with newline
			            thisVal = thisVal.replace(/<\/strong>/ig, ""); // remove </strong> tags
			            thisVal = thisVal.replace(/<strong>/ig, ""); // remove <strong> tags
			    		thisVal = thisVal.replace(/<\/u>/ig, ""); // remove </u> tags
			            thisVal = thisVal.replace(/<u>/ig, ""); // remove <u> tags
			    		thisVal = thisVal.replace(/<\/em>/ig, ""); // remove </em> tags
			            thisVal = thisVal.replace(/<em>/ig, ""); // remove <em> tags
					}
					
					
					if (maxByLineAvailable) {
						
							var classes = this.className.split('\s');
					        for (var i = 0; i < classes.length; i++) {
					            if ( classes[i].indexOf("maxByLine_") != -1 ) {
					                var startChar = ( classes[i].indexOf("maxByLine_") + 10 );
					                if (richText) {
						                var valsAtStart = classes[i].substring(startChar);
						                var valsEnd = valsAtStart.indexOf(" ");
						                var vals = valsAtStart.substring(0, valsEnd);
						            } else { 
						                var vals = classes[i].substring(startChar);
					                }
					                var valArray = vals.split('_');
					                maxCharactersPerLine = valArray[0];
					                maxLines = valArray[1];
					            }
					        }
					    
					
						if ( checkMaxCharactersByLineField(thisVal, theID, theLabel, maxCharactersPerLine, maxLines, richText, isRequired) != "" ) {
							thisWarnDiv.addClass('warn');
							noErrors = false;
						} else {
							thisWarnDiv.removeClass('warn');
						}
					} else {
						if ( checkTextField(thisVal, theID, theLabel, min_len, max_len, theValidation, richText, isRequired) != "" ) {
							thisWarnDiv.addClass('warn');
							noErrors = false;
						} else {
							thisWarnDiv.removeClass('warn');
						}
					}
				}
			}
		//-----------------------------------------------------------++
		}//--------end if element is hidden therefore not really required
		
		$(".formElement").find(".formElement .formElementWarn").css({"display" : "none"}) //--Never show comments that are part of a required set (image selector)
	});
	//-----------------------------------------------------------------------------+
	
	//-----------------------------------------------------------------------------+
	var sameDone = [];
	$('[same]').each(function(index) {
		var thisSame = $(this).attr("same");
		var theID = $(this).attr("id");
		if ( !(sameDone[thisSame]) ) {
			sameDone[thisSame] = theID;
			var Val_1 = $(this).val();
			
			$('[same="' + thisSame + '"]').filter('[id!="' + theID + '"]').each(function(index) {
				var Val_2 = $(this).val();
				var comparison = compareFields(Val_1, Val_2, thisSame, true);
				if (comparison != "") {
				why += comparison;
					return true;
				}
			});	
		}
	});
		
				
				
	
return noErrors;
}











//---CHECK TEXT FIELDS VALIDITY
//----------------------------------------
//---characterCheckLevel:
//---------------------0: allow only letters, numbers, and underscores (ie. username) 
//---------------------1: allow only letters and numbers, must contain at least 1 uppercase letter, 1 lowercase letter, and 1 numeral (ie. password)
//---------------------2: any characters, must contain at least 1 uppercase letter, 1 lowercase letter, and 1 numeral (ie. password)
//---------------------3: any characters (ie. text input)
//---------------------4: email validation (based on Apple guide recommendations)
//---------------------5: phone number, allow only numbers, spaces, parentheses, dashes and dots (ie. phone number)
//---------------------6: allow numbers only (ie. registration number or code)
function checkTextField(strng, fieldID, fieldName, lowestCharacters, highestCharacters, characterCheckLevel, isRichText, isRequired) {
	var error = "";
	
	
	//---check the field is not blank
	if ((strng == "") && (isRequired == true)) {
    	error = "You didn't enter a value for " + fieldName + ".\n";
    	return error;
	}
	
	//---check the value is within specified character limits
	if (isRichText) {
		var adjustLength = 1;
	} else {
		var adjustLength = 0;
	}
	
	if (lowestCharacters != "") {
		lowestCharacters = parseInt(lowestCharacters);
		if (strng.length - adjustLength < lowestCharacters) {
			error += "The " + fieldName + " length is too short.\n";
		}
	}
	if (highestCharacters != "") {
		highestCharacters = parseInt(highestCharacters);
		if ( (strng.length  - adjustLength > highestCharacters) && (highestCharacters != -1) ) {
    		error += "The " + fieldName + " length is too long.\n";
    	}
	}
	
	//---check for character tolerance
	if (characterCheckLevel == 0) {
		if ( containsOtherThan_LNU(strng) ) {
			error = "The " + fieldName + " contains illegal characters.\n";
		}
	} else if (characterCheckLevel == 1) {
		if ( containsOtherThan_LN(strng) ) {
			error = "The " + fieldName + " contains illegal characters.\n";
		}
		if ( containsOtherThan_1U1L1N(strng) ) {
			error += "The " + fieldName + " must contain at least one uppercase letter, one lowercase letter, and one numeral.\n";
		}
	} else if (characterCheckLevel == 2) {
		if ( containsOtherThan_1U1L1N(strng) ) {
			error = "The " + fieldName + " must contain at least one uppercase letter, one lowercase letter, and one numeral.\n";
		}
	//-------skip characterCheckLevel=3 because 3 is any character (see above)
	} else if (characterCheckLevel == 4) {
		if ( containsOtherThan_EMAIL(strng) ) {
			error = fieldName + ": Please enter a valid email address.\n";
		}
		if ( containsOtherThan_EMAIL_CHARS(strng) ) {
			error += "The email address contains illegal characters.\n";
		}
	} else if (characterCheckLevel == 5) {
		if ( containsOtherThan_PHONE_CHARS(strng) ) {
			error = "The " + fieldName + " contains illegal characters.\n";
		}
	}
	
	return error;
}
	
	
	
	
	
	
function checkMaxCharactersByLineField(strng, fieldID, fieldName, charPerLine, mostLines, isRichText, isRequired) {
	var error = "";

	//---check the field is not blank
	if ((strng == "") && (isRequired == true)) {
    	error = "You didn't enter a value for " + fieldName + ".\n";
    	return error;
	}
	
	//---check the value is within specified character limits
	if (isRichText) {
		var adjustLength = 1;
	} else {
		var adjustLength = 0;
	}
	
	var theseLines = strng.split('\n');

	if ( (theseLines.length - adjustLength) > mostLines ) {
		error += "The " + fieldName + " field has too many lines.\n";
	}
	
	for (var ix = 0; ix < theseLines.length; ix++) {
	    var i_str = theseLines[ix].replace(/\n*\t*\r*/ig, ""); // remove newlines, returns and tabs;
	    var i_length = theseLines[ix].length;
	    if (i_length > charPerLine) {
	    	error += ("The " + fieldName + " field has " + (i_length - charPerLine) + " characters too many on line " + (ix+1) + ".\n");
	    }
    }
	return error;
}
	
	
	
	
	
	
	
	
function checkMaxCharactersByLine_multi(strng, fieldID, fieldName, charPerLine, mostLines, theSelector, overallFieldName, isRequired) {
	var error = "";
	
	var thisContent = "";
	var allMyFields = $('.' + theSelector + ' textarea, .' + theSelector + ' input[type="text"]')
	var allMyFieldsLength = allMyFields.size();
   		allMyFields.each( function( g ) {
   			var textToAdd = "";
    		textToAdd = $(this).val();
    	
			if ( textToAdd != "" ) {
				thisContent += textToAdd
				if (g != (allMyFieldsLength - 2)) {
    				thisContent += "\n";
    			}
    		}
   	});

	//---check the field is not blank
	if ((thisContent == "") && (isRequired == true)) {
    	error = "You didn't enter a value for " + fieldName + ".\n";
    	return error;
	}
	
	
	var theseLines = thisContent.split('\n');

	if ( (theseLines.length) > mostLines ) {
		if (linesAlreadyAlerted[theSelector] != true) {
			error += "The " + overallFieldName + " fields have too many lines.\n";
			linesAlreadyAlerted[theSelector] = true;
		}
	}
	
	
	var theseLines = strng.split('\n');
	
	for (var ix = 0; ix < theseLines.length; ix++) {
	    var i_str = theseLines[ix].replace(/\n*\t*\r*/ig, ""); // remove newlines, returns and tabs;
	    var i_length = theseLines[ix].length;
	    if (i_length > charPerLine) {
	    	error += ("The " + overallFieldName + " - " + fieldName + " field has " + (i_length - charPerLine) + " characters too many on line " + (ix+1) + ".\n");
	    }
    }
	return error;
}
	
	
	
	
	
	
	
	
	
	
	
	

//---compare field values (html attributes same or differ)
function compareFields(strng1, strng2, fieldSetName, shouldBeIdentical) {
	var error = "";
	if (shouldBeIdentical == true) {
		if (strng1 != strng2) {
			error = "The " + fieldSetName + " fields do not match.\n";
		}
	} else {
		if (strng1 == strng2) {
			error = "The " + fieldSetName + " fields have matching values.\n";
		}
	}
	return error;
}





 

	
function containsOtherThan_LNU(str) {
	//--- allow only letters, numbers, and underscores
	//------------------------------------------------
	//---The JavaScript regular expression /\W/ is a standard character class
	//---that's handily predefined to mean "any character other than
	//---letters, numbers, and underscores."
	var illegalChars = /\W/;
    if (illegalChars.test(str)) {
       return true;
    }
    return false;
}

function containsOtherThan_LN(str) {
	//--- allow only letters and numbers
	//------------------------------------------------
	var illegalChars = /[\W_]/; // allow only letters and numbers
    if (illegalChars.test(str)) {
       return true;
    }
    return false;
}

function containsOtherThan_1U1L1N(str) {
	//--- must contain at least 1 uppercase letter, 1 lowercase letter, and 1 numeral
	//------------------------------------------------
    if (   !(  (str.search(/[a-z]+/) > -1)  &&  (str.search(/[A-Z]+/) > -1)  &&  (str.search(/[0-9]+/) > -1)  )   ) {
  		return true;
	}
    return false;
}

function containsOtherThan_EMAIL(str) {
	//--- must comply with our email address regex (as sure as we can be that it is an email address)
	//------------------------------------------------
	//--[any number of characters] @ [at least 2 characters, not dots] . [at least 2 characters, not dots] [any number of optional characters]
	var emailFilter=/^.+@[^.]{2,}\.[^.]{2,}.*$/; 
	if (!(emailFilter.test(str))) { 
     		return true;
	}
    return false;
}
	
function containsOtherThan_EMAIL_CHARS(str) {
	//--- allow only email permitted characters (as specified by Apple guide)
	//------------------------------------------------
	var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/
	if (str.match(illegalChars)) {
   		return true;
	}
    return false;
}

function containsOtherThan_PHONE_CHARS(str) {
	//--- allow only numbers, spaces, parentheses, dashes and dots
	//------------------------------------------------
	//strip out acceptable non-numeric characters
	var stripped = str.replace(/[\(\)\-\ ]/g, '');
	if ( isNaN(stripped) ) {
		return true;
	}
    return false;
}
   		



//---Remove the last character from input if it matches the charX
function removeLastCharacterMatching(input, charX) {
	var input_len = input.length;
	var input_lastChar = input.charAt(input_len -1);
    if (input_lastChar == charX) {
        input = input.slice(0, -1)
    }
    return input;
}


	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
