/**
* Created by ivanvelev on 11/11/16.
*/
var ClaremontEapFormController = function(cfg) {
var that = this;
var configs = cfg;
var getFieldsConfig = function() {
return configs.fields;
};
var SubmitState = {
REVIEW: 1,
CONFIRM: 2,
EDIT: 3
};
this.submitState = SubmitState.EDIT;
this.form = $(configs.elements.form);
if (!this.form || !this.form.length) {
console.log('error: no form to validate');
return;
}
this.formEl = $(configs.elements.form_container);
this.reviewContainerEl = $(configs.elements.form_summary_container);
this.reviewEl = $(configs.elements.form_summary);
this.submitProgressEl = $(configs.elements.form_submtit_progress);
this.submitDoneEl = $(configs.elements.form_submit_done);
this.submitErrorEl = $(configs.elements.form_submit_error);
this.confirmButtonEl = $(configs.elements.form_submit_confirm_button);
this.editButtonEl = $(configs.elements.form_edit_button);
this.reviewContainerEl.hide();
this.submitProgressEl.hide();
this.submitDoneEl.hide();
this.submitErrorEl.hide();
var showForm = function(isShow) {
that.formEl.toggle(isShow);
};
var showReview = function(isShow) {
that.reviewContainerEl.toggle(isShow);
if (isShow) {
compileReviewDetails();
}
window.scrollTo(0,0);
};
var showSubmitProgress = function(isShow) {
that.submitProgressEl.toggle(isShow);
};
var showSubmitDone = function(isShow) {
that.submitDoneEl.toggle(isShow);
if (isShow) {
that.submitErrorEl.toggle(false);
}
};
var showSubmitError = function(isShow) {
that.submitErrorEl.toggle(isShow);
if (isShow) {
that.submitDoneEl.toggle(false);
}
};
var setState = function(state) {
that.submitState = state;
};
var isState = function(state) {
return that.submitState == state;
};
var showRequiredFieldsAsterisk = function() {
var cfg = getFieldsConfig();
$.each(cfg, function(k, o) {
// attempt to get a field's required asterisk element
// the JSON config field key is with "_", but the CSS class uses "-" for part-concatenations
$('.field-'+k.replace('_','-')+' .required').toggle(o.required);
});
};
showRequiredFieldsAsterisk();
var compileReviewDetails = function() {
var html = '';
var cfg = getFieldsConfig();
var formValuesMap = {};
$.each(that.form.serializeArray(), function(i, v) {
if (!v.name) {
return;
}
// Check if value is a multi value
var isMultiValue = v.name.indexOf('[]');
v.name = v.name.replace('[]','');
var label = '';
if (!!cfg[v.name] && !!cfg[v.name]['label']) {
label = cfg[v.name]['label'];
}
if (!label) {
label = v.name.replace(/[^a-zA-Z]/g, ' ');
}
var value = v.value.replace(/[<>]/g, '');
if (!isMultiValue) { // single value
formValuesMap[label] = value;
} else {
// if multi-value
if (typeof formValuesMap[label] == 'undefined') {
formValuesMap[label] = []; // initialize array first
}
formValuesMap[label].push(value); // push value
}
});
$.each(formValuesMap, function(label,value){
html += '
' + label + ': ' + (formValuesMap[label] instanceof Array ? value.join(', ') : value) + '
';
});
that.reviewEl[0].innerHTML = '' + html + '
';
};
var configureValidation = function() {
var cfg = getFieldsConfig();
$.each(configs.validators, function(k, o) {
$.validator.methods[k] = o;
});
var validateConfig = {
rules: {},
messages: {},
submitHandler: that.handleFormSubmit
};
$.each(cfg, function(k, o){
var f = validateConfig.rules[k] = {};
var errorMsg = validateConfig.messages;
if (!!o.required) {
f.required = true;
}
if (!!o.error_messages) {
errorMsg[k] = o.error_messages;
}
if (!!o.email) {
f.email = true;
}
if (!!o.phone) {
f.phone = true;
}
if (!!o.minlength) {
f.minlength = o.minlength;
}
if (!!o.maxlength) {
f.maxlength = o.maxlength;
}
if (!!o.errorMessage && o.errorMessage == 'custom') {
f.errorPlacement = function(error, element) {
$(".error-message-custom-"+k).html(element);
}
}
});
that.form.validate(validateConfig);
};
var ajaxSubmit = function() {
$.ajax({
type: that.form[0].method,
url: that.form[0].action,
data: that.form.serialize(),
dataType: 'json',
success: function(data, textStatus, jqXHR ) {
showReview(false);
showSubmitDone(true);
showSubmitError(false);
showSubmitProgress(false);
// Redirect
if (!!data && !!data.redirect) {
var urlProtocol = window.location.protocol;
var urlHost= window.location.host;
// only if redirect is same host
if (new RegExp('^https?://(www\.)?'+urlHost+'/').test(data.redirect)) {
var urlRedirectForceProtocol = data.redirect.replace(/^\w+:/, urlProtocol);
window.location = urlRedirectForceProtocol;
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
showReview(false);
showSubmitError(true);
showSubmitProgress(false);
}
});
};
this.handleFormSubmit = function() {
if (isState(SubmitState.EDIT)) { // first attempt to submit
setState(SubmitState.REVIEW);
showForm(false);
showReview(true);
}
console.log('form submitted');
};
this.editButtonEl.click(function() {
setState(SubmitState.EDIT);
showForm(true);
showReview(false);
showSubmitError(false);
});
this.confirmButtonEl.click(function() {
setState(SubmitState.CONFIRM);
showSubmitError(false);
showSubmitProgress(true);
showReview(false);
ajaxSubmit();
});
var fillWithTestValues = function() {
var cfg = getFieldsConfig();
$.each(that.form.serializeArray(), function(i, v) {
if (!v.name) {
return;
}
var f = cfg[v.name];
if (!f || !f.test_values) {
return;
}
that.form[0][v.name].value=f.test_values.success;
});
};
var triggerTestValuesIfDoubleKeyPress = function(ev){
if (ev.target != ev.currentTarget) {
return;
}
that.fillWithTestValuesKeyTrigger = '/';
that.fillWithTestValuesKeyTriggerInterval = 1000;
var now = new Date();
if (!that.fillWithTestValuesKeyLastTriggerTime) {
that.fillWithTestValuesKeyLastTriggerTime = now;
return;
}
if (ev.key == that.fillWithTestValuesKeyTrigger) {
var timeSinceLastKeyTrigger = now - that.fillWithTestValuesKeyLastTriggerTime.getTime();
if (timeSinceLastKeyTrigger < that.fillWithTestValuesKeyTriggerInterval) {
fillWithTestValues();
} else {
that.fillWithTestValuesKeyLastTriggerTime = now; // reset
}
}
};
$('body').keypress(triggerTestValuesIfDoubleKeyPress);
configureValidation();
};
var ClaremontEapFormInit = function(fieldConfigJson) {
var claremontFormCtrl = new ClaremontEapFormController({
fields: fieldConfigJson,
elements: {
form: 'form',
form_container: 'form',
form_summary_container: '#form-summary',
form_summary: '#form-summary div',
form_submtit_progress: '#form-submit-in-progress',
form_submit_done: '#form-submit-done',
form_submit_error: '#form-submit-error',
form_submit_confirm_button: '.confirm-button',
form_edit_button: '.edit-button'
},
validators: { // jquery validation-style validator
'phone': function (value, element) {
if (this.optional(element)) {
return true;
}
var cleanValue = value.replace(/\s+/g, '');
return /^(\+?1[\.\-]?)?\(?\d{3}\)?[\-/\.]?\d\d\d[\-/\.]?\d\d\d\d$/.test(cleanValue);
}
}
});
};
$().ready(function() {
ClaremontEapFormInit({
"member_name": {
"required": true,
"label": "Member Full Name",
"is_sender_full_name": true,
"test_values" : {
"success" : "A Tester"
}
},
"member_phone": {
"required": true,
"phone": true,
"label": "Member Phone Number",
"error_messages": {
"phone" : "Please enter a valid phone number"
},
"test_values" : {
"success" : "301-423-1234"
}
},
"member_mailing_address": {
"required": true,
"label": "Member Mailing Address",
"test_values" : {
"success" : "street in Oakland, CA"
}
},
"member_email": {
"required" : false,
"label": "Member Email",
"email": true,
"is_sender_email": true,
"test_values" : {
"success" : "test@gmail.com"
}
},
"member_provider_name": {
"required": false,
"label": "Provider Name",
"test_values" : {
"success" : "An Insurance Provider"
}
},
"employee_name" : {
"required" : false,
"label": "Employee Name",
"test_values" : {
"success" : "An Employer"
}
},
"employer_name": {
"required": false,
"label": "Employer",
"test_values" : {
"success" : "Test Employer LLC"
}
},
"employer_relation": {
"required" : false,
"label":"Relation to Employer",
"test_values" : {
"success" : "test employer relation"
}
},
"grievance": {
"required" : true,
"label": "Nature of Grievance",
"test_values" : {
"success" : "Test grievance"
}
},
"grievance_action": {
"required": false,
"label": "Action You Would Like to Have Happen",
"test_values" : {
"success" : "what to do about grievance..."
}
},
"member_intials": {
"required": true,
"label": "I hereby attest that the above information is true. Enter initials to confirm",
"minlength": 2,
"test_values" : {
"success" : "TTT"
}
},
"member_contact_method": {
"required": false,
"label": "How do you prefer to be contacted by us?",
"errorMessage": "custom",
"test_values": {
"success": "Phone"
}
}
});
});