//jQuery Based Form Validator

function Validator(sFormID,bImg,bAjax,sScrollObj) {
	
	// Init some vars
	var valid = true;
	var IsChecked = false;
	var bHighlight = 0;
	var FieldToFix = '';
	var CurrValue = '';
	var OkToSubmit = 0;
	var ScrollObj = sScrollObj;

	// Re-init our message box
	$('#MessageBox').html("");
	$('#MessageBox').removeClass();
	$('#MessageBox').hide();
	
	// Reset all inputs to have generic bg-image or white bgcolor/black font
	$(':input').each(function() {
		var type = $(this).attr("type");
		if (type == 'text' || type == 'password' || type == 'select-one' || type == 'select-multiple') {
			if (bImg) {
				$(this).css({'background':"url('/intranet/images/form_bg.png') repeat-x top left"});
			} else {
				$(this).css({'background-color':'white'});
				$(this).css({'color':'black'});
			}
		} else if (type == 'textarea') {
			$(this).css({'background-color':'white'});
			$(this).css({'color':'black'});
		}
	});
	
	// Get our required fields
	var reqfields = $("input#Required").val().split(',');
	
	// If no required fields, allow submit
	if (reqfields.length <= 0) {
		
		OkToSubmit = 1;
		
	} else {
		
		MainLoop:
		for(i=0;i<reqfields.length;i++) {
			
			// Init FieldValidate var
			DoFieldValidate = 0;
			bFieldError = 0;
			
			// Check if passed in with "friendly name and ID name"				
			FriendlyCheck = reqfields[i].indexOf("|");
			if (FriendlyCheck > 0) {
				TmpSplit = reqfields[i].split('|');			
				CurrField = TmpSplit[0];
				FriendlyName = TmpSplit[1];
			} else {
				CurrField = reqfields[i];
				FriendlyName = reqfields[i];
			}
			
			//Get Type & Field Length (for checkboxes/radio w/same name
			CurrType = $('#' + CurrField).attr("type");
			CurrLength = $('#' + CurrField).attr("length");
			
			//If CurrLength GT 0, then this is a radio/checkbox w/same name, special extra processing needed
			//Ignore this for select boxes
			if(CurrLength > 0  && (CurrType == 'radio' || CurrType == 'checkbox')) {
				
				SecondLoop:
				for(var j = 0; j < CurrLength; j++) {
				
					if(IsChecked == true) {
						break;
					}
					
					CurrType = $('#' + CurrField[j]).attr("type");
					IsChecked = $('#' + CurrField[j]).attr("checked");					
					
				}//End SecondLoop For
			
				// Done w/loop, check if we have to alert
				//alert(reqfields[i]);
				if (IsChecked == false) {
					FieldToFix = CurrField;
					bHighlight = 0;
					break;							
				}
				
			//Not multi-named items	(if we didn't find one broken)
			} else if (FieldToFix == '') {
				
				//Checkboxes & Radio Buttons
				if (CurrType == 'radio' || CurrType == 'checkbox') {
					IsChecked = $('#' + CurrField).attr("checked");
					if (IsChecked == false) {
						FieldToFix = CurrField;
						bHighlight = 0;
						break;
					}
				}

				//Text, text area, password, files
				if (CurrType == 'text' || CurrType == 'textarea' || CurrType == 'password' || CurrType == 'file') {
					CurrValue = $('#' + CurrField).val();
					if (CurrValue == '') {
						FieldToFix = CurrField;
						bHighlight = 1;
						break;
						
					//Call field validator routines, returns an array with two elements, pass/fail and any error message to pass back to user.
					//Rules must be passed in the "rel" attribute
					} else if ($('#' + CurrField).attr("rel")) {
						
						FieldOK = ValidateField(CurrField);
						if (FieldOK[0] == 0) {
							FieldToFix = CurrField;
							bHighlight = 1;
							bFieldError = 1;
							strFieldError = FieldOK[1];
							break;
						} 
					}
					
				}
				
				//Select lists
				if (CurrType == 'select-one' || CurrType == 'select-multiple') {
					CurrValue = $('#' + CurrField).attr("selectedIndex");
					if (CurrValue == '' || CurrValue == '-1') {
						FieldToFix = CurrField;
						bHighlight = 1;
						break;
					}
				}
			
			}
			
		}
		
		if (FieldToFix != '') {
		
			//Was there a validation error with the field (not caught by onBlur, etc)
			if (bFieldError == 1) {
				var ErrorMsg = 'ERROR: <strong>' + strFieldError + '</strong><br>Please correct the <strong>' + FriendlyName + '</strong> field.';				
			} else {
				var ErrorMsg = 'Attention: Please ensure that all required fields are completed.<br>Please correct the <strong>' + FriendlyName + '</strong> field.';	
			}			
		
			if (bHighlight) {			
				if (bImg == 1 && CurrType != 'textarea') {
					$('#' + CurrField).css({'background':"url('/intranet/images/form_bg_req.png') repeat-x top left"});
				} else {
					$('#' + CurrField).css({'background-color':'red'});
					$('#' + CurrField).css({'color':'white'});
				}
				ErrorMsg += ' The affected field is highlighted.';
			} 
			
			$('#MessageBox').html(ErrorMsg);
			$('#MessageBox').addClass('errorBox');			
			$('#MessageBox').show();
			$.scrollTo($(ScrollObj), {offset: -50});
			$('#' + CurrField).select();			
		
		} else {
			OkToSubmit = 1;
		}
		
	}
	
	if (OkToSubmit) {
		$('#MessageBox').text("Please wait while we process your request...");
		$('#MessageBox').addClass('messageBox');
		$('#MessageBox').show();
		$.scrollTo($(ScrollObj), {offset: -50});
		$('input.submit').val("Please wait...");
		//Ajax submit?
		if (bAjax) {
			setTimeout(function(){ self.AjaxSubmitForm(sFormID) }, 750);
			return false;
		//Nope, regular, so submit the form!
		} else {
			setTimeout(function(){ $('#' + sFormID).submit() }, 750);
		}
	//Cannot submit, so return false no matter what	
	} else {		
    	return false;
	}
	
}

