var ContensisFormsLastElementFocus; var $progressAlert; var ContensisFormsCaptchaVisible = false; var ContensisFormsCurrentFormID = null; var ContensisFormsUploadControlCount = 0; var ContensisFormsUploadIncorrectFileType = 0; var uploader; var correctCaptcha = function (response) { $(".captchaStatus").html(''); }; var hasOwn = Object.prototype.hasOwnProperty; (function ($) { $.contensisForm = { addRules: function (rules) { $.contensisForm.rules = $.contensisForm.rules || []; $.contensisForm.rules.push(rules); }, addGroups: function (groups) { $.contensisForm.groups = $.contensisForm.groups || []; $.contensisForm.groups.push(groups); }, addDefaults: function (defaults) { $.contensisForm.defaults = $.contensisForm.defaults || []; $.contensisForm.defaults.push(defaults); }, addMessages: function (messages) { $.contensisForm.messages = $.contensisForm.messages || []; $.contensisForm.messages.push(messages); }, init: function () { // default items var rules = $.contensisForm.rules; var groups = $.contensisForm.groups; var defaults = $.contensisForm.defaults; var messages = $.contensisForm.messages; var config = { onsubmit: false, focusInvalid: true, errorClass: 'sys_cms-form-error', showErrors: $.contensisForm.showErrors, errorPlacement: $.contensisForm.errorPlacement }; if (rules) { config.rules = $.contensisForm.formatRules(rules); } if (groups) { config.groups = $.contensisForm.formatRules(groups); } $('form').validate(config); if (defaults && registerClearDefaultItem) { for (var i = 0, ilen = defaults.length; i < ilen; i++) { for (var id in defaults[i]) { if (hasOwn.call(defaults[i], id)) { registerClearDefaultItem(id, defaults[i][id]); } } } } if (messages && $.validator) { $.validator.messages = $.validator.messages || {}; for (var i = 0, ilen = messages.length; i < ilen; i++) { for (var id in messages[i]) { if (hasOwn.call(messages[i], id)) { $.validator.messages[id] = messages[i][id]; } } } } }, showErrors: function (errorMap, errorList) { $.each(errorList, function (name, value) { var element = $(value.element); var msgLabel = ''; if ($(element).is(':checkbox') || $(element).is(':radio')) { msgLabel = $(element).parent().parent().prev().text(); } else if ($(element).hasClass('tiny') || $(element).hasClass('address')) { msgLabel = $(element).parent().children(0).children(0).text(); } else if ($(element).hasClass('timeval')) { msgLabel = $(element).parent().parent().prev().text(); } else { msgLabel = $(element).parent().prev().text(); } this.message = msgLabel.replace('*', '') + " " + this.message; this.message = this.message.replace('This field', ''); }); this.defaultShowErrors(); }, errorPlacement: function (error, element) { if (element.rules().mincheckbox > 0) { var $p = $(element).parent().parent(); if ($p.siblings().hasClass('sys_cms-form-error') == false) { if (($p).children('label').length == 0) { error.insertBefore(($p).children(':first')); } } } else if ($(element).hasClass('timeval')) { var $p = $(element).parent().parent(); $p.children('label').remove(); if (($p).children('label').length == 0) { error.insertBefore(($p).children(':first')); } } else if ($(element).is('input[type=radio]')) { var $p = $(element).parent().parent(); if (($p).children('label').length == 0) { error.insertBefore(($p).children(':first')); } } else { error.insertBefore(element); } }, formatRules: function (rules) { var result = {}; for (var i = 0, ilen = rules.length; i < ilen; i++) { for (var id in rules[i]) { if (hasOwn.call(rules[i], id)) { var el = $('#' + id); var name = null; if (el.length > 0) { name = el.attr('name'); } else { el = $('[name$=\"$' + id + '\"]'); if (el.length > 0 && $(el[0]).is(':radio')) { name = $(el[0]).attr('name'); } } result[name || id] = rules[i][id]; } } } return result; } }; $(document).ready(function () { // Override the default validation hander to build the validation summary $.validator.defaults.onfocusout = function (element) { if ($(element).closest('.sys_cms-form-control').length != 0) { // BJ: Looks to see if it's in our forms before running HandleInputChange. HandleInputChange(element); } }; function HandleInputChange(element) { var currentpageId = ReturnPageId($(element).parents("li").attr('id')); var formID = ReturnFormId($(element).parents("ul").attr('id')).split("-")[1]; ShowValidationSummary(currentpageId, formID, false); } // Override default error message for url $.validator.messages.url = $('#hdValUrl' + $('[id*=hdValUrl]').attr('id').replace('hdValUrl', '')).val(); // add custom val method for filetype value $.validator.addMethod("filetypeallowed", function (value, element, param) { var paramSplit = param.split(","); if (value != "") { for (i = 0; i < paramSplit.length; i++) { if (value.toLowerCase().indexOf("." + $.trim(paramSplit[i])) > -1) { return true; } } } else { // let the check pass because any required fields will be handled with the required rule return true; } return false; }, $.validator.format($('#hdValFileType' + $('[id*=hdValFileType]').attr('id').replace('hdValFileType', '')).val())); // add custom val method for duplicate value $.validator.addMethod("isdup", function (value, element, param) { if (!param) { return true; } return false; }, $.validator.format($('#hdValIsDuplicate' + $('[id*=hdValIsDuplicate]').attr('id').replace('hdValIsDuplicate', '')).val())); // add custom val method for integer less than $.validator.addMethod("intlessthan", function (value, element, param) { if (parseInt(value) < parseInt(param)) { return true; } return false; }, $.validator.format($('#hdValLessThan' + $('[id*=hdValLessThan]').attr('id').replace('hdValLessThan', '')).val())); // add custom val method for minword count $.validator.addMethod("minwords", function (value, element, param) { var wordArray = value.split(/[\s\.\?]+/); if (wordArray.length >= param) { return true; } return false; }, $.validator.format($('#hdValMinWords' + $('[id*=hdValMinWords]').attr('id').replace('hdValMinWords', '')).val())); // add custom val method for maxword count $.validator.addMethod("maxwords", function (value, element, param) { var wordArray = value.split(/[\s\.\?]+/); if (wordArray.length <= param) { return true; } return false; }, $.validator.format($('#hdValMaxWords' + $('[id*=hdValMaxWords]').attr('id').replace('hdValMaxWords', '')).val())); // add custom val method for min checkboxes checked $.validator.addMethod("mincheckbox", function (value, element, param) { var $p = $(element).parent().parent(); var selected = $p.find('input[type=checkbox]:checked').length; if (selected >= param) { $p.children().children().removeClass('sys_cms-form-error'); $p.siblings('.sys_cms-form-error').remove(); return true; } $p.children('input[type=checkbox]').addClass('sys_cms-form-error'); return false; }, $.validator.format($('#hdValMinCheckbox' + $('[id*=hdValMinCheckbox]').attr('id').replace('hdValMinCheckbox', '')).val())); // shows or hides Other controls for radio elements $('.sys_cms-form-control div ul li div span input').click(function () { if ($(this).is('input[type=radio]')) { var parentDiv = $(this).parent().parent(); if ($(this).val() == 'Other') { $(parentDiv).children('span.sys_choices_other').find('.sys_otherlabel').show(); $(parentDiv).children('span.sys_choices_other').find('.sys_otherlabel').siblings().last().show(); $(parentDiv).children('span.sys_choices_other').find('.sys_otherlabel').siblings().last().focus(); } else { $(parentDiv).children('span.sys_choices_other').find('.sys_otherlabel').hide(); $(parentDiv).children('span.sys_choices_other').find('.sys_otherlabel').siblings().last().hide(); $(parentDiv).children('span.sys_choices_other').find('.sys_otherlabel').siblings().last().blur(); } } }); $.fn.randomize = function (childElem) { return this.each(function () { var $this = $(this); var elems = $this.children(childElem); var parent = $this.parent(); var modCount = 0; if ($(parent).hasClass('sys_threecolumns')) { modCount = 3; } else if ($(parent).hasClass('sys_twocolumns')) { modCount = 2; } elems.sort(function () { return (Math.round(Math.random()) - 0.5); }); $this.remove(childElem); for (var i = 0; i < elems.length; i++) { $(elems[i]).removeAttr('class'); if ((i % modCount) == 0) { $(elems[i]).addClass('sys_boxclearer'); } $this.append(elems[i]); } }); }; function SetInstructionsClass() { //console.warn('set instructions'); if ($('.sys_cms-form-body').find('[id*=instructions]').length > 0) { $('.sys_cms-form-control').addClass('sys_showinstructions'); } else { $('.sys_cms-form-control').removeClass('sys_showinstructions'); } } SetInstructionsClass(); function CheckLoadSingleReCaptcha() { var hdCaptcha = $('[id*=hdCaptchaVersion]'); if (hdCaptcha.length) { var formID = ReturnFormIdFromCaptcha($(hdCaptcha).attr('id')); var checkCaptcha = hdCaptcha.val(); if (checkCaptcha) { displayFormCaptcha(formID); } } } CheckLoadSingleReCaptcha(); $('.sys_cms-form-page').bind('keydown', function (e) { var key = e.which || e.keyCode; if (key === 13 && !acceptsEnter(e.target)) { var nextBtn = $('[id*=btnNext]', this); if (nextBtn.length) { nextBtn.click(); return false; } var submitBtn = $('[id*=btnSubmitForm]', this); if (submitBtn.length) { submitBtn.click(); return false; } } }); function acceptsEnter(element) { if (isDisabled(element)) { return false; } if (!isVisible(element)) { return false; } if (isAnchorWithhref(element)) { return true; } if (element.hasAttribute('contenteditable')) { return true; } let nodeName = element.nodeName.toLowerCase(); if (nodeName === 'button' || nodeName === 'textarea') { return true; } if (nodeName === 'input') { let type = element.getAttribute('type'); if (type && ((type.toLowerCase() === 'submit') || (type.toLowerCase() === 'reset'))) { return true; } } return false; } function isDisabled(element) { return element.hasAttribute('disabled'); } function isVisible(element) { return hasGeometry(element) && getComputedStyle(element).visibility === 'visible'; } function hasGeometry(element) { return !!(element.offsetWidth || element.offsetHeight || (typeof element.getClientRects === 'function' && element.getClientRects().length)); } function isAnchorWithhref(element) { return isAnchorElement(element) && element.hasAttribute('href'); } function isAnchorElement(element) { return element.nodeName.toLowerCase() === 'a'; } $("input,select,textarea").focus(function () { var formID = ReturnFormIdFromControl($(this).attr('id')); var checkCaptcha = $('#hdCaptchaVersion' + formID).val(); if (checkCaptcha) { if (formID != ContensisFormsCurrentFormID && ContensisFormsCurrentFormID != null) { ContensisFormsCaptchaVisible = false; } if (!ContensisFormsCaptchaVisible) { displayFormCaptcha(formID); } } //$('[id*=instructions]').hide(); // [Added by iG 16/04/2012] - Hide all of the instructions first. Ticketid: 13259 if ($('.sys_cms-form-control').hasClass('sys_showinstructions')) { ContensisFormsLastElementFocus = null; ContensisFormsLastElementFocus = $(this); var formelementid = ReturnItemId($(this).attr('id')); $('#instructions_' + formelementid + '-' + formID).show(); //console.warn('focus : ' + '#instructions_' + formelementid + '-' + formID); //console.warn('formid : ' + formID); //console.warn('formelementid : ' + formelementid); } }); function displayFormCaptcha(formID) { ContensisFormsCaptchaVisible = true; ContensisFormsCurrentFormID = formID; } $("input,select,textarea").blur(function () { var formID = ReturnFormIdFromControl($(this).attr('id')); if ($('.sys_cms-form-control').hasClass('sys_showinstructions')) { ContensisFormsLastElementFocus = null; var formelementid = ReturnItemId($(this).attr('id')); $('#instructions_' + formelementid + '-' + formID).hide(); } }); $('.sys_cms-form-body li').hover( function () { //if ($(this).find('[id*=instructions]').length > 0 && ContensisFormsLastElementFocus == null) { if ($(this).find('[id*=instructions]').length > 0) { $(this).find('[id*=instructions]').show(); } }, function () { //if ($(this).find('[id*=instructions]').length > 0 && ContensisFormsLastElementFocus == null) { if ($(this).find('[id*=instructions]').length > 0) { $(this).find('[id*=instructions]').hide(); } }); $('.sys_cms-form-body li input.required, textarea.required, select.required').each(function () { if ($(this).hasClass('timeval') || $(this).hasClass('tiny') || $(this).hasClass('address')) { if ($(this).parent().parent().prev('.sys_legend').children().length == 0) { $(this).parent().parent().prev('.sys_legend').append('*'); } } else { $(this).parent().prev('label').append('*'); } }); $('.sys_cms-form-body li input.filerequired').each(function () { $(this).parent().prev('label').append('*'); }); $('.sys_cms-form-body li input.checkrequired, input.radiorequired').each(function () { if ($(this).parent().parent().prev('.sys_legend').children().length == 0) { $(this).parent().parent().prev('.sys_legend').append('*'); } }); $('div.random').randomize('span'); $('.nodups').blur(function () { return validateDups(this, true); }); function validateDups(el, async) { var formelementid = ReturnItemId($(el).attr('id')); var formID = ReturnFormIdFromControl($(el).attr('id')); var val = $(el).val(); ContensisFormsLastElementFocus = null; ContensisFormsLastElementFocus = $(el); CheckDuplicate(formID, formelementid, val, async); return false; } function ReturnPageId(objId) { var IdArray = objId.split('_'); return IdArray[1]; } function ReturnItemId(objId) { var IdArray = objId.split('_'); var notNumber = isNaN(IdArray[1]); if (!notNumber) { // so is a number return IdArray[1]; } else { var value = IdArray[1].split('-'); return value[0]; } } function ReturnFormId(objId) { var IdArray = objId.split('_'); return IdArray[1]; } function ReturnFormIdFromControl(objId) { var IdArray = objId.split('-'); return IdArray[1]; } function ReturnFormIdFromCaptcha(objId) { return objId.replace('hdCaptchaVersion', ''); } function FormHasUploadElement(formID) { var hasForm = false; $('#formwrapperJS' + formID).find('.formsuploader').each(function (index) { if ($(this).val() != "") { hasForm = true; } }); return hasForm; } function scrollToTopOfForm(formId) { try { var form = $('#formwrapperJS' + formId); var formTop = form.offset().top; var windowScrollTop = $(window).scrollTop(); var windowHeight = $(window).innerHeight(); if (windowScrollTop > formTop || ((windowScrollTop + windowHeight) < formTop)) { $(window).scrollTop(formTop); } } catch (e) { } } $('[id*=btnSubmitForm]').click(function () { var formID = ReturnFormId($(this).attr('id')); var pageID = $(this).parent().parent().attr('id'); var currentpageId = ReturnPageId(pageID).split("-")[0]; var formIsValid = true; var invalidCount = 0; var thisForm = $('form#form1, form#Form1, form#aspnetForm'); var formHasUploadControl = FormHasUploadElement(formID); $(this).parent().parent().find("input, select, textarea").each(function (index) { if (typeof (thisForm.validate().element($(this))) !== 'undefined') { if ($(this).hasClass('formsuploader')) { if ($(this).val() != "") { formHasUploadControl = true; } } formIsValid = thisForm.validate().element($(this)); if (!formIsValid) invalidCount++; //if (!formIsValid) // break the loop if we fail the validation // return false; } }); if (invalidCount > 0) { formIsValid = false; ShowValidationSummary(currentpageId, formID, true); } if (formIsValid) { $("#formvalidationsummary_" + currentpageId + "-" + formID).remove(); $(this).attr("disabled", "disabled"); SaveFormResponse(formID, pageID, formHasUploadControl); } return false; }); $('[id*=btnNext]').click(function () { var currentpageId = parseInt(ReturnPageId($(this).attr('id'))); var formID = ReturnFormIdFromControl($(this).attr('id')); var nextpageId = CheckPageRule(formID, currentpageId); if (ValidatePage(formID, currentpageId, nextpageId)) { $('#formpage_' + currentpageId + '-' + formID).toggle(); if (nextpageId == null) { nextpageId = currentpageId + 1; } if (currentpageId == 0) { $('#hdPageNav' + formID).val('0'); } else { var pageSequence = []; pageSequence = ReturnPageSequenceArray(formID); pageSequence.push(currentpageId); $('#hdPageNav' + formID).val(pageSequence.join(",")); } $('#formpage_' + nextpageId + '-' + formID).toggle(); $("#formvalidationsummary_" + nextpageId + "-" + formID).show(); scrollToTopOfForm(formID); } return false; }); $('[id*=btnBack]').click(function () { var currentpageId = parseInt(ReturnPageId($(this).attr('id'))); var formID = ReturnFormIdFromControl($(this).attr('id')); $("#formvalidationsummary_" + currentpageId + "-" + formID).hide(); var prevPageId; var pageSequence = []; pageSequence = ReturnPageSequenceArray(formID); pageSequence.reverse(); if (pageSequence[0] == currentpageId) { pageSequence.splice(0, 1); } prevPageId = pageSequence[0]; pageSequence.reverse(); $('#hdPageNav' + formID).val(pageSequence.join(",")); $("#formpage_" + currentpageId + '-' + formID).toggle(); $("#formpage_" + prevPageId + '-' + formID).toggle(); scrollToTopOfForm(formID); return false; }); function ReturnPageSequenceArray(formID) { return $('#hdPageNav' + formID).val().split(","); } function PageIsInSequence(formID, currentPageId) { var pageSequence = ReturnPageSequenceArray(formID); for (var i = 0; i < pageSequence.length; i++) { var pageId = pageSequence[i]; if (pageId == currentPageId) { return true; break; } } return false; } function ValidatePage(formID, currentpageId, nextpageId) { var objCurrentPage = $('#formpage_' + currentpageId + '-' + formID); var objNextPage = $('#formpage_' + nextpageId + '-' + formID); var invalidCount = 0; var pageIsValid = true; var thisForm = $('form#form1, form#Form1, form#aspnetForm'); $(objCurrentPage).find("input, select, textarea").each(function (index) { if ($(this).is('.nodups')) { validateDups(this, false); } if (typeof (thisForm.validate().element($(this))) !== 'undefined') { pageIsValid = thisForm.validate().element($(this)); if (!pageIsValid) invalidCount++; //if (!pageIsValid) // break the loop if we fail the validation // return false; } }); if (invalidCount > 0) { pageIsValid = false; ShowValidationSummary(currentpageId, formID, true); } if (pageIsValid) { $("#formvalidationsummary_" + currentpageId + "-" + formID).remove(); return true; } return false; } $.contensisForm.init(); }); var originalDocumentTitle = document.title; function ShowValidationSummary(pageId, formId, scrollToError) { var summaryId = 'formvalidationsummary_' + pageId + "-" + formId; var summaryTitleId = summaryId + '-title'; //aria-labelledby="error-summary-title" $('#' + summaryId).remove(); var validationSummary = $(''); var validationSummaryDetails = ""; var formPageId = "#formpage_" + pageId + "-" + formId; $(formPageId).find(".sys_cms-form-error").each(function (index) { if (!$(this).is("input") && !$(this).is("textarea") && $(this).is(":visible") && !$(this).is("select")) { var text = $(this).text(); var anchorName = $(this).attr('for'); validationSummaryDetails += '
  • ' + $(this).text() + '
  • '; } }); if (validationSummaryDetails) { $(validationSummaryDetails).appendTo(validationSummary); $(formPageId).before(validationSummary); if (scrollToError) { var scrollElement = $('html, body'); var summaryTop = $('#' + summaryId).offset().top; scrollElement.animate({ scrollTop: summaryTop }, 1000); $('#' + summaryId)[0].focus(); } document.title = 'Error: ' + originalDocumentTitle; } else { document.title = originalDocumentTitle; } } function ReturnOperatorResult(eleValue, operatorType, operatorValue) { var result = false; switch (operatorType) { case 'is': result = (eleValue == operatorValue) ? true : false; break; case 'is not': result = (eleValue != operatorValue) ? true : false; break; case 'contains': result = (eleValue.indexOf(operatorValue) > -1) ? true : false; break; case 'does not contain': result = (eleValue.indexOf(operatorValue) == -1) ? true : false; break; case 'begins with': result = (eleValue.substring(0, operatorValue.length) == operatorValue) ? true : false; break; case 'ends with': result = (eleValue.match(new RegExp(operatorValue + '$', 'ig'))) ? true : false; break; case 'is equal to': result = (parseInt(eleValue) == parseInt(operatorValue)) ? true : false; break; case 'is greater than': result = (parseInt(eleValue) > parseInt(operatorValue)) ? true : false; break; case 'is less than': result = (parseInt(eleValue) < parseInt(operatorValue)) ? true : false; break; } return result; } function CheckPageRule(formId, pageId) { var nextPageId = null; var formPageRulesString = $("#hdPageRules" + formId).val(); var formPageRulesJson = $.parseJSON(formPageRulesString); var formPageRules = $.parseJSON(formPageRulesJson.FormPageRules); // Loop through each rule for (i = 0; i < formPageRules.length; i++) { var pagerule = formPageRules[i]; if (parseInt(pagerule.PageNumber) == pageId) { var ruleResults = []; // Loop through each condition of the rule for (j = 0; j < formPageRules[i].RuleConditions.length; j++) { var passedCondition = false; var ruleCondition = formPageRules[i].RuleConditions[j]; var eleValue; var valueToCheck = ruleCondition.OperatorValue; if (ruleCondition.ListItemIndex > -1) { var checkedState = $('[id*=ctrl_' + ruleCondition.FormElementId + '_' + ruleCondition.ListItemIndex + '-' + formId + ']').is(':checked'); if (checkedState) { eleValue = $('[id*=ctrl_' + ruleCondition.FormElementId + '_' + ruleCondition.ListItemIndex + '-' + formId + ']').val(); if (ruleCondition.OperatorValue == "checked") { valueToCheck = ruleCondition.FormElementName; } } else { eleValue = null; } } else { eleValue = $('input[name*=ctrl_' + ruleCondition.FormElementId + '-' + formId + ']:checked').val(); if (eleValue == null) { eleValue = $('[id*=ctrl_' + ruleCondition.FormElementId + '-' + formId + ']').val(); } } if (eleValue == null) { eleValue = $('[id*=ctrl_' + ruleCondition.FormElementId + '-' + formId + ']').val(); } passedCondition = ReturnOperatorResult(eleValue, ruleCondition.OperatorType, valueToCheck); // Log the result in an array to look at later var conditionResult = { "Id": ruleCondition.ConditionId, "Result": passedCondition, "Operation": ruleCondition.ConditionType } ruleResults.push(conditionResult); } var orArray = []; // Loop through the results for (var x = 0, len = ruleResults.length; x < len; x++) { var result = ruleResults[x]; // The first result will not have a logical operator on it if (orArray.length == 0) { orArray.push(result.Result); } else { // If the result uses a logical OR add to the OR array if (result.Operation === "OR") { orArray.push(result.Result); } else { // Otherwise, AND with the latest entry on the array orArray[orArray.length - 1] = orArray[orArray.length - 1] & result.Result; } } } // Now we should have a array, each of which are OR's. So we just need to loop through the array until we fine a true. for (var r = 0, len = orArray.length; r < len; r++) { var orValue = orArray[r]; if (orValue == true) { // [b.jenkins 14/01/2015 ] We could return here, however if we did we'd change the behaviour so that the first rule that matches 'wins' and stops all further processing of rules. However introducing this now would be a change of functionality, and we'd need to add UX on the CMS to re-order the rules. So this is one to revisit. nextPageId = parseInt(pagerule.ResultPageId); } } } } return nextPageId; } function CheckDuplicate(formID, formelementId, value, async) { var urlString = "/REST/UI/FormsModule/CheckDuplicates"; var dataString = '{"FormId": ' + parseInt(formID) + ', "FormElementId": ' + parseInt(formelementId) + ', "ResponseValue": "' + value + '"}'; ShowProgressAlert('Please wait...', false, formID); $.ajax({ url: urlString, type: "POST", cache: false, contentType: "application/json; charset=utf-8", data: dataString, dataType: "text json", success: function (data) { CheckDuplicateSucceeded(formID, formelementId, data); }, error: function (data) { CheckDuplicateFailed(formID, data); }, async: async }); return false; } function CheckDuplicateSucceeded(formID, formelementId, result) { var dupCheckFailedElement = $('[id*=ctrl_' + formelementId + ']'); HideProgressAlert(); var obj = $.parseJSON(result.CheckDuplicatesResult); if (obj.Status == "True") { var thisForm = $('form#form1, form#Form1, form#aspnetForm'); $(dupCheckFailedElement).rules("add", { isdup: true }); if (!$(thisForm).validate().element($(dupCheckFailedElement))) { // Re-validate this element, show the label if still invalid $(dupCheckFailedElement).siblings('.error').show(); } } else { $(dupCheckFailedElement).rules("remove", "isdup"); dupCheckFailedElement = null; } } function CheckDuplicateFailed(formID, result) { ShowProgressAlert('Please try again...', true, formID); } function CleanFormPostArray(allElements, formID) { var allElementsCleaned = []; $.each(allElements, function (i, field) { if (field.name != 'ScriptManager_HiddenField' && field.name != '__EVENTTARGET' && field.name != '__ContensisDialogueState' && field.name != '__EVENTARGUMENT' && field.name != '__VIEWSTATE' && field.name != '__EVENTVALIDATION' && field.name != 'SearchQueryControl_SearchTextBox' && field.name.indexOf('hdPageContent') == -1) { if (field.name.indexOf(formID) > -1 && field.name.indexOf('hdCurrentProject') == -1 && field.name.indexOf('hdPageNav') == -1) { var parts = field.name.split('$'); field.name = parts[parts.length - 1]; allElementsCleaned.push(field); } } }); return allElementsCleaned; } function IncludeFormUploadedFilesNames(formID, dataToPost) { $("#formwrapperJS" + formID).find(".formsuploader").each(function (index) { if ($(this).val() != "") { var fileName = $(this).val().substring($(this).val().lastIndexOf("\\") + 1); var file = { name: "file_" + $(this).attr("id"), value: fileName }; dataToPost.push(file); } }); return dataToPost; } function DeleteRadioButtons(data, idToDelete) { var index = FindRadioButton(data, idToDelete); // if index is -1 then don't splice anything // as wanted values will be removed if (index !== -1) { data.splice(index, 1); } return data; } function FindRadioButton(data, idToDelete) { for (i = 0; i < data.length; i++) { if (data[i].name == idToDelete) { return i; } } return -1; } function AddRadioButtons(data) { var form = $("form"); form.find('input:radio:checked').each(function () { var idSplit = this.id.split("-"); var fId = idSplit[idSplit.length - 1]; var idToDelete = this.name; data = DeleteRadioButtons(data, idToDelete); var newName = this.name + "-" + fId; var value = this.value; if (value === 'Other') { var other = form.find('[id$="-' + fId + '_other"]'); value = other.val(); } data[data.length] = { "name": newName, "value": value } }); return data; } function SaveFormResponse(formID, pageID, formHasUploadControl) { $('.errormsg').remove(); var formActionUrl = $('#hdActionUrl' + formID).val(), pageContentID = $('#hdPageContent' + formID).val(), currentProjectId = $('#hdCurrentProject' + formID).val(), publicKey = $('#hdCaptchaPublicKey' + formID).val(), captchaVersion = $('#hdCaptchaVersion' + formID).val(); var dataToPost = CleanFormPostArray($("form").serializeArray(), formID); dataToPost = IncludeFormUploadedFilesNames(formID, dataToPost); dataToPost = AddRadioButtons(dataToPost); function postForm(captchaResponse) { ShowProgressAlert('Sending...', false, formID); if (captchaResponse) { dataToPost[dataToPost.length] = { name: "captchaResponse", value: '{ Response: "' + captchaResponse + '", CurrentProjectId: "' + currentProjectId + '"}' }; } $.ajax({ url: formActionUrl + formID + "/" + pageContentID, type: "POST", data: dataToPost, success: function (data) { SaveSucceeded(data, formID, pageID, formHasUploadControl, dataToPost) }, error: function (data) { SaveFailed(data, formID) } }); } function invalidCaptcha() { $("#captchaStatus_" + formID).html("Your recaptcha is incorrect. Please try again"); $('[id*=btnSubmitForm]').removeAttr('disabled'); } if (captchaVersion) { if (captchaVersion === '3') { grecaptcha.ready(function () { grecaptcha.execute(publicKey, { action: 'submit' }).then(function (response) { if (!response) { invalidCaptcha(); } else { postForm(response); } }, invalidCaptcha); }); } else { var response = grecaptcha.getResponse(); if (!response) { invalidCaptcha(); } else { postForm(response); } } } else { postForm(null); } return false; } function SaveSucceeded(result, formID, pageID, formHasUploadControl, dataToPost) { if (result.success) { if (formHasUploadControl) { TriggerUploads(formID, pageID, result, dataToPost); } else { if (result.action === 'DisplayMessage') { ProcessMessageAction(formID, pageID, result); } else if (result.action === 'Redirect') { ProcessRedirect(formID, pageID, result); } } } else { ShowErrorMsg(formID); } } function ShowErrorMsg(formID) { var errormsg = $('
    An error has occurred while processing your request. Please, try again later.
    '); $('#formwrapperJS' + formID + '.sys_cms-form-control').append(errormsg); } function SaveFailed(result, formID) { HideProgressAlert(); $('[id*=btnSubmitForm]').removeAttr('disabled'); ShowErrorMsg(formID); } function getBaseUrl() { var url = window.location.href; if (url.toLowerCase().indexOf('cmsengine') > -1) { return "/"; } else { return ""; } } function ShowProgressAlert(msg, isFade, formID) { var wrapperOffset = $('#formwrapperJS' + formID).offset(); var top = wrapperOffset.top + ($('#formwrapperJS' + formID).height() / 2); var left = wrapperOffset.left + ($('#formwrapperJS' + formID).width() / 2); $progressAlert = $('
    ') .addClass('sys_form-progress') .css('top', top - 21) .css('left', left - 87) .html(msg); $('body').append($progressAlert); $progressAlert.fadeIn(); if (isFade) { $progressAlert.fadeOut('slow'); } } function HideProgressAlert() { $progressAlert.remove(); } function TriggerUploads(formID, pageID, formPostResponse, dataToPost) { var formPostID = formPostResponse.formPostId; $('#formwrapperJS' + formID).find('.formsuploader').each(function (index) { if ($(this).val() != "") { ContensisFormsUploadControlCount++; var elementID = $(this).attr('id'); var IdArray = elementID.split('_'); var formIdArray = IdArray[1].split('-'); var formElementID = formIdArray[0]; var formVersionID = formIdArray[1]; DoFileUpload(formID, pageID, elementID, formPostID, formElementID, formVersionID, formPostResponse, dataToPost); } }); } function DoFileUpload(formId, pageId, fileControlId, formPostId, formElementId, formVersionId, response, dataToPost) { var isPreviewMode = $(".sys_form-preview").length; $.ajaxFileUpload({ url: '/REST/UI/FormsModule/UploadFile', secureuri: false, fileElementId: fileControlId, previewMode: isPreviewMode, dataType: 'text', data: { formPostID: formPostId, formElementID: formElementId, formVersionID: formVersionId }, success: function (dataReturn, status) { var obj = null; if (dataReturn) { try { obj = $.parseJSON(dataReturn); } catch (e) { obj = null; } } var message = response.message; if (obj && obj.error) { ContensisFormsUploadIncorrectFileType++; if (response.redirect && (response.message === response.redirect.url)) { message = ''; } } var areAllUploadsComplete = CheckAllUploadsComplete(formId, pageId, message, formPostId, formVersionId, dataToPost); if (areAllUploadsComplete && response.action === 'Redirect') { ProcessRedirect(formId, pageId, response); } }, error: function (data, status, e) { ContensisFormsUploadIncorrectFileType++; var areAllUploadsComplete = CheckAllUploadsComplete(formId, pageId, '', formPostId, formVersionId, dataToPost); if (areAllUploadsComplete && response.action === 'Redirect') { ProcessRedirect(formId, pageId, response); } } }); } function CheckAllUploadsComplete(formID, pageID, message, formPostId, formVersionId, dataToPost) { // make the Upload response resemble the FormPost response var response = { message: message }; ContensisFormsUploadControlCount = ContensisFormsUploadControlCount - 1; if (ContensisFormsUploadControlCount <= 0) { // do notification stuff here var url = "/REST/UI/FormsModule/sendnotification/"; $.ajax({ url: url + formVersionId + "/" + formPostId, type: "POST", data: dataToPost }); ProcessMessageAction(formID, pageID, response); return true; } else { return false; } } function ProcessMessageAction(formId, pageId, response) { $('#sys_cms-form-confirmation_' + formId).show(0); //BJ: Added as it was requested that the DIV's are hidden, as designers are limited CSS wise (DEV-737) if (ContensisFormsUploadIncorrectFileType > 0) { response.message = response.message + '
    You attempted to upload a type of file that is not supported.'; } $('#' + pageId + '').hide(); $('#sys_cms-form-confirmation_' + formId + ' .sys_cms-form-confirmation-content').append(response.message.replace(/\n/g, '
    ')); ContensisFormsUploadIncorrectFileType = 0; HideProgressAlert(); } function ProcessRedirect(formId, pageId, response) { var redirect = response.redirect; switch (redirect.method) { case 'POST': var postData = {}; if (typeof redirect.data === 'string') { postData = QueryStringToJSON(redirect.data); } else if (typeof redirect.data === 'object' && !redirect.data) { postData = redirect.data; } else if (typeof redirect.body === 'string') { postData = QueryStringToJSON(redirect.body); } $.redirectPost(redirect.url, postData); break; default: // GET etc window.location = redirect.url; break; } } function QueryStringToJSON(data) { var pairs = (data || location.search.slice(1)).split('&'); var result = {}; pairs.forEach(function (pair) { pair = pair.split('='); result[pair[0]] = decodeURIComponent(pair[1] || ''); }); return JSON.parse(JSON.stringify(result)); } $.extend({ redirectPost: function (location, args) { var form = ''; $.each(args, function (key, value) { value = value.split('"').join('\"') form += ''; }); $('
    ' + form + '
    ').appendTo($(document.body)).submit(); } }); })(jQuery);