/* methods and properties for the A.wesome Framework A.methods - Getting Content get() - private function used for retrieving content from view.php getTab(tabName, value) - uses get to retrieve content for a tab getHTML(func, value, div, customFunc) - uses get to retrieve HTML content getLb(func, value) - uses get to retrieve content for a LB getInputData(func, value, fieldId, customFunc) - pushes the result into a textarea, input text/hidden field, or select. If select, the result needs to be key/value JSON string getResponse(func, value, customFunc) - does nothing with the result. customFunc defines what happens with the result. - Setting Content push() - private function for setting content in edit.php set(func, data, customFunc) - uses push to set data setAndGetTab(func, data, tabValue) - uses push and retrieves last used tab after setting data setResponse(func, value, customFunc) - does nothing with the result. customFunc defines what happens with the result. - Setting Name Var setName(name) - used to set the 'Name' parameter until it is reset again setTempName(tempName) - sets the 'Name' parameter only for one ajax call refreshName() - private function used to clear the A.tempName variable - Lightbox commands showLb(isFluid) - shows the lightbox. Fluid means that the lightbox will extend the width to the right if necessary hideLb() - hides the lightbox - TinyMCE Commands initEditor() - creates the necessary tinymce instances if any (don't forget to use the class 'editor') submitEditor() - if there are tinymce instances, it will pull the content into the original textareas shutdownEditor() - destroys any tinymce instances - Setting URL params parseValues(value) - private function that creates the url string to be inserted into get() setValues(data) - private function that creates the url string to be inserted into push(), can be formId, object, or single value (must be int) - Misc Methods editText() - creates editable spans with the class of editText and data-json attributes. Kinda complicated :) addError(msg) - sends error message to the console if the browser has a console - Boolean Methods isDefined(data) - checks if var is defined isString(data) - checks if var is string isInt(data) - checks if var is int isObject(data) - checks if var is object hasComma(string) - checks if string has comma in it A Properties and other important variables name - (string) the name used for executing any following function. Similar to a controller tabName - (string) same as name (dynamically set) func - (string) the type of function to execute for the controller value - (string) values passed into view.php or edit.php callObj - (object) values passed from child functions into the parent functions { name - . func - .. value - these are values that are compiled from A.parseValues and A.setValues div - (string) if useDiv then it will push the data into this divs id, customFunc - (function) a function to execute after the ajax is completed. useDiv - .. } useDiv - (boolean) If the results are being pushed into a div (typically HTML) tempName : '', skipNotify : (boolean) Used for skipping the use of the notifications class A special classes editor - this should be applied to all textareas where TinyMCE is desired input.datePicker - this is applied only to input[type="text"] and is for toggling the datepicker. span.tooltipTrigger - initiate a tooltip on a span (format is Show Text
Hover Text
) span.editText - used to dynamically edit something that looks like text there other attributes necessary for this to work. Go find them [span].showHide - use this on the span for show/hide archived or show/hide inactive links. F.methods validate(formId) - validates a form if assigned a class of 'v' getStates(countryId, includeEmpty, emptyTopOptionText) - gets the states for a particular country and sets them in #state_id dropdown. moveOptions(theSelFromId, theSelToId) - if there are two multiselects, then this moves an option from one to the other handlePaste(event) - Ported the handlePaste function from jquery-admin-functions.js to here */ var A = { tabName : '', name : '', func : '', value : '', callObj : {}, useDiv : true, tempName : '', tempDir : '', lbTempName : '', lbTempDir : '', skipNotify : false, params : {}, postParams : {}, largeParam : {}, xhrLog : [], // Main ajax call for gets get : function() { var o = A.callObj; if(!A.isDefined(o.customFunc) && A.isFunction(o.div)) { o.customFunc = o.div; o.div = ''; } Timeout.renew(); if(A.useDiv) A.div = o.div; if(!A.useDiv) A.fieldId = o.fieldId; if(!o.name || !o.func) { A.addError('A name and func must be present to run a get(). name: ' + o.name + ', func: ' + o.func); return false; } var extraParams = A.paramToString(); var $loading = $('div.loading'); $loading.fadeIn(200); var domainId = A.isDefined(A.domainId) ? '&domain_id=' + A.domainId : ''; var tempDir = A.lbTempDir.length > 0 ? A.lbTempDir : ''; tempDir = A.tempDir != '' && A.isDefined(A.tempDir) ? A.tempDir : tempDir; var xhr = $.get(tempDir + 'view.php', 'n=' + o.name + '&f=' + o.func + extraParams + domainId + (typeof(o.value) != 'undefined' ? '&' + o.value : ''), function(result) { if(typeof(result) == 'string' && result.indexOf('Session Expired. Please logout and login again') != -1) { if(alert('You have remained inactive for a period of time. Please login again to refresh your user session')) { var forceLogout = window.location = '/?logout=1&return_url=' + encodeURIComponent(document.location.pathname + document.location.search); return false; } } // Shutdown any active instances of tinymce if(!o.isResponse) A.shutdownEditor(o.div); // If the div should be populated if(o.useDiv == true) { if(result == '') { A.addError('There wasn\'t any HTML to fetch. name: ' + o.name + ' func: ' + o.func + ' value: ' + o.value); } if(o.div) { var $div = $('#' + o.div); $div.html(result); // If there are any archive toggles on the page if($div.find('.showHide').length) { $div.find('.showHide').parent().on('click', function() { $t = $(this).find('.showHide'); if($t.text() == 'show') $t.text('hide'); else $t.text('show'); }); } if(A.isDefined(jQuery.fn.placeholder)) $div.find('input,textarea').placeholder(); V.init($div); } // If there is a datepicker on the page if(A.isDefined(jQuery.fn.simpleDatepicker)) { if($('.datePicker.date').length > 0) { $('.datePicker').simpleDatepicker({startdate : 2008, format : 'd-M-Y'}); } else { $('.datePicker').simpleDatepicker({startdate : 2008}); } } // If tooltips are on the page if($(result).find('.tooltipTrigger').length) Tooltip.init(); // If there are editText classes that need to be editable if($(result).find('span.editText').length) setTimeout(function() { A.editText(); }, 100); } else { if(result == '') { A.addError('There wasn\'t anything to fetch. name: ' + o.name + ' func: ' + o.func + ' value: ' + o.value); } if(o.fieldId) { var $field = $('#' + o.fieldId); var tag = $field.prop('tagName'); var type = $field.prop('type'); if(tag == 'TEXTAREA' || (tag == 'INPUT' && (type.toUpperCase() == 'HIDDEN' || type == 'TEXT'))) { $field.val(result); } else if(tag == 'SELECT') { var obj = $.parseJSON(result); $field.empty(); for(var i in obj) { $field.append(''); } } } // if(o.isResponse && typeof(result) == 'string') { // var possibleJSON = result.replace(/\<(script)[\s\S]*\<\/(script)\>/g, ""); // var firstChar = possibleJSON.slice(0,1), checkChar = firstChar == "[" ? "]" : "}", lastChar = possibleJSON.slice(-1), extraJavascript; // if((firstChar == "[" || firstChar == "{") && checkChar == lastChar) { // extraJavascript = result.replace(/[\s\S]*\([\s\S]+)\<\/script\>/, "$1"); // result.replace(/\
Peak Memory: [0-9\.]+ MB\<\/div\>/, ""); // try{eval(extraJavascript);} catch(e) {} // result = $.parseJSON(possibleJSON); // } else { // extraJavascript = result.replace(/[\s\S]*\([\s\S]+)\<\/script\>/, "$1"); // result.replace(/\
Peak Memory: [0-9\.]+ MB\<\/div\>/, ""); // try{eval(extraJavascript);} catch(e) {} // result = possibleJSON; // } // } } // if a specific function needs to be run after the get request if(A.isDefined(o.customFunc)) { o.customFunc(result); } // Initiated any wysiwyg editor instances if(!o.isResponse) { if(typeof(o.div) == 'string') A.initEditor(o.div); } $loading.fadeOut(200); }, (o.isJson ? 'json' : 'html')); A.xhrLog.push(xhr); // If A.tempName() was called before this call, it will now be reset. // This will also reset tempDir A.refreshName(); }, // Get a tab. If the LB is open, it will close it. getTab : // tabName : string, name is usually tab_[name] function(tabName, value) { tabName = typeof(tabName) != 'undefined' ? tabName : A.tabName; A.tabName = tabName; var split = A.tabName.split('_'); A.name = split[1]; value = A.parseValues(value); if($('#common_faq_button').length) $('#common_faq_button').text('Common ' + $('#' + tabName + ' a').text() + ' Questions'); A.callObj = { name : A.name, func : 'tab', value : value, div : 'landingStrip', useDiv : true, customFunc : function(result) { $('#tabs li').removeClass(); $('#' + A.tabName).addClass('selected active'); // Try to set the URL to change the &name= variable in case the url is copied and given to someone else, the correct tab will load. try { if(window.location.href.indexOf('?') != -1) { var searchQuery = window.location.search; if(window.location.search.indexOf('name=') != -1) window.history.replaceState(name,name,searchQuery.replace(/([\?&])?name=(?:.*?)(&|$)/g, "$1name=" + A.name + "$2")); else window.history.replaceState(name,name,searchQuery + '&name='+name); } } catch(e) {} FAQ.updateCommonQuestions(A.name); //$('#' + A.callObj.div).html(result); } }; $('#landingStrip').removeClass('bootstrap-area'); A.hideLb(); A.get(); }, getHTML : function(func, value, div, customFunc) { var formValues = A.parseValues(value); A.callObj = { name : A.name, func : func, value : formValues, div : div, customFunc : customFunc, useDiv : true }; A.get(); }, // This was copied from a.js getHTMLAsPost : function(func, value, div, customFunc) { A.isPost = true; var formValues = A.parseValues(value), formId = A.isString(value) && /[a-z]+/i.test(value) && value.indexOf('&') == -1 ? value : A.formId; A.callObj = { name : A.name, func : func, values : formValues, formId : formId, skipNotify : true, isResponse : false, isJson : false, pushFileName : 'view.php', customFunc : function(result) { if(div.length) {$('#' + div).html(result);} customFunc(result); } }; A.push(); }, getLb : function(func, value, isFluid, skipCommonQuestions) { A.getHTML(func, value, 'lb', function(result) { A.showLb(isFluid); if (!skipCommonQuestions) { FAQ.updateCommonQuestionsForLb('#'+func); } }); }, getInputData : function(func, value, fieldId, customFunc) { var formValues = A.parseValues(value); A.callObj = { name : A.name, func : func, value : formValues, fieldId : fieldId, customFunc : customFunc, useDiv : false } A.get(); }, /** * DEPRECATED. DO NOT USE ANYMORE! Either use A.getHTML or A.getJson */ getResponse : function(func, value, customFunc) { var formValues = A.parseValues(value); formValues += '&is_json_request=1'; A.callObj = { name : A.name, func : func, value : formValues, customFunc : customFunc, useDiv : false, isResponse : true }; A.get(); }, getJson : function(func, value, customFunc) { var formValues = A.parseValues(value); formValues += '&is_json_request=1'; A.callObj = { name : A.name, func : func, value : formValues, customFunc : customFunc, useDiv : false, isResponse : true, isJson : true }; A.get(); }, // This is the function that actually interacts with edit.php. The other functions are like "wrapper" functions that push to this one. push : function() { var o = A.callObj, values; if(A.useDiv) A.div = o.div; Timeout.renew(); $('div.loading').fadeIn(200); if(!o.name || !o.func) { A.addError('A name and func must be present to run a set(). name: ' + o.name + ', func: ' + o.func); } var $loading = $('div.loading'); $loading.fadeIn(200); // Validate a form if formId is supplied if(o.formId) { if(!V.form(o.formId)) { $loading.fadeOut(200); // ATS-41583-5 If the form fails and we used A.setTempDir, when the user re-submits the form, the original A.name would be overwritten by the tempName and we would end up using the wrong one for other get/set calls A.refreshName(); return false; } } var extraParams = A.paramToString(); if($(A.postParams).length) extraParams += A.postParamToString(); var domainId = A.isDefined(A.domainId) ? '&domain_id=' + A.domainId : ''; var tempDir = A.lbTempDir.length > 0 ? A.lbTempDir : ''; tempDir = A.tempDir != '' && A.isDefined(A.tempDir) ? A.tempDir : tempDir; var xhr = $.post(tempDir + 'edit.php', "n=" + o.name + "&f=" + o.func + extraParams + domainId + (typeof(o.values) != 'undefined' ? '&' + o.values : ''), function(result) { if(result) { if(typeof(result) == 'string' && result.indexOf('Session Expired. Please logout and login again') != -1) { if(alert('You have remained inactive for a period of time. Please login again to refresh your user session')) { var forceLogout = window.location = '/?logout=1&return_url=' + encodeURIComponent(document.location.pathname + document.location.search); return false; } } // Popup notify anything that is echoed out. if(!A.skipNotify) { var hasActualResult = result.replace(/\<(script|div)[\s\S]*\<\/(script|div)\>/, ""); if(hasActualResult) { if(A.useN) { N.add(result); } else { Notify.add(result); } } } else { A.skipNotify = false; } // if(o.isResponse && typeof(result) == 'string') { // var possibleJSON = result.replace(/\<(script|div)[\s\S]*\<\/(script|div)\>/, ""); // var firstChar = possibleJSON.slice(0,1), checkChar = firstChar == "[" ? "]" : "}", lastChar = possibleJSON.slice(-1), extraJavascript; // if((firstChar == "[" || firstChar == "{") && checkChar == lastChar) { // extraJavascript = result.replace(/[\s\S]*\([\s\S]+)\<\/script\>/, "$1"); // result.replace(/\
Peak Memory: [0-9\.]+ MB\<\/div\>/, ""); // try{eval(extraJavascript);} catch(e) {} // result = $.parseJSON(possibleJSON); // } else { // extraJavascript = result.replace(/[\s\S]*\([\s\S]+)\<\/script\>/, "$1"); // result.replace(/\
Peak Memory: [0-9\.]+ MB\<\/div\>/, ""); // try{eval(extraJavascript);} catch(e) {} // result = possibleJSON; // } // } } // Execute any type of custom function if(A.isDefined(o.customFunc)) { o.customFunc(result); } // Unset the formId variable as we shouldn't need it again. A.formId = ""; $loading.fadeOut(200); }, (o.isJson ? 'json' : 'html')); A.xhrLog.push(xhr); // If A.tempName() was called before this call, it will now be reset. A.refreshName(); }, // This is the wrapper function that is used for the push function. The push function is the actual function that accesses edit.php set : function(func, data, customFunc) { var formValues = A.setValues(data), formId = A.formId; A.callObj = { name : A.name, func : func, values : formValues, formId : formId, customFunc : customFunc }; A.push(); }, // Will get the main tab and hide any open lb after the edit is complete. setAndGetTab : function(func, data, tabValue) { var formValues = A.setValues(data), formId = A.formId; A.callObj = { name : A.name, func : func, values : formValues, formId : formId, customFunc : function() { A.getTab('tab_'+A.name, tabValue); A.hideLb(); } }; A.push(); }, setAndGetHTML : function(func, data, viewFunc, viewValue, viewDiv, viewCustomFunc) { var formValues = A.setValues(data), formId = A.formId; A.callObj = { name : A.name, func : func, values : formValues, formId : formId, customFunc : function() { A.getHTML(viewFunc, viewValue, viewDiv, viewCustomFunc); A.hideLb(); } }; A.push(); }, /** * DEPRECATED. DO NOT USE ANYMORE! Either use A.set or A.setJson */ setResponse : function(func, data, customFunc) { A.skipNotify = true; var formValues = A.setValues(data), formId = A.formId; formValues += '&is_json_request=1'; A.callObj = { name : A.name, func : func, values : formValues, formId : formId, isResponse : true, customFunc : customFunc }; A.push(); }, setJson : function(func, value, customFunc) { A.skipNotify = true; var formValues = A.setValues(value), formId = A.formId; formValues += '&is_json_request=1'; A.callObj = { name : A.name, func : func, values : formValues, formId : formId, isResponse : true, customFunc : customFunc, isJson : true }; A.push(); }, // idString is a comma/hyphen delimited string of the ids needed to be converted into a url string. /* addValues : function(idString) { var string = '', $obj; var ids = A.hasComma(idString) ? idString.split(',') : idString.split('-'); for(var i = 0; i < ids.length; ++i) { $obj = $('#' + ids[i]); string += $obj.name + '=' encodeURIComponent($obj.val()); } A.extraValues += string; }, */ // Sets the name permanantly until changed by another setName() or a tab is clicked. setName : function(name) { A.name = name; }, // Sets the name to be something for one ajax call (get or push). Afterwards it is reset to the previous main name that was set. setTempName : function(tempName) { A.tempName = A.name; A.name = tempName; }, // Sets directory for one ajax call that needs to be used if it's going to something specific (like to the /jobs/view.php), you would use setTempDir('/jobs/'); setTempDir : function(tempDir) { A.tempDir = tempDir; }, /** * Sets the name while the LB is open. Once it closes, it reverts to what it was previously * @param {string} tempName - ex: "jobListings" * @since 11/5/15 * @author Austin */ setLbName : function(tempName) { A.lbTempName = A.name; A.name = tempName; }, /** * Sets the name while the LB is open. Once it closes, it reverts to what it was previously * @param {string} tempName - ex: "/jobs/" * @since 11/5/15 * @author Austin */ setLbTempDir : function(tempDir) { A.lbTempDir = tempDir; }, refreshName : function() { if(A.tempName) { A.name = A.tempName; A.tempName = ''; } if(A.tempDir) { A.tempDir = ''; } }, // Popup that shows up when something is clicked, also called lightbox showLb : function(isFluid) { var $lb = $('#lb-direct-wrapper'); var scrollTop = 0; var left = 0; var centerVertically = false; var newStyle = false; //left = (document.documentElement.clientWidth-490)/2; scrollTop = (document.documentElement.scrollTop) ? document.documentElement.scrollTop : window.pageYOffset; //If IE 8 if(scrollTop == undefined) scrollTop = 0; switch(isFluid){ case 'tiny-center': lbwidth = '20%'; centerVertically = true; newStyle = true; break; case true: case 1: case '1': lbwidth = 'auto'; break; default: lbwidth = 975; break; } if(!newStyle){ $lb.css({'width': lbwidth, 'min-width': 975}); left = (document.documentElement.clientWidth-490) / 2; } else { $lb.css('width', lbwidth); left = ($(window).width() - $lb.width()) / 2; } if(centerVertically){ voffset = ($(window).height() - $lb.height()) / 2; } else voffset = 30; // lbbg is the large dark background area that appears when the lightbox comes up $('#lbbg').show().css({width : document.documentElement.clientWidth + 0, height : document.documentElement.clientHeight + 0, left : '0px', top : '0px'}) // lb is the lightbox itself $lb.show().css({top : (scrollTop + voffset) + 'px', left : (left + 10) + 'px'}); // lbx is the red x in the top right corner or the lightbox $('#lbx').show().css({top : (scrollTop + 35) + 'px', left : (left) + 'px', width : lbwidth, minWidth : 975}); $lb.find('.lb-close').on('click', function() { A.hideLb(); }); }, // Hides the lightbox. hideLb : function() { if(A.lbTempName.length > 0) { A.name = A.lbTempName; A.lbTempName = ''; } if(A.lbTempDir.length > 0) A.lbTempDir = ""; A.shutdownEditor(); $('#lb-direct-wrapper').hide(); $('#lb').html(''); $('#lbx').hide(); $('#lbbg').hide(); V.clearErrors(); }, attachParam : function(param, value) { A.params[param] = value; }, detachParam : function(param) { delete A.params[param]; }, paramToString : function() { var i, str = ''; for(i in A.params) { str += '&' + i + '=' + A.params[i]; } return str; }, attachPostParam : function(param, value) { A.postParams[param] = value; }, detachPostParam : function(param) { delete A.postParams[param]; }, postParamToString : function() { var i, str = ''; for(i in A.postParams) { str += '&' + i + '=' + A.postParams[i]; } return str; }, // Initializes the Wysiwyg Editor. The editor textarea must have a class of "editor" initEditor : function() { var id, $t; if(typeof(tinyMCE) == 'undefined') return; var cmd = tinyMCE.majorVersion == 4 ? 'mceAddEditor' : 'mceAddControl'; $('textarea.editor').each(function() { $t = $(this); id = $t.attr('id'); if(typeof(tinyMCE.editors[id]) == 'undefined') { tinyMCE.execCommand(cmd, false, id); } }); }, submitEditor : function() { var id, $t; $('textarea.editor').each(function() { $t = $(this); id = $t.attr('id'); if(typeof(tinyMCE.editors[id]) != 'undefined') { $('#' + id).val(tinyMCE.get(id).getContent()); } }); }, shutdownEditor : function() { var tinymceCheck = false, tinymceInstances; try { if(tinyMCE.get().length) { tinymceCheck = true; } } catch(e) {} if(tinymceCheck) { tinymceInstances = tinyMCE.editors; var cmd = tinyMCE.majorVersion == 4 ? 'mceRemoveEditor' : 'mceRemoveControl'; for(var i = (tinymceInstances.length - 1); i >= 0; --i) { tinyMCE.execCommand(cmd, false, tinymceInstances[i]['id']); } } }, parseValues : function(value) { return A.setValues(value); /* var formValues = ''; // If this is an object, it'll need to be parsed as an encoded URL if(A.isObject(value)) { formValues = $.param(value); // If it is one single value, just attach it to the "v" param } else if(typeof(value) != 'undefined') { formValues = 'v=' + value; } return formValues; */ }, setValues : function(data) { var formValues; // If this is an string, we'll assume it's a form id if(A.isString(data) && /[a-z]+/i.test(data) && data.indexOf('&') == -1) { // Save data from wysiwyg editors A.submitEditor(); formValues = $('#' + data).serialize(); A.formId = data; // Data can also be a key : value object } else if(A.isObject(data)) { formValues = $.param(data); // If it's a custom url string } else if(A.isString(data) && data.indexOf('&') != -1) { formValues = data; // If it's only an int, we'll assume that it's an id and assign it to v } else if(/[^a-z]+/i.test(data)) { formValues = 'v=' + data; // If there's an & we'll assume that they are trying to manually format the url parameters } else if(A.isString(data) && data.indexOf('&') != -1) { formValues = data; } return formValues; }, // To run this properly, you need to define some text in span tags. The value is defined by the html within the tag // class: editText, // data-func: the func to run, // data-id: the unique id assigned to the element. editText : function() { var image = 'pencil.png'; $('span.editText').css({cursor: 'pointer'}).on('click', function() { var $span = $(this), newVal = $span.html().replace(/\/gi, ''), dateCheck = new Date(newVal.replace(/-/g,'/')), $input = $(document.createElement('input')), $button = $(document.createElement('input')), oValues = $.parseJSON($span.attr('data-json')), id = oValues.id; $input.attr('type', 'text').css('width', $span.outerWidth()).val(newVal).attr('id', 'editText-' + id); $button.attr('type', 'button').val('Update').click(function() { oValues.value = $('#editText-' + id).val(); A.set($span.attr('data-func'), oValues, function() { $span.show().html($input.val()).append(''); $input.remove(); $button.remove(); }); }); $span.hide(); // Make sure there is only one instance of the inputs if(!$span.parent().find('input').length) { $span.parent().append($input).append($button); // if the date seems like it's a valid date (DD-MMM-YYYY) if($span.hasClass('date')) $input.simpleDatepicker({format : 'd-M-Y'}).css('width', '100px'); } // Only append one image to each field }).each(function() { var $span = $(this); if(!$span.find('img').length) $span.append(''); }); }, addError : function(msg) { try { console.log(msg); } catch(e) {} }, isDefined : function(data) { return typeof(data) != 'undefined'; }, isString : function(data) { return typeof(data) == 'string'; }, isInt : function(data) { return typeof(data) == 'number'; }, isObject : function(data) { return typeof(data) == 'object'; }, isFunction : function(data) { return typeof(data) == 'function'; }, hasComma : function(string) { return string.indexOf(',') != -1; }, setLargeGetParam: function(paramName, valueString) { A.largeParam[paramName] = valueString; }, getLargeGetParam: function(paramName) { return A.largeParam[paramName]; }, /* * * Misc functions * */ // This is used in the autocomplete plugin we have. This will bold the letters that we are searching for. highlightResult : function(value, data) { var q = $('#autocomplete').val().toLowerCase(); q = q.split(''); var location, newValue, finalValue = '', lastLocation, done = new Array(); var playValue = value.toLowerCase(); for(var i = 0; i < q.length; i++) { //if(!$.inArray(value.indexOf(q[i]), done)) { // location = value.indexOf(q[i]); //} else { location = playValue.indexOf(q[i], lastLocation + 1); //} if(i == 0) { if(location == 0) { newValue = '' + value.slice(0, 1) + ''; } else { newValue = value.slice(0, location) + '' + value.slice(location, location + 1) + ''; } } else { //if(lastLocation == (location - 1)) { // newValue = '' + value.slice(location, location + 1) + ''; //} else { newValue = value.slice(lastLocation + 1, location) + '' + value.slice(location, location + 1) + ''; //} } lastLocation = location; finalValue += newValue; done.push(location); } finalValue += value.slice(lastLocation + 1); return finalValue; }, addFieldToUrl : function(parameter, value) { try { var searchQuery = window.location.search, questionMark = window.location.href.indexOf('?') == -1 ? '?' : '', nameQuery = parameter + '=' + value, nameRegex = new RegExp(parameter + "\=([a-z0-9\_\+\%]*)", "i"); if(window.location.search.indexOf(parameter + '=') != -1) window.history.replaceState(parameter,parameter,searchQuery.replace(nameRegex, nameQuery)); else window.history.replaceState(parameter,parameter,searchQuery + questionMark + (questionMark == '' ? '&' : '') + nameQuery); } catch(e) {} }, removeFieldFromUrl : function(parameter) { try { var searchQuery = window.location.search, nameRegex = new RegExp('&?' + parameter + "\=([a-z0-9\_\+\%]*)", "i"); if(window.location.search.indexOf(parameter + '=') != -1) window.history.replaceState(parameter,parameter,searchQuery.replace(nameRegex, "")); } catch(e) {} }, generateUniqueID : function() { if(!window.funID) window.funID = Math.round(Math.random() * 100); var funID = window.funID; var d = performance.now(); var uuid = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = (d + Math.random()*16)%16 | 0; d = Math.floor(d/16); return (c=='x' ? r : (r&0x7|0x8)).toString(16); }); uuid = uuid.slice(0, parseInt('-' + funID.length)) + funID; return uuid; }, killAllActiveAjaxRequests : function() { $.each(A.xhrLog, function(index, xhr) { if(xhr) { xhr.abort(); } }); } }; // Generates microsecond timestamp used to generate the unique_id (function(a){a.performance=a.performance||{};performance.now=performance.now||performance.mozNow||performance.msNow||performance.oNow||performance.webkitNow||Date.now||function(){return(new Date).getTime()}})(window); var F = { validate : function(formId) { // Thanks to jquery 2.0.3, it freaks out on the $fields var below if there's no formId if(typeof(formId) == 'undefined' || !formId || formId == '') return true; var failed, showAlert = false, alertText = '', field = '', color = '', afterText = '', check = ''; // SSN and DOB alerts var ssn_dob = false; var skip_ssn_dob = false; var $fields = typeof(formId) == 'string' ? $('#'+formId+' .v') : formId; $fields.each(function() { // if it is a multiple select, make sure that all the fields are automatically selected before putting them through the check. if($(this).prop('tagName') == 'SELECT' && ($(this).attr('multiple') == 'multiple' || $(this).attr('multiple') == '')) { $(this).find('option').attr('selected','selected'); } failed = false; switch($(this).val()) { case undefined: case false: case null: case "": case " ": failed = true; break; case 0: case '0': if(!$(this).hasClass('zeroValue')) failed = true; break; default: break; } field = ''; // If the input needs to be validated for email if($(this).hasClass('email') && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test($(this).val()) === false) { field = 'email'; alertText += "\nThis does not appear to be a valid email address. Please verify the email address and try again. (Red)\n"; failed = true; } // If the input needs to be validated for digits if($(this).hasClass('digit') && /[^0-9]+/.test($(this).val()) === true) { field = 'digit'; alertText += "\nThis field must be a digit with no other characters or spaces. Please verify and try again. (Blue)\n"; failed = true; } // If the input needs to be validated for ASCII valid characters if($(this).hasClass('ascii') && /[^\x20-\x7f\x0A\x0D\t]+/.test($(this).val()) === true) { field = 'char'; alertText += "\nThere are unusual characters in this field. You may have tried to copy and paste the text in this field. Try typing the field out by hand and attempt again. (Yellow)\n"; failed = true; } // If the input needs to be validated for letters, numbers, and the characters _ - . No spaces (ideally for a username) if($(this).hasClass('filename') && /[^\w\-\.]+/.test($(this).val()) === true) { field = 'filename'; alertText += "\nThere should only be letters, numbers, and the characters _ - . in this field. No spaces or other characters are allowed. (Red)\n"; failed = true; } // If the input needs to be validated for a subdomain. (Same as filename, just no period) if($(this).hasClass('subdomain') && /[^\w\-]+/.test($(this).val()) === true) { field = 'subdomain'; alertText += "\nThere should only be letters, numbers, and the characters _ and - in this field. No spaces or other characters are allowed. (Red)\n"; failed = true; } // If the input needs to be validated for decimals (as in currency) if($(this).hasClass('currency') && /[0-9]+\.[0-9]{2}/.test($(this).val()) === false) { field = 'currency'; alertText += "\nThis field must be in the standard format for currency, e.g. 10.00.\n"; failed = true; } // Check for errors in possible HTML tags in additional/screening question text if((formId == 'add_screening_question' || formId == 'edit_screening_question') && this.id == "question"){ if(!F.validateHtmlTags($(this).val())){ alertText += "\nYou have some HTML errors in your question text. Make sure your tags are closed and properly nested.\n"; failed = true; } } afterText = ''; // If the input failed if(failed) { switch(field) { case 'email': color = '#FFD1DD'; afterText = 'Invalid Email'; break; case 'digit': color = '#B6C7FE'; afterText = 'Only Digits'; break; case 'char': color = '#FEFF8F'; afterText = 'Invalid Characters'; break; case 'filename': color = '#FFD1DD'; afterText = 'Only A-Z, 0-9, _, -, . allowed'; break; case 'subdomain': color = '#FFD1DD'; afterText = 'Only A-Z, 0-9, _, -, . allowed'; break; case 'currency': color = '#FFD1DD'; afterText = 'Only currency format. Ex: (10.00)'; break; default: color = '#FFD1DD'; afterText = ''; break; } $(this).css({border : '2px solid ' + color}); if(!$(this).parent().find('span').length) $(this).after('' + afterText + ''); if($(this).parent().find('img').length) $(this).parent().find('img[src*="priceQuote"]').remove(); showAlert = true; } else { $(this).css({border:'2px solid #38BE51'}); //if(!$(this).parent().find('img[src*="priceQuote"]').length) // $(this).after(''); if($(this).parent().find('span').length) $(this).parent().find('span[class!="noValidate"]').remove(); } // SSN and DOB checks check = $(this).val(); if(typeof(check) === "string" && this.id == 'question') ssn_dob = F.checkSSNandDOBVerbiage(check); }); if(showAlert) { if(typeof(formId) == 'string') alert('The highlighted fields need to be completed before you can proceed' + "\n" + alertText); return false; } else { // SSN and DOB checks if( $('select[name=type_id]').val() == '11' || $('input[name=type_id]').val() == '11') { skip_ssn_dob = true; } if( !skip_ssn_dob && ssn_dob == true && (formId == 'add_screening_question' || formId == 'edit_screening_question') ) { alert('The collection of an applicant\'s social security number or date of birth is not allowed in this area. SSN and DOB data will be removed if collected. Please contact support if you have any questions and to learn how you can help in our efforts to improve the security of your applicant\'s personal information.'); ajax('ssnDobBreach', 'email', $('input[name=screening_question_id]').val()); if( !$('input[name=screening_question_id]').length ) $('input[name="flagged"]').val('1') return false; } else if( typeof(check) === "string") { //if the question was set to "Last 4 SSN digits, we just need to check for DOB" if ( F.checkDOBVerbiage(check) == false && skip_ssn_dob && (formId == 'add_screening_question' || formId == 'edit_screening_question')){ return true; } else if( F.checkSSNandDOBVerbiage(check) == true && (formId == 'add_screening_question' || formId == 'edit_screening_question') ) { alert('The collection of an applicant\'s date of birth is not allowed in this area. DOB data will be removed if collected. Please contact support if you have any questions and to learn how you can help in our efforts to improve the security of your applicant\'s personal information.'); ajax('ssnDobBreach', 'email', $('input[name=screening_question_id]').val()); if( !$('input[name=screening_question_id]').length ) $('input[name="flagged"]').val('1') return false; } else { return true; } } else { return true; } } }, getStates : function(countryId, includeEmpty, emptyTopOptionText) { includeEmpty = typeof(includeEmpty) == 'undefined' ? 1 : includeEmpty ? 1 : 0; var text = typeof(emptyTopOptionText) == 'undefined' ? '' : emptyTopOptionText; $.get('/includes/states.php', 'country_id=' + countryId + '&empty_top_option=' + includeEmpty + '&empty_top_option_text=' + text, function(data) { $('#state_id option').remove(); $('#state_id').html(data); }); }, getTimezones : function(countryId, includeEmpty, emptyTopOptionText) { includeEmpty = typeof(includeEmpty) == 'undefined' ? 1 : includeEmpty ? 1 : 0; var text = typeof(emptyTopOptionText) == 'undefined' ? '' : emptyTopOptionText; $.get('/includes/states.php', 'country_id=' + countryId + '&empty_top_option=' + includeEmpty + '&empty_top_option_text=' + text + '&type=time_zones', function(data) { $('#time_zone_id option').remove(); $('#time_zone_id').html(data); }); }, moveOptions : function (theSelFromId, theSelToId) { $('#' + theSelFromId + ' option').each(function() { if($(this).is(':selected') && $(this).prop('disabled') == false) { $('#' + theSelToId).append($(this)); } }); }, moveOptionsCategorized : function (theSelFromId, theSelToId) { $('#' + theSelFromId + ' option').each(function(){ if($(this).is(':selected') && $(this).prop('disabled') == false){ var o_class = $(this).attr('class'); if($('#' + theSelToId + ' option.' + o_class).length){ $('#' + theSelToId + ' option.' + o_class +':last').after($(this)); } else{ $('#' + theSelToId).append($(this)); } } }); }, highSchoolCheck : function(hsValue) { //If they are not doing from/to if($('#years_attended').length) { var $years = $('#years_attended'); var yearsVal = $years.val() != 'N/A' ? $years.val() : ''; if(hsValue == '1') $years.attr('disabled', 'disabled').addClass('disabled').val('N/A'); else $years.removeAttr('disabled').val(yearsVal).removeClass('disabled'); } else { // from/to var $yearsFrom = $('#years_attended_from'); var $yearsTo = $('#years_attended_to'); var fromVal = $yearsFrom.val() != 'N/A' ? $yearsFrom.val() : ''; var toVal = $yearsTo.val() != 'N/A' ? $yearsTo.val() : ''; if(hsValue == '1') { $yearsFrom.attr('disabled', 'disabled').val('N/A').addClass('disabled'); $yearsTo.attr('disabled', 'disabled').val('N/A').addClass('disabled'); } else { $yearsFrom.removeAttr('disabled').val(fromVal).removeClass('disabled'); $yearsTo.removeAttr('disabled').val(toVal).removeClass('disabled'); } } //If Major is enabled if($('#major').length) { var $major = $('#major'); var val = $major.val() != 'N/A' ? $major.val() : ''; if(hsValue == '1') $major.attr('disabled', 'disabled').val('N/A').addClass('disabled'); else $major.removeAttr('disabled').val(val).removeClass('disabled'); } //If Degree is enabled if($('#degree').length) { var $degree = $('#degree'); var val = $degree.val() != 'N/A' ? $degree.val() : ''; if(hsValue == '1') $degree.attr('disabled', 'disabled').val('N/A').addClass('disabled'); else $degree.removeAttr('disabled').val(val).removeClass('disabled'); } }, handlePaste : function (e) { var t = e.target ? e.target : e.srcElement; if(!$(t).data("EventListenerSet")) { //get length of field before paste var keyup = function(){ $(this).data("lastLength",$(this).val().length); }; $(t).data("lastLength", $(t).val().length); //catch paste event var paste = function(){ $(this).data("paste",1); //Opera 11.11+ }; //process modified data, if paste occured var func = function(){ if($(this).data("paste")){ var strTagStrippedText = this.value; strTagStrippedText = strTagStrippedText.replace(/<\/p>/g, "\r\n\r\n"); strTagStrippedText = strTagStrippedText.replace(/
/g, "\r\n"); strTagStrippedText = strTagStrippedText.replace(/<\/?[^>]+(>|$)/g, ""); strTagStrippedText = strTagStrippedText.replace(/&[l|r]+dquo;/g, '"'); strTagStrippedText = strTagStrippedText.replace(/&[l|r]+squo;/g, "'"); strTagStrippedText = strTagStrippedText.replace(/…/g, "..."); strTagStrippedText = strTagStrippedText.replace(/&[n|m]+squo;/g, "'"); strTagStrippedText = strTagStrippedText.replace(/•/g, "\r\n"); // Search and destroy weird characters through converting to URL encoded versions. strTagStrippedText = encodeURIComponent(strTagStrippedText); // Double Curly Quotes strTagStrippedText = strTagStrippedText.replace(/(\%E2\%80\%9C|\%E2\%80\%9D)/g, '"'); // Single Curly Quotes strTagStrippedText = strTagStrippedText.replace(/(\%E2\%80\%98|\%E2\%80\%99)/g, "'"); // Ellipsis strTagStrippedText = strTagStrippedText.replace(/\%E2\%80\%A6/g, "..."); // Emdash strTagStrippedText = strTagStrippedText.replace(/\%E2\%80\%93/g, " - "); // Bullet strTagStrippedText = strTagStrippedText.replace(/\%E2\%80\%A2/g, " - "); strTagStrippedText = decodeURIComponent(strTagStrippedText); var strAmpStrippedText = strTagStrippedText.replace(/&[a-z]+;/g, " "); strAmpStrippedText = strAmpStrippedText.replace(/[^\x20-\x7f\x0A\x0D]+/g, ""); strAmpStrippedText = strAmpStrippedText.replace(" ", " "); while(true) { if(strAmpStrippedText[0] == "\n" || strAmpStrippedText[0] == "\r" || strAmpStrippedText[0] == " ") { strAmpStrippedText = strAmpStrippedText.substring(1); } else { break; } } $(this).data("paste",0); this.value = strAmpStrippedText; $(t).data("lastLength", $(t).val().length); } }; if(window.addEventListener) { t.addEventListener('keyup', keyup, false); t.addEventListener('paste', paste, false); t.addEventListener('input', func, false); } else{ //IE t.attachEvent('onkeyup', function() {keyup.call(t);}); t.attachEvent('onpaste', function() {paste.call(t);}); t.attachEvent('onpropertychange', function() {func.call(t);}); } $(t).data("EventListenerSet",1); } }, validateHtmlTags : function (text){ var tagRegex = /<(\/?\w+)[\sA-Z0-9\'\"\.\,\/=;\:\?\&\%\@+\-_]*>/gi; var questionText = text.toLowerCase(); var searchingFor = []; function checkHtmlTags(){ var result = tagRegex.exec(questionText); //If regex finds nothing if(result === null){ return searchingFor.length === 0; // If an opening tag is found }else if(result[1].charAt(0) !== '/'){ //Self closing tags that might possibly be used. There are others that exist, but they shouldn't be putting them in here. if(result[1] !== 'br' && result[1] !== 'hr' && result[1] !== 'img') searchingFor.push('/'+result[1]); return checkHtmlTags(); // If a closing tag is found } else if(result[1].charAt(0) === '/'){ if(searchingFor[searchingFor.length-1] === result[1]){ searchingFor.pop(); return checkHtmlTags(); }else return false; } } return checkHtmlTags(); }, checkSSNandDOBVerbiage : function(check) { if( check.toLowerCase().search(/\bssn\b/) > -1 || check.toLowerCase().search(/\bss#\b/) > -1 || check.toLowerCase().search(/\bss\b/) > -1 || check.toLowerCase().search(/\bssn#\b/) > -1 || check.toLowerCase().search(/((social( *|_*))(security( *|_*))(number))/) > -1 || check.toLowerCase().search(/((social( *|_*))(security))/) > -1 || check.toLowerCase().search(/((social( *|_*))(card( *|_*))(#))/) > -1 || check.toLowerCase().search(/((social( *|_*))(card( *|_*))(number))/) > -1 || check.toLowerCase().search(/((social( *|_*))(security( *|_*))(card))/) > -1 || check.toLowerCase().search(/((social( *|_*))(security( *|_*))(card( *|_*))(#))/) > -1 || check.toLowerCase().search(/\b((ss( *|_*))(card))\b/) > -1 || check.toLowerCase().search(/\b((ss( *|_*))(number))\b/) > -1 || check.toLowerCase().search(/((social( *|_*))(number))/) > -1 || check.toLowerCase().search(/((social( *|_*))(card))/) > -1 || check.toLowerCase().search(/((social( *|_*))(security))/) > -1 || check.toLowerCase().search(/((date( *|_*))(of( *|_*))(birth))/) > -1 || check.toLowerCase().search(/\b((d( *|_*))(0( *|_*))(b))\b/) > -1 || check.toLowerCase().search(/((birth( *|_*))(date))/) > -1 || check.toLowerCase().search(/((birth( *|_*))(day))/) > -1 || check.toLowerCase().search('mm/dd/yyyy') > -1 || check.toLowerCase().search('mm/dd/yy') > -1 || check.toLowerCase().indexOf('mm-dd-yyyy') > -1 || check.toLowerCase().search('mm-dd-yy') > -1 || check.toLowerCase().search(/\b([x0-9]{3}-[x0-9]{2}-[x0-9]{4})\b/) > -1 || check.toLowerCase().search(/\b([x0-9]{3} [x0-9]{2} [x0-9]{4})\b/) > -1) { return true; } else { check = check.replace(/\s+/g, ''); if( check.toLowerCase().search('socialcard') > -1 || check.toLowerCase().search('socialcardnumber') > -1 || check.toLowerCase().search('socialsecuritycard') > -1 || check.toLowerCase().search('socialnumber') > -1 || check.toLowerCase().search('socialsecuritynumber') > -1 || check.toLowerCase().search('dateofbirth') > -1 || check.toLowerCase().search('birthday') > -1 ) { return true; } else { return false; } } }, checkDOBVerbiage : function(check) { if( check.toLowerCase().search(/((date( *|_*))(of( *|_*))(birth))/) > -1 || check.toLowerCase().search(/\b((d( *|_*))(0( *|_*))(b))\b/) > -1 || check.toLowerCase().search(/((birth( *|_*))(date))/) > -1 || check.toLowerCase().search(/((birth( *|_*))(day))/) > -1 || check.toLowerCase().search('mm/dd/yyyy') > -1 || check.toLowerCase().search('mm/dd/yy') > -1 || check.toLowerCase().indexOf('mm-dd-yyyy') > -1 || check.toLowerCase().search('mm-dd-yy') > -1) { return true; } else { check = check.replace(/\s+/g, ''); if( check.toLowerCase().search('dateofbirth') > -1 || check.toLowerCase().search('birthday') > -1 ) { return true; } else { return false; } } } }; // New Validation System. Use a class of "required" to validate the input var V = { //errorId : 'error', isForm: false, //$e : {}, init : function($div) { var $base = A.isDefined($div) ? $div : $(document); $base.find('form.validate :input').each(function() { var $t = $(this); if($t.prop('tagName') == 'SELECT') { $t.on('change', function() { V.field($t); }).on('blur', function() { V.field($t); }); } else if($t.prop('type') == 'checkbox' || $t.prop('type') == 'radio') { $t.on('click', function() { V.field($t); }); // Set it so all check boxes will be 0 or 1 when clicked on if($t.prop('type') == 'checkbox' && $t.get(0).onclick == null) $t.on('click', function() { if(this.value == '1') this.value = '0'; else this.value = '1'; }); } else { $t.on('blur', function() { V.field($t); }); } if($t.data('maxlength')) { var maxlength = $t.data('maxlength'); $t.prop('maxlength', maxlength + 1); } }); $('form.validate.onsubmit').on('submit', function() { // no-conflict: for times when you have multiple forms on the page and their validity depends on naught but their individual results from V.form if($(this).hasClass('no-conflict')) $('.sticky.formError:eq(0)').remove(); if(!V.form($(this))) return false; }); /* var $error = $('#' + V.errorId); var $ul = $(document.createElement('ul')).addClass('error-list'); if($error.length) { $error.append($ul); V.$e = $error; } */ }, form : function(formId) { // Thanks to jquery 2.0.3, it freaks out on the $fields var below if there's no formId if(typeof(formId) == 'undefined' || !formId || formId == '') return true; var failed = false, errorText = 'Please complete all required fields to proceed.'; var $fields = typeof(formId) == 'string' ? $('#' + formId + ' :input') : formId.find(':input'); V.isForm = true; var groups = []; $fields.each(function() { $t = $(this); // Make sure that the input is visible. We don't need to validate what the user can't see. if($t.closest('dd').length > 0) { $is_visible = $t.closest('dd').is(':visible'); } else { $is_visible = $t.is(':visible'); } // Check if the field is part of a group and, if ti is, only validate the group if($t.closest('div.check-group').length && $t.hasClass('required') && $is_visible) { // Make sure each group is only validated once if($.inArray($t.attr('name'), groups) == -1) { groups.push($t.attr('name')); if(!V.field($t.closest('fieldset'))) { failed = true; } } } else if($is_visible) { if(!V.field($t)) { failed = true; } } else if($t.attr('id') === 'sig_output' && $t.hasClass('required') && !$is_visible) { // Applicants shouldn't bypass the signature on the applicant statement(disclosure). eform-approval also uses it but not required. if(!V.field($t)) { failed = true; } } }); //if(failed || V.$e.find('li').length) { if(failed) { //if(V.$e.find('li').length) //V.$e.fadeIn(); V.isForm = false; V.addError(errorText, '', true); return false; } else { //if(!V.$e.find('li').length) // V.$e.fadeOut(); V.isForm = false; V.removeError(errorText); if(typeof formId == 'object' && formId.hasClass('no-conflict')) return true; // Make sure there are no lingering errors like duplicate check if($('.sticky.formError:eq(0)').html() == '' || !$('.sticky.formError:eq(0)').length) return true; } }, field : function(element) { var failed = false, addAlertText = [], removeAlertText = [], i = 0, $parentForm, $this, $div, customText = '', emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/, phoneRegex = /[^0-9\(\)\-\+\. ]+|^[^\d]*$/, placeholderText; if(element.jquery) $this = $(element); else $this = element; // Just for radios/checkboxes $div = $this.closest('div.check-group'); // If only validating a single field, make sure that it isn't part of a group if($div.length && $this.hasClass('required')) $this = $this.closest('fieldset'); // if it is a multiple select, make sure that all the fields are automatically selected before putting them through the check. if($this.prop('tagName') == 'SELECT' && !$this.hasClass('SumoSelectBox') && ($this.attr('multiple') == 'multiple' || $this.attr('multiple') == '')) { $this.find('option').prop('selected',true); } // Handle checkboxes and radios if(($this.prop('type') == 'checkbox' || $this.prop('type') == 'radio')) { switch($this.prop('name')) { case 'sex_type': customText = 'You must choose a Sex/Gender'; break; case 'ethnic_type': customText = 'You must choose an Ethnicity'; break; case 'vet': customText = 'You must choose a VET100 Classification'; break; case 'veta': customText = 'You must choose a VET100A Classification'; break; case 'is_vet_2014': customText = 'You must choose a Veteran Classification'; break; case 'is_disabled': customText = 'You must choose a Disability Classification'; break; } if(($div.find(':input').hasClass('required') || $div.find(':input').hasClass('v')) && !$div.find(':input:checked').length) { if(customText != '') V.addFieldError(customText, true, $this); else if(A.isDefined($this.data('question-number')) && $this.data('question-number') != '') addAlertText.push("Fix Question #" + $this.data('question-number')+" is missing."); else if(A.isDefined($this.data('question-title')) && $this.data('question-title') != '') addAlertText.push($this.data('question-title')+" is missing."); else if(A.isDefined($this.attr('placeholder')) && $this.attr('placeholder') != '' && !A.isDefined($this.data('question-title'))) { placeholderText = $this.attr('placeholder'); placeholderText = placeholderText.replace('*', ''); addAlertText.push(placeholderText+" is missing."); } failed = true; } else { if(customText != '') V.removeFieldError($this); else if(A.isDefined($this.data('question-number')) && $this.data('question-number') != '') removeAlertText.push("Fix Question #" + $this.data('question-number')); else if(A.isDefined($this.data('question-title')) && $this.data('question-title') != '') removeAlertText.push($this.data('question-title')); else if(A.isDefined($this.attr('placeholder')) && $this.attr('placeholder') != '' && !A.isDefined($this.data('question-title'))) { placeholderText = $this.attr('placeholder'); placeholderText = placeholderText.replace('*', ''); removeAlertText.push(placeholderText+" is missing."); } } // For jointly required checkboxes } else if($this.prop('tagName') == 'FIELDSET') { if(!$this.find('input:checked').length) { addAlertText.push("You must select at least one option."); failed = true; } else removeAlertText.push("You must select at least one option."); // Set this to the first child, that is an input, so that the addFieldError method can select it by name $this = $this.find("input:first"); // all other form inputs } else { if($this.hasClass('required') || $this.hasClass('v')) { switch($this.val()) { case undefined: case false: case null: case "": case " ": failed = true; break; case 0: case '0': if(!$this.hasClass('zeroValue') && $this.prop('tagName') == 'SELECT') failed = true; break; default: if(!A.supportsPlaceholders && $this.attr('placeholder') == $this.val()) failed = true; break; } } if(A.isDefined($this.data('question-number')) && $this.data('question-number') != '') { if(failed) { addAlertText.push("Fix Question #" + $this.data('question-number')); } else { removeAlertText.push("Fix Question #" + $this.data('question-number')); } } if(A.isDefined($this.data('question-title')) && $this.data('question-title') != '') { if(failed) { addAlertText.push($this.data('question-title')+" is missing."); } else { removeAlertText.push($this.data('question-title')+" is missing."); } } if(A.isDefined($this.attr('placeholder')) && $this.attr('placeholder') != '' && !A.isDefined($this.data('question-title'))) { if(failed) { placeholderText = $this.attr('placeholder'); placeholderText = placeholderText.replace('*', ''); addAlertText.push(placeholderText+" is missing."); } else { placeholderText = $this.attr('placeholder'); placeholderText = placeholderText.replace('*', ''); removeAlertText.push(placeholderText+" is missing."); } } if($this.prop('tagName') == 'SELECT') { if(failed) { placeholderText = $("#"+$this.attr('id')+" option:selected").text(); placeholderText = placeholderText.replace('*', ''); placeholderText = placeholderText == '' ? 'Preference' : placeholderText; addAlertText.push(placeholderText+" is missing."); } else { placeholderText = $("#"+$this.attr('id')+" option:selected").text(); placeholderText = placeholderText.replace('*', ''); placeholderText = placeholderText == '' ? 'Preference' : placeholderText; removeAlertText.push(placeholderText+" is missing."); } } $parentForm = $this.closest('form'); var $email = $parentForm.find('input[name="email"]'), $emailConfirm = $parentForm.find('input[name="email_confirm"]'); if(!failed && $this.val() != "") { switch($this.prop('name')) { case 'email': case 'email_confirm': case 'email_address': case 'supervisor_email': if(emailRegex.test($this.val()) === false) { failed = true; addAlertText.push("Invalid email address."); } else { removeAlertText.push("Invalid email address."); } // Check for validation issues with confirming emails. if($email.length && $emailConfirm.length) { var emailConfirmText = "The email addresses you have entered do not match. Please make sure that both email addresses match before proceeding."; if($emailConfirm.val().length > 0 && $email.val().length > 0 && $email.val().toLowerCase() != $emailConfirm.val().toLowerCase()) { failed = true; addAlertText.push(emailConfirmText); } else { removeAlertText.push(emailConfirmText); } } break; case 'password': case 'password_confirm': var $password = $parentForm.find('input[name="password"]'); var $passwordConfirm = $parentForm.find('input[name="password_confirm"]'); var passwordConfirmText = "The passwords you have entered do not match. Please make sure that both passwords match before proceeding."; if($passwordConfirm.length && $password.val().length > 0 && $passwordConfirm.val().length > 0 && $password.val() != $passwordConfirm.val()) { failed = true; addAlertText.push(passwordConfirmText); } else { removeAlertText.push(passwordConfirmText); } break; case 'contact_number': case 'phone_number': case 'supervisor_phone': case 'phone': if(phoneRegex.test($this.val()) === true) { failed = true; addAlertText.push("Field must be a valid phone number"); } else { removeAlertText.push("Field must be a valid phone number"); } var $country = $parentForm.find('select[name="country_id"]'); if($this.val().length < 7 && $country.val() == 226 ){ failed = true; addAlertText.push("The phone number must be at least 7 digits long"); } else{ removeAlertText.push("The phone number must be at least 7 digits long"); } break; case 'zip': case 'zip_code': case 'job_board_zip': var $country = $parentForm.find('select[name="country_id"]'); if($this.val().length < 5 && $country.val() == 226 ){ failed = true; addAlertText.push("The zip/postal code must be at least 5 digits long"); } else{ removeAlertText.push("The zip/postal code must be at least 5 digits long"); } break; default: // If the input needs to be validated for digits if($this.hasClass('digit')) { if(/[^0-9]+/.test($this.val()) === true) { addAlertText.push("Field must be a digit with no other characters or spaces."); failed = true; } else { removeAlertText.push("Field must be a digit with no other characters or spaces."); } // If the input needs to be validated for ASCII valid characters } if($this.hasClass('ascii')) { if(/[^\x20-\x7f\x0A\x0D]+/.test($this.val()) === true) { addAlertText.push("There are unusual characters in a field. You may have tried to copy and paste the text in this field. Try typing the field out by hand and attempt again."); failed = true; } else { removeAlertText.push("There are unusual characters in a field. You may have tried to copy and paste the text in this field. Try typing the field out by hand and attempt again."); } // If the input needs to be validated for letters, numbers, and the characters _ - . No spaces (ideally for a username) } if($this.hasClass('filename')) { if(/[^\w\-\.]+/.test($this.val()) === true) { addAlertText.push("Field should only have letters, numbers, and the characters _ - . . No spaces or other characters are allowed."); failed = true; } else { removeAlertText.push("Field should only have letters, numbers, and the characters _ - . . No spaces or other characters are allowed."); } // If the input needs to be validated for a subdomain. (Same as filename, just no period) } if($this.hasClass('subdomain')) { if(/[^\w\-]+/.test($this.val()) === true) { addAlertText.push("Field should only be letters, numbers, and the characters _ and - . No spaces or other characters are allowed."); failed = true; } else { removeAlertText.push("Field should only be letters, numbers, and the characters _ and - . No spaces or other characters are allowed."); } // If the input needs to be validated for decimals (as in currency) } if($this.hasClass('currency')) { if(/[0-9]+\.[0-9]{2}/.test($this.val()) === false) { addAlertText.push("Field must be in standard currency format, e.g. 10.00."); failed = true; } else { removeAlertText.push("Field must be in standard currency format, e.g. 10.00."); } } break; } } if(!failed && $this.data('maxlength') > 0) { var maxLength = $this.data('maxlength'), characters = $this.val().length; if(characters > maxLength) { addAlertText.push('You have exceeded the maximum allowed characters. Maximum: ' + maxLength); failed = true; } else removeAlertText.push('You have exceeded the maximum allowed characters. Maximum: ' + maxLength); } } // end if form inputs // Add Errors.... for(i in addAlertText) { V.addFieldError(addAlertText[i], true, $this); } // Remove Errors.... for(i in removeAlertText) { V.removeFieldError($this); } // If the input failed if(failed) { if($this.prop('type') == 'checkbox' || $this.prop('type') == 'radio') { $div.find('img').remove(); $div.addClass('check-validationFailed'); checkboxID = ($this.attr('id')); checkboxText = ($this.attr('iferrText')); if($("#error-"+checkboxID).length < 1 && checkboxText) $("
Error: "+checkboxText+"
").insertAfter($div); //$div.removeClass('check-validated'); //$div.append(''); } else if ($this.hasClass('SumoSelectBox')) { $this.siblings('p.SelectBox') .attr('aria-invalid', 'true') .addClass('validationFailed') .removeClass('validated'); } $this.attr('aria-invalid', 'true'); $this.addClass('validationFailed'); $this.removeClass('validated'); return false; } else { if($this.prop('type') == 'checkbox' || $this.prop('type') == 'radio') { $div.find('img').remove(); $div.removeClass('check-validationFailed'); //$div.removeClass('check-validated'); checkboxID = ($this.attr('id')); $("#error-"+checkboxID).remove(); $div.append('Successfully Entered'); } else if ($this.hasClass('SumoSelectBox')) { $this.siblings('p.SelectBox') .attr('aria-invalid', 'false') .removeClass('validationFailed') .addClass('validated'); } $this.attr('aria-invalid', 'false'); $this.removeClass('validationFailed'); $this.addClass('validated'); switch($this.prop('name')) { case 'email': case 'email_confirm': if($email.val() && $emailConfirm.length) { $email.removeClass('validationFailed'); $email.addClass('validated'); } if($emailConfirm.val()) { $emailConfirm.removeClass('validationFailed'); $emailConfirm.addClass('validated'); } break; } return true; } }, addError : function(message, force, prepend) { var e = $('.sticky.formError:eq(0)'), eul = e.find('ul'), found = false, canClose, cleanedMessage = message.replace(/<.+>/g, ''); if(e.length) { eul.find('li').each(function(index) { //This doublecheck nonsense is to account for the possibility of google translate if($(this).data('orig-text').indexOf(cleanedMessage) != -1 || $(this).html().indexOf(message) != -1) { found = true; return; } }); if(!found) { if(prepend) eul.prepend('
  • ' + message + '
  • '); else eul.append('
  • ' + message + '
  • '); //if(!V.isForm && e.is(':hidden')) // e.fadeIn(); } } else if(!V.isForm || force == true) { canClose = A.isMobile ? true : false; e = N.add('
    • '+message+'
    ', { forceStatus : 'error', canClose : canClose, uniqueClass: 'formError'}); } }, removeError : function(message, force) { var e = $('.sticky.formError:eq(0)'), eul = e.find('ul'), found = false, liIndex, eId, cleanedMessage = message.replace(/<.+>/g, ''); eul.find('li').each(function(index) { //This doublecheck nonsense is to account for the possibility of google translate if($(this).data('orig-text').indexOf(cleanedMessage) != -1 || $(this).html().indexOf(message) != -1) { found = true; liIndex = index; return; } }); if(found) { if((!V.isForm || force == true) && e.is(':visible')) { if(eul.find('li').length == 1) { e.empty(); eId = e.prop('id'); eId = eId.match(/[0-9]+/); N.close(eId); //e.fadeOut(function() { // eul.html(''); //}); } else { eul.find('li:eq(' + liIndex + ')').remove(); } } } }, addFieldError : function(message, force, element, useIdInsteadOfName) { useIdInsteadOfName = typeof useIdInsteadOfName === 'undefined' ? false : useIdInsteadOfName; setTimeout(function() { var id = $(element).attr('name'); if(!id || useIdInsteadOfName) id = $(element).attr('id'); id = id.replace("[]", ""); if(!$("#error_"+id).length) { var cleanedMessage = message.replace(/<.+>/g, ''); var error_message = "

    Error: "+cleanedMessage+"

    "; var error = $("
    "+error_message+"
    "); if( $('.errors_div').length ) $('.errors_div').append(error_message); // Handle Checkboxes and Radio Buttons if((element.prop('type') == 'checkbox' || element.prop('type') == 'radio')) { var div = element.closest('fieldset'); error.insertAfter(div); // Handle the signature in the applicant statement } else if(element.prop('name') == 'output') { var div = element.closest('.sigWrapper'); error.insertAfter(div); } else error.insertAfter(element); } }, 150); }, removeFieldError : function(element, useIdInsteadOfName) { useIdInsteadOfName = typeof useIdInsteadOfName === 'undefined' ? false : useIdInsteadOfName; var id = $(element).attr('name'); if(!id || useIdInsteadOfName) id = $(element).attr('id'); // if it's empty for some reason if(!id) return; id = id.replace("[]", ""); $("#error_"+id).remove(); $("#message_"+id).remove(); if(id == 'email_confirm' && $("#error_email:contains('do not match')")) $("#error_email").remove(); }, clearErrors : function() { $('.sticky.formError:eq(0)').fadeOut(function () { $(this).remove(); }); }, duplicate : function(func, $field) { A.getJson(func, {field : $field.prop('name'), value : $field.val() }, function(result) { if(result) { if(result.failed) { V.addError(result.message); } else { V.removeError(result.message); } } }); }, checkRequestUri : // ATS-43375 : Fix Cross-Site Scripting Vulnerabilities function (request_uri) { var found_cnt = 0; var prohibited_terms = ["window.", "location.", ".length", ".html(", ".remove(", "contains(", "encodeURI(", "substring(", "charat(", "split(", "cookie.", "indexof(", "atob(", "btoa(", "onload", "onerror", "$.ajax", "$.get", "$.post", "= 0) { found_cnt++; } }); } else { found_cnt = 0; } return found_cnt; }, isEmailAddressListValid : // ATS-43899 : Check if the value provided is a single valid email address or a comma separated list of valid email addresses. // This code was copied from includes/views/users/functions/contacts_update.php and adapted to be more reusable. function (emailAddresses, inputSelectorString) { var failed = true; // We don't allow any newlines. if(emailAddresses.indexOf('\n') !== -1) { return false; } emailAddresses = Txt.clean(emailAddresses, { stripHtml: true }).replace(/(mailto\:|)+/ig, ''); // If the input selector is provided and the element exists, set the cleaned value as the element's value. if(inputSelectorString && $(inputSelectorString).length) { $(inputSelectorString).val(emailAddresses); } var splits = emailAddresses.split(','); for(var i in splits) { if(!splits[i]) continue; if(/^[^\s@]+@[^\s@]+\.[^\s@]+$/i.test($.trim(splits[i])) === false) { failed = false; break; } } return failed; } }; var N = { add : function(alert, options) { var newId, timeoutId, lastId, split, $newNotify, $lastNotification, offsetTop, $allNotifications = $('.sticky'); // Default options var defaults = { width : 225, canClose : true, time : 6000, uniqueClass : '', forceStatus : '' }; if(A.isObject(options)) { for(var i in options) { defaults[i] = A.isDefined(options[i]) ? options[i] : defaults[i]; } } // Get all notifications and get the length if($allNotifications.length) { lastId = $allNotifications.last().attr('id'); split = lastId.split('_'); newId = parseInt(split[1]) + 1; } else { newId = 1; } // Create New Notification $newNotify = $(document.createElement('div')).addClass('alert').addClass('sticky').attr('id','notify_' + newId).prop('data-id', newId); $newNotify.html(alert); if(defaults.uniqueClass != '') { $newNotify.addClass(defaults.uniqueClass); } if(defaults.canClose) { $newNotify.addClass('alert-dismissable'); $newNotify.prepend(''); $newNotify.find('.close').click(function() { if(A.isDefined(options) && A.isDefined(options.notify_id) && options.notify_id != '') N.go(options.notify_id); if(A.isDefined(options) && "alert_id" in options && options.alert_id != "") N.clearAlert(options.alert_id); N.close(newId); }); } if(defaults.width != 225) { $newNotify.css('width', defaults.width); } // Assign the top attribute of the notification depending on how many notifications are already present. if($allNotifications.length == 0) { var mobileTop = A.isMobile ? 10 : 125; $newNotify.css({ top : mobileTop }); } else { $lastNotification = $allNotifications.last(); offsetTop = $lastNotification[0].offsetTop; $newNotify.css({ top : offsetTop + $lastNotification.outerHeight() + 10 }); } // Format Error Alert Message As Necessary if(/error/i.test(alert) || defaults.forceStatus == 'error' || defaults.forceStatus == 'danger') { $newNotify.addClass('alert-danger'); if(defaults.uniqueClass == 'dismiss-after-10') { defaults.time = 10000; } else { defaults.time = 400000; } } else if(/success/i.test(alert) || defaults.forceStatus == 'success') { $newNotify.addClass('alert-success'); } else if(alert.indexOf('Ticket:') != -1 || defaults.forceStatus == 'ticket') { $newNotify.addClass('alert-warning'); } else { $newNotify.addClass('alert-info'); } // Add a class to all links to have them match the notification. $newNotify.not('.formError').find('a').each(function() { $(this).addClass('alert-link'); }); timeoutId = setTimeout(function() { N.close(newId); }, defaults.time); $newNotify.data('timeout_id_notify', timeoutId); $newNotify.data('timeout_time_notify', defaults.time); // Attach it to the body $newNotify.appendTo(document.body); $newNotify.show(); var $closeAll = $('#closeAll'); if(!$closeAll.length && $('.sticky').length > 1) { $(document.body).append('
    Hide All Notifications
    ') } }, close : function(id) { var $notify = $('#notify_' + id); var height = $notify.outerHeight(); $notify.fadeOut(function() { $notify.remove(); N.moveUp(id, height); if($('.sticky').length <= 1) { $('#closeAll').fadeOut(function() { $(this).remove(); }); } }); }, // Remove via text instead of id remove : function(message) { $('.alert.sticky').each(function(){ if(this.textContent.indexOf(message) > -1) { N.close(this.id.split("_")[1]); return false; } }); }, alertAlreadyExists: function(message) { var found = false; $('.alert.sticky').each(function(){ if(this.textContent.indexOf(message) > -1) { found = true; return false; } }); return found; }, moveUp : function(id, height) { var $notifications = $('.sticky'); var i = 1; var prevId, currentId; var $firstNotification, offset; $notifications.each(function() { $currentNotify = $(this); currentId = parseInt($currentNotify.prop('data-id')); if(currentId == id) { $currentNotify.animate({ top : 120 }); } else if(currentId > id) { offsetTop = $currentNotify[0].offsetTop; $currentNotify.animate({ top : (offsetTop - height - 10) }); } clearTimeout($currentNotify.data('timeout_id_notify')); setTimeout(function() { N.close(currentId); }, $currentNotify.data('timeout_time_notify')); }); }, go : function(viewId, url) { $.post('/notify.php', {view_id : viewId}, function() { if(A.isDefined(url) && url != '') var newLocation = window.location = url; }); }, clearAlert : function(alertId) { A.setTempDir('/'); A.setTempName('alerts'); A.set('clearAlert', { alert_id : alertId }); }, addError : function(message) { N.add(message, { uniqueClass : 'alert-danger' }); } }; var Tooltip = { init : function() { $(function() { Tooltip.active = false; Tooltip.i = Tooltip.i ? Tooltip.i : 1; var $image = $(document.createElement('img')).attr('src', '/images/newhelpicon.png'); var $tooltip = $('.tooltipTrigger').each(function() { $thisTooltip = $(this); if($thisTooltip.hasClass('noHover')) { $thisTooltip.click(function(e) { if($(e.target).hasClass('tooltipTrigger') || $(e.target).parent().hasClass('tooltipTrigger')) { $element = $(this); var id = $element.attr('id'); var div = id + '_div'; var $div = $('#' + div); if($('#' + div).is(':hidden')) { var overflow, tooltipHeight, newDiv; if(Tooltip.activeId != id) { var activeDiv = Tooltip.activeId + '_div'; // div must be set to fadedIn in order to be hidden. if(Tooltip[activeDiv] == 'fadedIn') { $('#' + activeDiv).show().fadeOut(200, function() { $(this).css({ position: 'absolute', top: 0, left: 0, overflowY: 'hidden', height: Tooltip[activeDiv + '_height'] }); Tooltip[activeDiv] = 'fadedOut'; Tooltip.active = false; }); } } // Get the elements positions var pos = $element.position(); var offset = $element.offset(); var spanWidth = $element.outerWidth(); // Make an AJAX call if useAjax is class // // The
    inside the span should be in the following format [name]-[id] // This will be processed as AI.get(div,[name],[id]); if($element.hasClass('useAjax')) { // Gather the initial data inside the div var origArray = $element.attr('data-ajax').split('-'); newDiv = $(document.createElement('div')).attr('id',id + '_internal_div'); $div.html(newDiv); if($div.css('height') == '0px') $div.css('height', 20); newDiv.html('
    '); // Make the Ajax call AI.get(newDiv.attr('id'), origArray[0], origArray[1], function() { tooltipHeight = newDiv.outerHeight(); Tooltip[div + '_height'] = newDiv.css('height'); // Just so the tooltip can stay in the window without leaking out. actualTop = (pos.top - tooltipHeight) > 5 ? (pos.top - tooltipHeight) - ($div.outerHeight() - parseInt($div.css('height'))) : 5; actualLeft = offset.left > 5 && actualTop > 5 ? (pos.left + 5) : (pos.left + spanWidth); // If tooltip box is greater than 450 pixels, put in a scroll bar overflow = tooltipHeight > 450 ? 'scroll' : 'visible'; if(tooltipHeight > 450) { tooltipHeight = 350; // Redo the top location actualTop = (pos.top - $('#' + id + '_div').outerHeight()); } if(newDiv.outerHeight() > $div.outerHeight()) { $div.css({ height : tooltipHeight, top : actualTop, left : actualLeft, overflowY : overflow }); } }, origArray[2]); }// else { tooltipHeight = $('#' + div).outerHeight(); Tooltip[div + '_height'] = $('#' + div).css('height'); // Just so the tooltip can stay in the window without leaking out. var actualTop = (pos.top - tooltipHeight) > 5 ? (pos.top - tooltipHeight) : 5; var actualLeft = offset.left > 5 && actualTop > 5 ? (pos.left + 5) : (pos.left + spanWidth); // If tooltip box is greater than 450 pixels, put in a scroll bar overflow = tooltipHeight > 450 ? 'scroll' : 'visible'; if(tooltipHeight > 450) { $('#' + id + '_div').css({height : 350}); // Redo the top location actualTop = (pos.top - $('#' + id + '_div').outerHeight()); } //} // Make the changes to the div's css $('#' + id + '_div').css({ position: 'absolute', top: actualTop + 'px', left: actualLeft + 'px', overflowY: overflow, width: 300 }).hide().fadeIn(200, function(){ // fadedIn only allows the div to fade in once instead of multiple times Tooltip[div] = 'fadedIn'; Tooltip.activeId = id; Tooltip.active = true; }).find('a').attr('target','_blank'); // Hide div on double click $(window).one('dblclick', function() { $('#' + div).show().fadeOut(function() { $(this).css({ position: 'absolute', top: 0, left: 0, overflowY: 'hidden', height: Tooltip[div + '_height'] }); // fadedOut only allows the div to fade in once instead of multiple times Tooltip[div] = 'fadedOut'; Tooltip.active = false; }); $(window).unbind('dblclick'); }); // If is(':visible') } else { // div must be set to fadedIn in order to be hidden. if(Tooltip[div] == 'fadedIn') { $('#' + div).show().fadeOut(200, function() { $(this).css({ position: 'absolute', top: 0, left: 0, overflowY: 'hidden', height: Tooltip[div + '_height'] }); Tooltip[div] = 'fadedOut'; Tooltip.active = false; }); } } } }); // Configure the id and class of the span/div $thisTooltip.attr('id', 'tooltip_' + Tooltip.i); $thisTooltip.attr('title','Click For More Information (Double Click To Close)'); $thisTooltip.children('div').addClass('tooltip').attr('id','tooltip_' + Tooltip.i + '_div'); ++Tooltip.i; // Append the help image if(!$thisTooltip.find('img').length && !$thisTooltip.hasClass('noIcon')) { $thisTooltip.append($image.clone()); } // Make it appear as a link with a hover if there is noIcon class set if($thisTooltip.hasClass('noIcon')) { $thisTooltip.css({ textDecoration : 'underline', fontWeight : 'bold', color: '#4A5C82' }); } } else { $thisTooltip.hover( // on mouseover.... function() { $element = $(this); var id = $element.attr('id'); var div = id + '_div'; var $div = $('#' + div); if(typeof(Tooltip.mouseOutTimeoutId) != 'undefined' && id == Tooltip.activeId) clearTimeout(Tooltip.mouseOutTimeoutId); if((Tooltip[div] == undefined || Tooltip[div] == 'fadedOut') && !Tooltip.active) { // You must hover for 600 ms before the tooltip will show. var time = 600; Tooltip.timeoutId = window.setTimeout(function() { var overflow, tooltipHeight, newDiv, actualTop, actualLeft, pos, offset, spanWidth; // Get the elements positions pos = $element.position(); offset = $element.offset(); spanWidth = $element.outerWidth(); $div.show();//.css({left: -2000}); /* * * Make an AJAX call if useAjax is class * * The
    inside the span.useAjax should be in the following format [func]-[id][-[name]] * This will be processed as AI.get(newDiv,[func],[id]); * */ if($element.hasClass('useAjax')) { // Gather the initial data inside the div var origArray = $element.attr('data-ajax').split('-'); newDiv = $(document.createElement('div')).attr('id',id + '_internal_div'); $div.html(newDiv); if($div.css('height') == '0px') $div.css('height', 20); newDiv.html('
    '); // Make the Ajax call AI.get(newDiv.attr('id'), origArray[0], origArray[1], function() { tooltipHeight = newDiv.outerHeight(); Tooltip[div + '_height'] = newDiv.css('height'); // Just so the tooltip can stay in the window without leaking out. actualTop = (pos.top - tooltipHeight) > 5 ? (pos.top - tooltipHeight) - ($div.outerHeight() - parseInt($div.css('height'))) : 5; actualLeft = offset.left > 5 && actualTop > 5 ? (pos.left + 5) : (pos.left + spanWidth); // If tooltip box is greater than 450 pixels, put in a scroll bar overflow = tooltipHeight > 450 ? 'scroll' : 'visible'; if(tooltipHeight > 450) { tooltipHeight = 350; // Redo the top location actualTop = (pos.top - $('#' + id + '_div').outerHeight()); } if(newDiv.outerHeight() > $div.outerHeight()) { $div.css({ height : tooltipHeight, top : actualTop, left : actualLeft, overflowY : overflow }); } }, origArray[2]); } //else { tooltipHeight = $div.outerHeight(); Tooltip[div + '_height'] = $div.css('height'); // Just so the tooltip can stay in the window without leaking out. actualTop = (pos.top - tooltipHeight) > 5 ? (pos.top - tooltipHeight) : 5; actualLeft = offset.left > 5 && actualTop > 5 ? (pos.left + 5) : (pos.left + spanWidth); // If tooltip box is greater than 450 pixels, put in a scroll bar overflow = tooltipHeight > 450 ? 'scroll' : 'visible'; if(tooltipHeight > 450) { $div.css({height : 350}); // Redo the top location actualTop = (pos.top - $div.outerHeight()); } //} // Make the changes to the div's css $div.css({ position: 'absolute', top: actualTop, left: actualLeft, overflowY: overflow, width: 300 }).hide().fadeIn(200, function(){ // fadedIn only allows the div to fade in once instead of multiple times Tooltip[div] = 'fadedIn'; Tooltip.activeId = id; // If they click the mouse it will hide the div if(!$element.hasClass('noClick')) { $(window).one('mousedown', function() { $div.show().fadeOut(function() { $(this).css({ position: 'absolute', top: 0, left: 0, overflowY: 'hidden', height: Tooltip[div + '_height'] }); // fadedOut only allows the div to fade in once instead of multiple times Tooltip[div] = 'fadedOut'; Tooltip.active = false; window.clearTimeout(Tooltip.timeoutId); }); $(window).unbind('mousedown'); }); } Tooltip.active = true; }).find('a').attr('target','_blank'); }, time); } }, // on mouseout.... function() { $element = $(this); var id = $element.attr('id'); var div = id + '_div'; var $div = $('#' + div); if(Tooltip.timeoutId) window.clearTimeout(Tooltip.timeoutId); // div must be set to fadedIn in order to be hidden. if(Tooltip[div] == 'fadedIn') { $(window).unbind('mousedown'); Tooltip.mouseOutTimeoutId = setTimeout( function() { $div.show().fadeOut(200, function() { $(this).css({ position: 'absolute', top: 0, left: 0, overflowY: 'hidden', height: Tooltip[div + '_height'] }); Tooltip[div] = 'fadedOut'; Tooltip.active = false; }); }, 400); } } ); // Configure the id and class of the span/div $thisTooltip.attr('id', 'tooltip_' + Tooltip.i); $thisTooltip.children('div').addClass('tooltip').attr('id','tooltip_' + Tooltip.i + '_div'); ++Tooltip.i; // Append the help image if(!$thisTooltip.find('img').length && !$thisTooltip.hasClass('noIcon')) { $thisTooltip.append($image.clone()); } // Make it appear as a link with a hover if there is noIcon class set if($thisTooltip.hasClass('noIcon')) { $thisTooltip.css({ textDecoration : 'underline', fontWeight : 'bold', color: '#4A5C82' }); } } }); /* $tooltip.hover( // on mouseover.... function() { $element = $(this); var id = $element.attr('id'); var div = id + '_div'; if(typeof(tooltip.mouseOutTimeoutId) != 'undefined' && id == tooltip.activeId) clearTimeout(tooltip.mouseOutTimeoutId); if((tooltip[div] == undefined || tooltip[div] == 'fadedOut') && !tooltip.active) { // You must hover for 600 ms before the tooltip will show. var time = 600; tooltip.timeoutId = window.setTimeout(function() { // Get the elements positions var pos = $element.position(); var offset = $element.offset(); var tooltipHeight = $('#' + div).outerHeight(); tooltip[div + '_height'] = $('#' + div).css('height'); var spanWidth = $element.outerWidth(); // Just so the tooltip can stay in the window without leaking out. var actualTop = (pos.top - tooltipHeight) > 5 ? (pos.top - tooltipHeight) : 5; var actualLeft = offset.left > 5 && actualTop > 5 ? (pos.left + 5) : (pos.left + spanWidth); // If tooltip box is greater than 450 pixels, put in a scroll bar var overflow = tooltipHeight > 450 ? 'scroll' : 'visible'; if(tooltipHeight > 450) { $('#' + id + '_div').css({height : 200}); // Redo the top location actualTop = (pos.top - $('#' + id + '_div').outerHeight()); } // Make the changes to the div's css $('#' + id + '_div').css({ position: 'absolute', top: actualTop + 'px', left: actualLeft + 'px', overflowY: overflow, width: 300 }).hide().fadeIn(200, function(){ // fadedIn only allows the div to fade in once instead of multiple times tooltip[div] = 'fadedIn'; tooltip.activeId = id; // If they click the mouse it will hide the div if(!$element.hasClass('noClick')) { $(window).one('mousedown', function() { $('#' + div).show().fadeOut(function() { $(this).css({ position: 'absolute', top: 0, left: 0, overflowY: 'hidden', height: tooltip[div + '_height'] }); // fadedOut only allows the div to fade in once instead of multiple times tooltip[div] = 'fadedOut'; tooltip.active = false; window.clearTimeout(tooltip.timeoutId); }); $(window).unbind('mousedown'); }); } tooltip.active = true; }).find('a').attr('target','_blank'); }, time); } }, // on mouseout.... function() { $element = $(this); var id = $element.attr('id'); var div = id + '_div'; if(tooltip.timeoutId) window.clearTimeout(tooltip.timeoutId); // div must be set to fadedIn in order to be hidden. if(tooltip[div] == 'fadedIn') { $(window).unbind('mousedown'); tooltip.mouseOutTimeoutId = setTimeout( function() { $('#' + div).show().fadeOut(200, function() { $(this).css({ position: 'absolute', top: 0, left: 0, overflowY: 'hidden', height: tooltip[div + '_height'] }); tooltip[div] = 'fadedOut'; tooltip.active = false; }); }, 400); } } ).each(function() { $element = $(this); // Configure the id and class of the span/div $element.attr('id', 'tooltip_' + tooltip.i); $element.children('div').addClass('tooltip').attr('id','tooltip_' + tooltip.i + '_div'); ++tooltip.i; // Append the help image if(!$element.find('img').length && !$element.hasClass('noIcon')) { $element.append($image.clone()); } // Make it appear as a link with a hover if there is noIcon class set if($element.hasClass('noIcon')) { $element.css({ textDecoration : 'underline', fontWeight : 'bold', color: 'blue' }); } }) */ }); } }; // basic class to track custom links/buttons/etc var Analytics = { extraParams : {}, hasSent : false, addAction : function(customActionField, options) { var params = {action : customActionField}; if(A.isObject(options)) { $.extend(params, options); } if(typeof(document.referrer) !== "undefined" && document.referrer !== "") Analytics.addParams( { referrer : document.referrer } ); if($(Analytics.extraParams).length) $.extend(params, Analytics.extraParams); $.post('/includes/link_tracking.php', params, function() { Analytics.extraParams = {}; }); Analytics.hasSent = true; }, addParams : function(params) { if($(params).length) $.extend(Analytics.extraParams, params); } }; var typeDelay = function(){ var timer = 0; return function(callback, ms){ clearTimeout (timer); timer = setTimeout(callback, ms); } }(); var Password = { minLength : 0, minLetters : 0, minSpecials : 0, minNumbers : 0, currentPasswordLength : 0, passwordId : '', confirmPasswordId : '', confirmPasswordErrorDiv : '', errorDiv : '', formId : '', switchId : '', showPopup : false, requirementsDiv : '', checkImage : '/images/check_margin.png', xImage : '/images/x_margin.png', // New version, copied from a.js initStuff : function(divId) { var reqs = [], p = Password, lengthStr = ''; divId = divId != "" && divId != undefined ? divId : 'password_requirements_div'; p.switchId = p.switchId != "" ? p.switchId : 'password_switch'; if(p.formId) { $('#' + p.formId).on('submit', function(e) { if($('#' + p.switchId).val() == "0" && $('#' + p.passwordId).val() != "") { N.add('Error: Your password does not meet all the necessary requirements. Please re-type your password and try again.'); e.stopImmediatePropagation(); return false; } }); } if($('#' + divId).length) { p.requirementsDiv = divId; if(p.minLetters != 0) reqs.push('Letters in password: ' + p.minLetters); if(p.minNumbers != 0) reqs.push('Numbers in password: ' + p.minNumbers); if(p.minSpecials != 0) reqs.push('Special characters in password: ' + p.minSpecials + ' (ex. !@#$%^&*()?<>. etc)'); if(p.minLength != 0) reqs.push('Total minimum length of password: ' + p.minLength + '. Currently at ' + p.currentPasswordLength + ' characters.') if(p.minLength != 0 || p.minLetters != 0 || p.minNumbers != 0 || p.minSpecials != 0) $('#' + divId).html('Your password must meet the following requirements:
    ' + reqs.join('
    ')); } p.passwordId = p.passwordId != "" ? p.passwordId : 'password'; if($('#' + p.passwordId).length) { $('#' + p.passwordId).on('keyup', function() { $('#' + p.requirementsDiv).show(); var t = this; typeDelay(function() { Password.checkPassword(t.value); }, 200); }); } }, // Old version, but is still bein used setupRequirementsDiv : function(divId) { var reqs = [], p = Password, lengthStr = ''; if($('#' + divId).length) { p.requirementsDiv = divId; if(p.minLetters != 0) reqs.push('Letters in password: ' + p.minLetters); if(p.minNumbers != 0) reqs.push('Numbers in password: ' + p.minNumbers); if(p.minSpecials != 0) reqs.push('Special characters in password: ' + p.minSpecials + ' (ex. !@#$%^&*()?<>. etc)'); if(p.minLength != 0) reqs.push('Total minimum length of password: ' + p.minLength + '. Currently at ' + p.currentPasswordLength + ' characters.'); if(p.minLength != 0 || p.minLetters != 0 || p.minNumbers != 0 || p.minSpecials != 0) $('#' + divId).html('Your password must meet the following requirements:
    ' + reqs.join('
    ')); } }, checkLength : function(input_password) { // If password is less than x chars if(Password.minLength != 0 && input_password.length < Password.minLength) { $('#password_req_length').attr('src', Password.xImage); return false; } else { $('#password_req_length').attr('src', Password.checkImage); return true; } }, checkLetters : function(input_password) { // If password doesn't have x letters if(Password.minLetters != 0) { regex = new RegExp("[A-Za-z]{" + Password.minLetters + ",}"); if(!regex.test(input_password)) { $('#password_req_letters').attr('src', Password.xImage); return false; } else { $('#password_req_letters').attr('src', Password.checkImage); return true; } } }, checkSpecials : function(input_password) { // If password doesn't have x specials if(Password.minSpecials != 0) { regex = new RegExp("[^A-Za-z0-9\t\n ]{" + Password.minSpecials + ",}"); if(!regex.test(input_password)) { $('#password_req_specials').attr('src', Password.xImage); return false; } else { $('#password_req_specials').attr('src', Password.checkImage); return true; } } }, checkNumbers : function(input_password) { // If password doesn't have x numbers if(Password.minNumbers != 0) { regex = new RegExp("[0-9]{" + Password.minNumbers + ",}"); if(!regex.test(input_password)) { $('#password_req_numbers').attr('src', Password.xImage); return false; } else { $('#password_req_numbers').attr('src', Password.checkImage); return true; } } }, checkPassword : function(input_password) { var p = Password, regex, length, letter, number, special, error = []; //if(typeof(options) != 'object') // return false; length = p.checkLength(input_password); letter = p.checkLetters(input_password); number = p.checkNumbers(input_password); special = p.checkSpecials(input_password); // If they don't have any rules. if(typeof(length) == "undefined" && typeof(letter) == "undefined" && typeof(number) == "undefined" && typeof(special) == "undefined") return true; if($('#password_length_counter').length) $('#password_length_counter').text(input_password.length); if(length == false || letter == false || number == false || special == false) error.push("Your password must meet the following requirements:"); if(letter == false) error.push("Letters in password: " + p.minLetters); if(number == false) error.push("Numbers in password: " + p.minNumbers); if(special == false) error.push("Special characters in password: " + p.minSpecials + " (ex. !@#$%^&*()<>?. etc)"); if(length == false) error.push("Total minimum length of password: " + p.minLength); if(error.length) { if(p.errorDiv != "" && $('#' + p.errorDiv).length) $('#' + p.errorDiv).html(error.join('
    ')); else if(p.showPopup) N.add(error.join('
    ')); $('#' + p.switchId).val(0); return false; } $('#' + p.switchId).val(1); return true; }, comparePasswords : function() { var p = Password; if(p.confirmPasswordId != "" && p.passwordId != "" && $('#' + p.confirmPasswordId).length && $('#' + p.passwordId).length) { if($('#' + p.confirmPasswordId).val() != "" && $('#' + p.confirmPasswordId).val() != $('#' + p.passwordId).val()) { $('#' + p.confirmPasswordErrorDiv).text('Your passwords don\'t match.'); p.checkPassword($('#' + p.passwordId).val()); return false; } else { $('#' + p.confirmPasswordErrorDiv).text(''); p.checkPassword($('#' + p.passwordId).val()); return true; } } } }; // Uses the Apprise plugin var P = { // The form that is usually set in another area of the page to submit if the user needs to save info activeForm : "", saveDialog : function(options) { Apprise('A change was made, but wasn\'t saved. Do you want to save your changes?', { buttons : { dontSave : { action: function() { if(A.isDefined(options.dontSaveFunc)) options.dontSaveFunc(); Apprise('close'); }, className: 'pull-left', id: 'dont_save', text: 'Don\'t Save' }, cancel : { action: function() { Apprise('close'); }, className: null, id: 'cancel', text: 'Cancel' }, save : { action: function() { if(A.isDefined(options.saveFunc)) options.saveFunc(); Apprise('close'); }, className: "pure-button-accent", id: 'save', text: 'Save Changes' } } }); } }; // Questions, job questions, survey questions, etc. var Q = { defaultOptions : { question_input : '#question', question_html : '#example_question', answer_type_input : '#answer_type', add_more_rows : '#add_more_rows', answer_table : '#answers_table', main_form : '#question-form', example_element_container : '#example_type' }, showType : function(type, options) { options = $.extend(Q.defaultOptions, options); var t = $(options.example_element_container), a = $(options.answer_table); switch(type) { case "": case "0": a.hide(); break; case "1": case "11": t.html(''); a.hide().find('.populate-options:eq(0)').removeClass('v zeroValue'); break; case "2": t.html(''); a.hide().find('.populate-options:eq(0)').removeClass('v zeroValue'); break; case "3": t.html(''); a.show().find('.populate-options:eq(0)').addClass('v zeroValue'); // Only clear the answer table if creating a new question if(!$(options.main_form + ' input[name="id"]:eq(0)').val()) { $(options.answer_table + ' input').val("").prop('checked', false); } Q.addOptions(options); break; case "4": t.html(''); a.show().find('.populate-options:eq(0)').addClass('v zeroValue'); // Only clear the answer table if creating a new question if(!$(options.main_form + ' input[name="id"]:eq(0)').val()) { $(options.answer_table + ' input').val("").prop('checked', false); } Q.addOptions(options); break; case "5": t.html(''); a.show().find('.populate-options:eq(0)').addClass('v zeroValue'); // Only clear the answer table if creating a new question if(!$(options.main_form + ' input[name="id"]:eq(0)').val()) { $(options.answer_table + ' input').val("").prop('checked', false); } Q.addOptions(options); break; case "6": t.html(''); a.show().find('.populate-options:eq(0)').addClass('v zeroValue'); // Only clear the answer table if creating a new question if(!$(options.main_form + ' input[name="id"]:eq(0)').val()) { $(options.answer_table + ' input').val("").prop('checked', false); $(options.main_form + ' input[name="answer[]"]:eq(0)').val('Yes'); $(options.main_form + ' input[name="answer[]"]:eq(1)').val('No'); } Q.addOptions(options); break; case "7": t.html(''); a.hide().find('.populate-options:eq(0)').removeClass('v zeroValue'); break; case "10": t.html(''); a.show().find('.populate-options:eq(0)').addClass('v zeroValue'); $(options.answer_table + ' input').val("").prop('checked', false); $(options.main_form + ' input[name="answer[]"]:eq(0)').val('Yes'); $(options.main_form + ' input[name="answer[]"]:eq(1)').val('No'); Q.addOptions(options); break; case "12": case "13": var states = { "AL" : "Alabama", "AK" : "Alaska", "AZ" : "Arizona", "AR" : "Arkansas", "CA" : "California", "CO" : "Colorado", "CT" : "Connecticut", "DE" : "Delaware", "DC" : "District of Columbia", "FL" : "Florida", "GA" : "Georgia", "HI" : "Hawaii", "ID" : "Idaho", "IL" : "Illinois", "IN" : "Indiana", "IA" : "Iowa", "KS" : "Kansas", "KY" : "Kentucky", "LA" : "Louisiana", "ME" : "Maine", "MD" : "Maryland", "MA" : "Massachusetts", "MI" : "Michigan", "MN" : "Minnesota", "MS" : "Mississippi", "MO" : "Missouri", "MT" : "Montana", "NE" : "Nebraska", "NV" : "Nevada", "NH" : "New Hampshire", "NJ" : "New Jersey", "NM" : "New Mexico", "NY" : "New York", "NC" : "North Carolina", "ND" : "North Dakota", "OH" : "Ohio", "OK" : "Oklahoma", "OR" : "Oregon", "PA" : "Pennsylvania", "PR" : "Puerto Rico", "RI" : "Rhode Island", "SC" : "South Carolina", "SD" : "South Dakota", "TN" : "Tennessee", "TX" : "Texas", "UT" : "Utah", "VT" : "Vermont", "VA" : "Virginia", "WA" : "Washington", "WV" : "West Virginia", "WI" : "Wisconsin", "WY" : "Wyoming" }; var state_abbreviations = Object.keys(states); a.show().find('.populate-options:eq(0)').addClass('v zeroValue'); $(options.answer_table + ' input').val("").prop('checked', false); $.each(state_abbreviations, function( index, abbreviation ){ var state_string = states[abbreviation] + ' - ' + abbreviation; // Check if the element exists and create it, if it doesn't if($(options.main_form + ' input[name="answer[]"]:eq(' + index + ')').length) { $(options.main_form + ' input[name="answer[]"]:eq(' + index + ')').val(state_string); } else { var $clone, currentLength = $(options.answer_table + ' tbody tr').length + 1; $clone = $(options.answer_table).find('tr').last().clone(true); $clone.find('input').val("").prop('checked', false); $clone.find('input[name="answer[]"]').val(state_string); $clone.find('input[name="answer_weight[]"]').val(currentLength); $(options.answer_table + ' tbody').append($clone).sortable('reload'); } }); Q.addOptions(options); break; case "14": t.html(''); a.hide(); break; } }, addOptions : function(options) { options = $.extend(Q.defaultOptions, options); // save all answers in an array to rearrange them later var html_array = new Array(), html_str = "", type_id = $(options.answer_type_input).val(), isSelect = type_id != "4" && type_id != "5" && type_id != "13"; html_str = isSelect ? ' ' + this.value + '

    '; break; default: html_array[order] += ''; } } }); for(var a in html_array) html_str += html_array[a]; html_str += isSelect ? '' : ''; $(options.example_element_container).html(html_str); }, setQuestionEvents : function(options) { options = $.extend(Q.defaultOptions, options); $(options.question_input).on('keyup', function() { $(options.question_html).html(this.value); }); $(options.answer_type_input).on('change', function() { Q.showType(this.value, options); if($.inArray(this.value, ['3','4','5','10']) != -1) { $(options.answer_table + ' input[type=text]').first().addClass('v'); //Ticket 31420 Fix $(options.add_more_rows).show(); } else { $(options.answer_table + ' input[type=text]').first().removeClass('v'); //Ticket 31420 Fix $(options.add_more_rows).hide(); } }); $(options.add_more_rows).on('click', function() { var $clone, currentLength = $(options.answer_table + ' tbody tr').length + 1; for(var i = 0; i < 5; ++i, ++currentLength) { $clone = $(options.answer_table).find('tr').last().clone(true); $clone.find('input').val("").prop('checked', false); $clone.find('input[name="answer_weight[]"]').val(currentLength); $(options.answer_table + ' tbody').append($clone).sortable('reload'); } }); $(options.answer_table + ' .populate-options').on('keyup', function() { typeDelay(function() { Q.addOptions(options); }, 500); }); } }; var Txt = { /** * clean will convert any unusual text (ex: copy/paste) and make it ASCII safe. * @param {string} text * @param {object} options * options.stripHtml - strips out html * options.basicSpacing - tries to convert some HTML to newline characters. * options.nl2br - converts \n to <br /> * @returns {string} */ clean : function(text, options) { var cleanText = $.trim(text), stripHtml = false, html2nl = false, nl2br = false; if(typeof(options) != "undefined") { stripHtml = typeof(options.stripHtml) != "undefined" ? options.stripHtml : false; html2nl = typeof(options.html2nl) != "undefined" ? options.html2nl : false; nl2br = typeof(options.nl2br) != "undefined" ? options.nl2br : false; } // Curly quotes cleanText = cleanText.replace(/&[l|r]+dquo;/g, '"'); cleanText = cleanText.replace(/&[l|r]+squo;/g, "'"); cleanText = cleanText.replace(/&[n|m]+squo;/g, "'"); cleanText = cleanText.replace(/[“”]+/g, '"'); cleanText = cleanText.replace(/[‘’]+/g, "'"); // Ellipsis cleanText = cleanText.replace(/…/g, '...'); cleanText = cleanText.replace(/…+/g, "..."); // Mdash cleanText = cleanText.replace(/—/g, '-'); cleanText = cleanText.replace(/—+/g, "-"); // Ndash (ATS-44470) cleanText = cleanText.replace(/–/g, '-'); // Any non ASCII characters cleanText = cleanText.replace(/[^\x20-\x7f\t\r\n\s]/g, ""); if(html2nl) { // Bullets cleanText = cleanText.replace(/•/g, "\r\n"); // Paragraphs cleanText = cleanText.replace(/<\/p>/g, "\r\n\r\n"); } if(nl2br) { cleanText = cleanText.replace(/\n/g, "
    "); } // Clean out the html if(stripHtml) cleanText = Txt.stripHtml(cleanText); // Strip excessive spaces cleanText = cleanText.replace(/ {2,}/g, " "); return cleanText; }, /** * Strips out HTML and any entities if provided * @param {string} html_text * @param {boolean} strip_entities * @returns {string} purified */ stripHtml : function(htmlText, stripEntities) { var cleanText = $.trim(htmlText); // If this is escaped html, converts it to real html first. cleanText = cleanText.replace(/&(lt|gt);/g, function (strMatch, p1) { return (p1 == "lt") ? "<" : ">"; }); cleanText = $('
    ').html(cleanText).text(); if(stripEntities) cleanText = cleanText.replace(/\&[a-z]+;/ig, " "); return cleanText; }, /** * Gets the counts of characters and words and saves them to the Txt object * @param {string} text * @returns {Txt} */ getCounts : function(text) { text = $.trim(text); text = text.replace(/\s{2,}/g, " "); split = text.split(' '); Txt.words = split.length; Txt.characters = text.length; return Txt; }, copyToClipboard : function(str) { function listener(e) { e.clipboardData.setData("text/plain", str); e.preventDefault(); } document.addEventListener("copy", listener); document.execCommand("copy"); document.removeEventListener("copy", listener); } }; var Timeout = { limit : 14400, // 4 hours intervalId : 0, start : function() { Timeout.renew(); }, renew : function() { if(('AS' in window) == false) return; var newTime = Math.round((new Date()).getTime() / 1000); $('.timeout-notification').fadeOut().remove(); AS.set('logged_in', 'yes'); AS.set('timeout_last_activity', newTime); Timeout.refreshTimeout(); }, refreshTimeout : function() { if(Timeout.intervalId > 0) clearInterval(Timeout.intervalId); Timeout.intervalId = setInterval(function() { Timeout.ping(); }, 1000); }, ping : function() { if(('AS' in window) == false) return; var newTime = Math.round((new Date()).getTime() / 1000), lastActivity = AS.get('timeout_last_activity'); // 60 second warning message if((newTime - lastActivity) > (Timeout.limit - 60)) { if($('.timeout-notification').length == 0) N.add('Your session is about to expire. You will be logged out for security purposes.

    Click to Stay Logged In', { uniqueClass : 'alert-danger timeout-notification', time : 600000, canClose : false }); } else if((newTime - lastActivity) < Timeout.limit && $('.timeout-notification').length) { $('.timeout-notification').fadeOut().remove(); // This usually means the timeout was renewed in another tab, just need to refresh the intervals Timeout.refreshTimeout(); } if(((newTime - lastActivity) > Timeout.limit) || AS.get('logged_in') == 'no') { clearInterval(Timeout.intervalId); AS.set('logged_in', 'no'); window.location.href = '/logout.php?t_location=ajaxjs&t_time=' + lastActivity + '&t_ntime=' + newTime + '&return_url=' + encodeURIComponent(window.location.pathname + window.location.search); } } }; // Localstorage/simpleStorage shim var AS = { _failoverStorage : {}, get : function(key) { var value; if(simpleStorage.canUse()) value = simpleStorage.get(key); else value = typeof(AS._failoverStorage[key]) !== 'undefined' ? AS._failoverStorage[key] : null; return value; }, set : function(key, value, TTL) { if(simpleStorage.canUse()) result = simpleStorage.set(key, value, TTL); else { AS._failoverStorage[key] = value; result = !!AS._failoverStorage[key]; } return value; } }; var D = { getCurrentDate: function(format) { var date, d, m, y, dateStr; date = new Date(); d = date.getDate(); m = date.getMonth() + 1; y = date.getFullYear(); switch(format) { case 'n/j/Y': dateStr = m + '/' + d + '/' + y; break; } return dateStr; }, getCurrentTime: function(format) { var date, h, newH, m, s, ampm, timeStr; date = new Date(); h = date.getHours(); m = date.getMinutes(); s = date.getSeconds(); ampm = h > 11 ? 'PM' : 'AM'; switch(format) { case 'g:i a': // do non military time, if it's 0, it is midnight newH = h > 12 ? h - 12 : (h === 0 ? 12 : h); timeStr = newH + ':' + m + ' ' + ampm; break; } return timeStr; }, getCurrentYear : function() { var date = new Date(); return date.getFullYear(); } }; var FAQ = { commonQuestions: {}, commonFaqs: {}, currentOpenPercent: 0, lastAttemptedTab : '', // Also check out a.js updateCommonQuestions : function(tabName) { FAQ.lastAttemptedTab = tabName; var foundEm = [], type, row; if(!$(FAQ.commonQuestions).length) return; $.each(FAQ.commonQuestions, function(index, data) { if(!data.tab || data.tab == tabName || data.tab == 'pageLoad') // added pageLoad for ATS-40250 to pull Main Page Load FAQs foundEm.push(data); }); $('#faq_common_questions_div').empty(); if(foundEm.length) { for(var i in foundEm) { row = foundEm[i]; type = row.faq_type_id == '1' ? 'faq-type-faq' : (row.faq_type_id == '4' ? 'faq-type-ug' : (row.faq_type_id == '3' ? 'faq-type-video' : (row.faq_type_id == '5' ? 'faq-type-qr-guide' : (row.faq_type_id == '6' ? 'faq-type-checklist' : '')))); $('#faq_common_questions_div').append(' '); } } }, // Also check out a.js updateCommonFaqButton : function(tabName) { var tabText = "", buttonText = "", hasCorrectTabArticles = false, hasCorrectPageArticles = false, faqRow, pathname = window.location.pathname, $button = $('#common_faq_button'); if(typeof(tabName) != 'undefined' && $button.length) { tabName = tabName.replace("tab_", ""); tabText = $('#tab_' + tabName + ' a').text(); // Find if there are any faq that can be viewed and if not, hide the button altogether. for(var i in FAQ.commonFaqs) { faqRow = FAQ.commonFaqs[i]; if(faqRow.tab == tabName && hasCorrectTabArticles == false) { hasCorrectTabArticles = true; } if(faqRow.main_page == pathname && hasCorrectPageArticles == false) hasCorrectPageArticles = true; } buttonText = hasCorrectTabArticles && tabText ? 'Common ' + tabText + ' Questions' : 'Common Questions'; $button.text(buttonText); if(hasCorrectTabArticles) $button.show().css('opacity', '1'); else $button.hide().css('opacity', '0'); } }, // Also check out a.js updateCommonQuestionsForLb : function(tabName) { // only store pre-lb tab if we're not coming from a previous lb if (!FAQ.tabBeforeLbOpen) { FAQ.tabBeforeLbOpen = FAQ.currentTab; } FAQ.updateCommonQuestions(tabName); FAQ.assignLbCloseEvent(); }, // Also check out a.js assignLbCloseEvent : function() { var i = 0; if($('.lb-close').length) { $('.lb-close').on('click.FAQUpdate', function() { FAQ.updateCommonQuestions(FAQ.tabBeforeLbOpen); FAQ.tabBeforeLbOpen = ''; }); } else { setTimeout(function() { i++; // Let this try for 10 seconds, if it doesn't work, something horrible is going on. if(i < 1000) FAQ.assignLbCloseEvent(); }, 10); } }, // Also check out a.js openBar : function(percent) { if(!percent) percent = 85; var newHeight = percent / 100; // Means this is open and less than it already is... if(percent < FAQ.currentOpenPercent) return; if($('.faq-bar-container').data('is-open') == 'true') return; $('#faqResults').css({ display: 'block' }); $("#faq_bar_form").css({ height: "100%", overflow: "auto" }); $("#faq_common_questions_div").css({ "flex-basis": "auto", "min-width": '0' }); $('.faq-bar-container').data('is-open', 'true'); $('.faq-bar-container').data('is-closed', 'false'); if(A.isMobile) { $('body,html').velocity('scroll', { complete : function() { $('body,html').css('overflow', 'hidden'); $('.main').css('position', 'fixed'); } }); } else { // Prevent the body from scrolling $('body,html').css('overflow', 'hidden'); } $('.faq-bar-right').show(); $('.faq-bar-close').velocity({ opacity : 1 }); $('.faq-bar-container').velocity({ height: $(window).height() * newHeight }, { complete : function() { FAQ.setFaqResultsHeight(); } }); if($('#searchParentCategory').is(':hidden')) { $('#searchParentCategory, #faqType, #faqVisibility').velocity('fadeIn'); } if($('#faq_contact_us_button').is(':hidden')) $('#faq_contact_us_button').velocity('fadeIn'); if($('#common_faq_button').length) { $('#common_faq_button').data('previous-state', ($('#common_faq_button').is(':visible') ? 'visible' : 'hidden')); $('#common_faq_button').velocity('fadeOut'); } $('#faq_bg').css({ width : $(document).width(), height : $(document).height() }).show().velocity({ opacity: 0.4 }); FAQ.currentOpenPercent = percent; }, // Also check out a.js closeBar : function() { if($('.faq-bar-container').data('is-closed') == 'true') return; $('#faq_bar_form').css({ height: '30px', overflow: 'hidden' }); $('#faq_common_questions_div').css({ 'flex-basis': '30%', 'min-width': '143px' }); $('.faq-bar-container').data('is-open', 'false'); $('.faq-bar-container').data('is-closed', 'true'); $('.faq-bar-right').hide(); $('.faq-bar-container').velocity({ height: 46 }); $('.faq-bar-close').velocity({ opacity : 0 }); $('#searchParentCategory, #searchSubCategory, #faqType, #faqVisibility, #faq_contact_us_button').velocity('fadeOut'); $('#faqResults').css({ height : 'auto', overflow : 'scroll', display : 'none' }); $('body,html').css('overflow', 'visible'); if(A.isMobile) $('.main').css('position', 'relative'); $('#faq_bg').css({ width : 0, height : 0 }).velocity('fadeOut'); if($('#common_faq_button').length && $('#common_faq_button').data('previous-state') == 'visible') $('#common_faq_button').velocity("fadeIn"); FAQ.currentOpenPercent = 0; }, // Also check out a.js setFaqResultsHeight : function() { var containerHeight = $(".faq-bar-container").height(); var formHeight = $(".faq-bar-main").height(); $('#faqResults').css("height", containerHeight - formHeight); } };