function AjaxSubmitForm(sFormID) {
	
	//Serialize our form data for submission
	var postData = $("#" + sFormID).serialize();
	//Get our "posting" page, will always be in a var ID = "Submitter", must prefix with "ajax_" and suffix with ".cfm"
	SubmitPage = $('#Submitter').val();
	
	$.ajax({
		type: "POST",
		url: "/home/library/ajax_" + SubmitPage + ".cfm",
		data: postData,
		success: function() {
			$('#MessageBox').removeClass();
			$('#MessageBox').text("Your information has been successfully submitted!");
			$('#MessageBox').addClass('positiveBox');
			$('#MessageBox').show();		
			//$(':input').val('');
			clearForm(sFormID);
			$('input.submit').val("Submit");
		}
	});
	
}

function ValidateField(sCurrField) {
		
	sValidateRules = $('#' + sCurrField).attr("rel");
	
	//Strip the brackets
	rulesRegExp = /\[(.*)\]/;
	getRules = rulesRegExp.exec(sValidateRules);		
	str = getRules[1];
	
	//Now split the rules
	pattern = /\W+/;
	arrRules = str.split(pattern);
	
	//Loop through our rules to check for this field		
	for (j=0; j < arrRules.length; j++){
		switch (arrRules[j]){
		case "phone": 
			var validateResult = ValidatePhone(sCurrField);
		break;
		case "email": 
			var validateResult = ValidateEmail(sCurrField);
		break;
		case "length": 
			var validateResult = ValidatePhone(sCurrField);
		break;
		default :;
		};
	};
	
	return validateResult;

}

function ValidatePhone(sCurrField){

	// Use this to remove all non-number values
	var re= /\D/;
	// test for this format: (xxx)xxx-xxxx
	var re2 = /^\({1}\d{3}\)\d{3}-\d{4}/; 
	// test for this format: xxx-xxx-xxxx
	var re3 = /^[2-9]\d{2}-\d{3}-\d{4}$/;
	
	var newNum;
	var currNum =  $('#' + sCurrField).val();
	var RetData = Array(1);
	if (currNum != "" && (re2.test(currNum)!=true || re3.test(currNum)!=true)){
	
		//Strip all non-numbers
		while (re.test(currNum)){
			currNum = currNum.replace(re,"");
		}
		
		//If not 10 digits, return error
		if (currNum.length != 10){
			RetData[0] = 0;
			RetData[1] = 'Please enter a 10 digit phone number!';
		} else {
			//Reformat the number
			newNum = currNum.substring(0,3) + '-' + currNum.substring(3,6) + '-' + currNum.substring(6,10);
			$('#' + sCurrField).val(newNum);
			RetData[0] = 1;
			RetData[1] = '';
		}
	} else {
		RetData[0] = 1;
		RetData[1] = '';
	}

	return RetData;

}

function ValidateEmail(sCurrField)
{

	// Use Regular Expressions for Email Verification
	// Credit Reg-Ex Check: Gavin Sharp (http://www.glensharp.com/gavin/)
	REEmail = /^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$/
	
	var sEmail =  $('#' + sCurrField).val();
	//Check if blank, if so, ignore for now
	if (sEmail.value != '') {
		if (!sEmail.value.match(REEmail)) {
			RetData[0] = 0;
			RetData[1] = 'Please enter a valid email address!';
		} else {
			RetData[0] = 1;
			RetData[1] = '';
		}
	} else {
		RetData[0] = 1;
		RetData[1] = '';
	}
	
	return RetData;
	
}

///Generic Function to Show/Hide "Other" text field when drop down has "Other" option 
///*** Other option value must be "Other" for this to work, as well as use of <span id="Other<field>" style="display: 'none'"> tags, 
///where <field> is a numerical value for which <span> to hide/show
function ShowOtherOption(sCurrField) {	
	if ($('#' + sCurrField).val() == "Other") {
		$('#' + sCurrField + 'Other').show();
	} else {
		$('#' + sCurrField + 'Other').hide();
	}
}


//Clear out the form for ajax based submits.
function clearForm(sFormID) {
  // iterate over all of the inputs for the form
  // element that was passed in
  $('#' + sFormID + ' :input').each(function() {
    var type = this.type;
    var tag = this.tagName.toLowerCase(); // normalize case
    // it's ok to reset the value attr of text inputs,
    // password inputs, and textareas
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = "";
    // checkboxes and radios need to have their checked state cleared
    // but should *not* have their 'value' changed
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    // select elements need to have their 'selectedIndex' property set to -1
    // (this works for both single and multiple select elements)
    else if (tag == 'select' || tag == 'select-multiple')
      this.selectedIndex = -1;
  });
};