/* * Twix v1.0 - a lightweight library for making AJAX requests. * Author: Neil Cowburn (neilco@gmail.com) * * Copyright (c) 2013 Neil Cowburn (http://github.com/neilco/) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ var Twix=function(){function t(){}t.ajax=function(t){t=t||{url:""},t.type=t.type&&t.type.toUpperCase()||"GET",t.headers=t.headers||{},t.timeout=parseInt(t.timeout)||0,t.success=t.success||function(){},t.error=t.error||function(){},t.async="undefined"==typeof t.async?!0:t.async;var e=new XMLHttpRequest;t.timeout>0&&(e.timeout=t.timeout,e.ontimeout=function(){t.error("timeout","timeout",e)}),e.open(t.type,t.url,t.async);for(var s in t.headers)t.headers.hasOwnProperty(s)&&e.setRequestHeader(s,t.headers[s]);return e.send(t.data),e.onreadystatechange=function(){if(4==this.readyState&&(this.status>=200&&this.status<300||304==this.status)){var e=this.responseText,s=this.getResponseHeader("Content-Type");s&&s.match(/json/)&&(e=JSON.parse(this.responseText)),t.success(e,this.statusText,this)}else 4==this.readyState&&t.error(this.status,this.statusText,this)},0==t.async&&(4==e.readyState&&(e.status>=200&&e.status<300||304==e.status)?t.success(e.responseText,e):4==e.readyState&&t.error(e.status,e.statusText,e)),e};var e=function(e,s,n,r){return"function"==typeof n&&(r=n,n=void 0),t.ajax({url:s,data:n,type:e,success:r})};return t.get=function(t,s,n){return e("GET",t,s,n)},t.head=function(t,s,n){return e("HEAD",t,s,n)},t.post=function(t,s,n){return e("POST",t,s,n)},t.patch=function(t,s,n){return e("PATCH",t,s,n)},t.put=function(t,s,n){return e("PUT",t,s,n)},t["delete"]=function(t,s,n){return e("DELETE",t,s,n)},t.options=function(t,s,n){return e("OPTIONS",t,s,n)},t}();__=Twix; var global_common_domain = ''; function SetCommonDomain ( common_domain ) { global_common_domain = common_domain; } var qs_id_map = new Array(); qs_id_map['edit_lead_instance_id'] = {qs:'lead_instance_id',translate:'',active:'true'}; qs_id_map['edit_product_id'] = {qs:'product_id',translate:'',active:'true'}; qs_id_map['edit_afid'] = {qs:'afid',translate:'',active:'true'}; qs_id_map['edit_cid'] = {qs:'cid',translate:'',active:'true'}; qs_id_map['edit_crid'] = {qs:'crid',translate:'',active:'true'}; qs_id_map['edit_sid1'] = {qs:'sid1',translate:'',active:'true'}; qs_id_map['edit_sid2'] = {qs:'sid2',translate:'',active:'true'}; qs_id_map['edit_sid3'] = {qs:'sid3',translate:'',active:'true'}; qs_id_map['edit_sid4'] = {qs:'sid4',translate:'',active:'true'}; qs_id_map['edit_sid5'] = {qs:'sid5',translate:'',active:'true'}; qs_id_map['edit_click_instance_id'] = {qs:'click_instance_id',translate:'',active:'true'}; qs_id_map['edit_redirect_instance_id'] = {qs:'redirect_instance_id',translate:'',active:'true'}; qs_id_map['edit_campaign_id'] = {qs:'campaign_id',translate:'',active:'true'}; qs_id_map['edit_source_url'] = {qs:'edit_source_url',translate:'',active:'true'}; var post_data; var parsedQueries = []; function SetPrepopMap ( replacement_map ) { if ( Array.isArray ( replacement_map ) ) qs_id_map = replacement_map; } function PostTranslateData ( data ) { return data; } // Use the prepop map to select function SelectByIndex ( id ) { // Look for form data first, then query string data var value = SelectByName ( id ); if ( value === undefined || value == '' ) { if ( Array.isArray ( qs_id_map ) && ( id in qs_id_map ) ) value = SelectByName ( qs_id_map[id].qs ); } return ( value ); } // // get / post manipulation // function SelectByName ( name ) { var value; // Post first so data from the form will override anything that was passed and is being carried along value = SelectPostByName ( name ); if ( value === undefined || value == '' ) value = SelectGetByName ( name ); return ( value ); } function SetPostData ( data ) { if ( data === undefined ) data = ''; post_data = data; } function GetPostData() { return ( post_data ); } function SelectPostByName ( name ) { return ( SelectWithDataByName ( name, post_data ) ); } function SelectGetByName ( name ) { return ( SelectWithDataByName ( name, window.location.href ) ); } function ParseQueryString() { var vars = window.location.search.replace(/^\?/, '').split("&"); var query_string = {}; for (var i = 0; i < vars.length; i++) { var pair = vars[i].split("="); var key = decodeURIComponent(pair[0]); var value = decodeURIComponent(pair[1]); // If first entry with this name if (typeof query_string[key] === "undefined") { query_string[key] = decodeURIComponent(value); // If second entry with this name } else if (typeof query_string[key] === "string") { var arr = [query_string[key], decodeURIComponent(value)]; query_string[key] = arr; // If third or later entry with this name } else { query_string[key].push(decodeURIComponent(value)); } } return query_string; } function SelectWithDataByName ( name, qs ) { if (qs === undefined || qs === '') { return '' } if (parsedQueries[qs] === undefined) { parsedQueries[qs] = (qs != '') ? ParseQueryString() : {}; } return parsedQueries[qs][name] || ''; } function CapturePostData ( form_id ) { var post_data = ''; $(':input', '#' + form_id).each(function() { if ( this.name != '' ) post_data = post_data + '&' + this.name + '=' + encodeURIComponent(this.value); }); SetPostData ( post_data ); } //Accounts for radio buttons and created for e-sign flows. **Disclaimer** double-check functionality if used for other sites function CaptureSelectedPostData ( form_id ) { var post_data = ''; $(':input', '#' + form_id).each(function() { if ( $('#' + this.id).is(':checked' ) || this.type !== 'radio' || this.value === '') { post_data = post_data + '&' + this.name + '=' + encodeURIComponent(this.value); } }); SetPostData ( post_data ); } function InfoForZip ( zip, request_async, control ) { var geo_interface = global_common_domain + '/lead.php' if ( typeof request_async === undefined ) request_async = false; if ( typeof control === undefined ) control = ''; var zip_info = ''; var request = { request: 'lead_zip_to_geo', zip: zip }; var json = JSON.stringify( request ); json = encodeURIComponent ( json ); var http_request = geo_interface + "?request=" + json; // Submit $.ajax({ url: http_request, dataType: 'json', async: request_async, control: control, zip_info: zip_info, success: function(json) { var valid = json.response_code; if ( valid === 1 ) { field_valid = true; zip_info = json.response_data; if ( control === undefined || control == '' ) ; else $('#' + control).val(zip_info); } }, error: function error(jqXHR, textStatus, errorThrown) { var error = jqXHR.responseText; } }) return ( zip_info ); } function IPToGeo ( ip, request_async, control, control_type, control_format, default_value ) { var geo_interface = global_common_domain + '/lead.php' if ( typeof request_async === undefined ) request_async = false; var geo = new Object(); geo.country_code = ''; geo.region_code = ''; geo.city_name = ''; geo.latitude = ''; geo.longitude = ''; var request = new Object(); request.request = 'lead_ip_to_geo'; request.ip = ip; if ( request.ip == '127.0.0.1' ) request.ip = '162.209.76.133'; else if (request.ip == '172.23.0.1') request.ip = '162.209.76.133'; var json = JSON.stringify( request ); json = encodeURIComponent ( json ); var http_request = geo_interface + "?request=" + json; return new Promise(function(resolve, reject) { $.ajax({ url: http_request, dataType: 'json', async: request_async, control: control, control_type: control_type, control_format: control_format, default_value: default_value, success: function(json) { var valid = json.response_code; if ( valid === 1 ) { field_valid = true; var parsed = jQuery.parseJSON ( json.response_data ); geo.country_code= parsed.country_code; geo.country_name= parsed.country_name; geo.region_name = parsed.region_name; geo.region_code = parsed.region_code; geo.city_name = parsed.city_name; geo.latitude = parsed.latitude; geo.longitude = parsed.longitude; if ( control === undefined || control == '' ) ; else { if ( control_type === undefined || control_type == '' ) control_type = 'html'; if ( control_format === undefined || control_format == '' ) control_format = '%%city_name%%, %%region_code%%'; if ( default_value === undefined || default_value == '' ) default_value = ''; if ( control_format == 'json' ) control_format = json.response_data; else { control_format = control_format.replace ( '%%country_code%%', geo.country_code ); control_format = control_format.replace ( '%%region_code%%', geo.region_code ); control_format = control_format.replace ( '%%region_name%%', geo.region_name ); control_format = control_format.replace ( '%%city_name%%', geo.city_name ); control_format = control_format.replace ( '%%latitude%%', geo.latitude ); control_format = control_format.replace ( '%%longitude%%', geo.longitude ); } if ( parsed.error == 'IP_NOT_FOUND' ) control_format = default_value; switch ( control_type ) { case 'html': $('#' + control).html(control_format); break; case 'value': $('#' + control).val(control_format); break; } } } }, error: function error(jqXHR, textStatus, errorThrown) { var error = jqXHR.responseText; } }) }); } var lead_interface = global_common_domain + '/lead.php'; var service_interface = global_common_domain + '/validate.php'; (function(){ if ( global_common_domain == undefined || global_common_domain === null || typeof global_common_domain === 'undefined' || global_common_domain == '') global_common_domain = ''; common_domain_base = global_common_domain.toLowerCase().replace ( 'http://', '' ).replace ( 'https://', '' ).replace ( 'local.', '' ).replace ( 'dev.', '' ).replace ( 'staging.', '' ); if (global_common_domain === '') { lead_interface = '/lead.php'; } else { lead_interface = global_common_domain + '/lead.php'; //Production default re = /^local./; match = re.test(window.location.hostname); if (match) lead_interface = 'http://local.' + common_domain_base + '/lead.php'; re = /^dev./; match = re.test(window.location.hostname); if (match) lead_interface = 'http://dev.' + common_domain_base + '/lead.php'; re = /^staging./; match = re.test(window.location.hostname); if (match) lead_interface = 'http://staging.' + common_domain_base + '/lead.php'; } })(); // Update lead data in database function LeadSaveData ( async_call, override, additional_data ) { if ( async_call === undefined ) async_call = true; var lead_instance_id = SelectByIndex ( 'edit_lead_instance_id' ); var product_id = SelectByIndex ( 'edit_product_id' ); var email = SelectByIndex ( 'edit_email' ); if ( email === '' || email === undefined ) email = SelectByIndex ( 'email' ); var crid = SelectByIndex ( 'edit_crid' ); // Is crid at least 9 digit number? var crid_valid = /^[0-9]{9,}$/.test(crid); if ( crid_valid === false ) { // Okay, get all the matching ones var new_crid = window.location.href.toLowerCase().match ( /crid=[^&]+/g ); if ( Array.isArray ( new_crid ) ) { for ( i = 0; i < new_crid.length; i++ ) { crid = new_crid[i]; crid = crid.replace ( "crid=", "" ); if ( /^[0-9]{9,}$/.test(crid) ) break; // Since our crid will come first from our Cake links, use the first matching one } } } var afid = SelectByIndex ( 'edit_afid' ); var cid = SelectByIndex ( 'edit_cid' ); // Is creative_id a digit? var cid_valid = /^\d+$/.test(cid); if ( cid_valid === false ) { // Okay, get all the matching ones var new_cid = window.location.href.toLowerCase().match ( /cid=[^&]+/g ); if ( Array.isArray ( new_cid ) ) { for ( i = 0; i < new_cid.length; i++ ) { cid = new_cid[i]; cid = cid.replace ( "cid=", "" ); if ( /^\d+$/.test(cid) ) break; // Since our cid will come first from our Cake links, use the first matching one } } } var redirect_instance_id = SelectByIndex ( 'edit_redirect_instance_id' ); var click_instance_id = SelectByIndex ( 'edit_click_instance_id' ); var campaign_id = SelectByIndex ( 'edit_campaign_id' ); // Is campaign_id a 4 digit or less number? var campaign_id_valid = /^[0-9]{1,4}$/.test(campaign_id); if ( campaign_id_valid === false ) { // Okay, get all the matching ones var new_cid = window.location.href.toLowerCase().match ( /campaign_id=[^&]+/g ); if ( Array.isArray ( new_cid ) ) { for ( i = 0; i < new_cid.length; i++ ) { campaign_id = new_cid[i]; campaign_id = campaign_id.replace ( "campaign_id=", "" ); if ( /^[0-9]{1,4}$/.test(campaign_id) ) break; // Since our campaign_id will come first from our Cake links, use the first matching one } } } var sid1 = SelectByIndex ( 'edit_sid1' ); var sid2 = SelectByIndex ( 'edit_sid2' ); var sid3 = SelectByIndex ( 'edit_sid3' ); var lid_control = 'edit_lead_instance_id'; var data_source = window.location.href.split(/[?&]/)[0].split('/').pop(); var post_data = GetPostData(); var get_data = window.location.search.replace(/^(\?)/, ''); // Get source_url if not present var source_url = SelectByIndex ( 'edit_source_url' ); if ( source_url === undefined || source_url == '' ) { source_url = [location.protocol, '//', location.host, location.pathname].join(''); $('#edit_source_url').val(source_url); } if ( override != undefined && override !== null && typeof override === 'object' ) { $.each(override, function( index, data ) { switch ( index ) { case 'afid': afid = data; break; case 'crid': crid = data; break; case 'cid': cid = data; break; case 'campaign_id': campaign_id = data; break; case 'edit_lead_instance_id': lead_instance_id = data; break; case 'edit_email': email = data; break; } }); } // May need to do post translations on some fields if ( PostTranslateData != undefined ) post_data = PostTranslateData ( post_data ); // Product id is hardcoded in the form if ( product_id === undefined || product_id == '' ) product_id = $('#edit_product_id').val(); // Append source URL if needed if ( post_data === undefined || post_data == '' ) ; else { var check = SelectPostByName ( 'edit_source_url' ); if ( check === undefined || check == '' ) post_data = post_data + '&edit_source_url=' + source_url; } if ( get_data === undefined || get_data == '' ) ; else { var check = SelectGetByName ( 'edit_source_url' ); if ( check === undefined || check == '' ) get_data = get_data + '&edit_source_url=' + source_url; } var lead_is_unique = null; if ( $('#lead_is_unique').length != 0 ) lead_is_unique = $('#lead_is_unique').val(); LeadInstanceUpdate ( async_call, lead_instance_id, product_id, email, crid, afid, cid, redirect_instance_id, click_instance_id, campaign_id, data_source, post_data, get_data, sid1, sid2, sid3, lid_control, additional_data, lead_is_unique ); } function LeadInstanceUpdate ( async_call, lead_instance_id, product_id, email, crid, afid, cid, redirect_instance_id, click_instance_id, campaign_id, data_source, post_data, get_data, sid1, sid2, sid3, lid_control, additional_data, lead_is_unique ) { var request = new Object(); if ( additional_data === undefined ) additional_data = ''; if ( lead_is_unique === undefined ) lead_is_unique = null; request.request = 'lead_instance_update'; request.lead_instance_id = lead_instance_id; request.product_id = product_id; request.email = email; request.crid = ( crid === undefined ) ? '' : crid; request.afid = ( afid === undefined ) ? '' : afid; request.cid = ( cid === undefined ) ? '' : cid; request.redirect_instance_id = ( redirect_instance_id === undefined ) ? '' : redirect_instance_id; request.click_instance_id = ( click_instance_id === undefined ) ? '' : click_instance_id; request.campaign_id = ( campaign_id === undefined ) ? '' : campaign_id; request.data_source = ( data_source === undefined ) ? '' : data_source; request.post_data = ( post_data === undefined ) ? '' : post_data; request.get_data = ( get_data === undefined ) ? '' : get_data; request.sid1 = ( sid1 === undefined ) ? '' : sid1; request.sid2 = ( sid2 === undefined ) ? '' : sid2; request.sid3 = ( sid3 === undefined ) ? '' : sid3; request.additional_data = additional_data; request.lead_is_unique = lead_is_unique; var json = JSON.stringify( request ); json = encodeURIComponent ( json ); var http_request = lead_interface; var request_data = "&request=" + json; try { Twix.ajax({ url: http_request, type: 'POST', data: request_data, async: async_call, headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, success: function (response) { var lead_instance_id = 0; var json = JSON.parse(response); var valid = json.response_code; if ( valid === 1 ) { var parsed = jQuery.parseJSON ( json.response_data ); lead_instance_id = parsed.lead_instance_id; } $('#' + lid_control).val ( lead_instance_id ); } }); } catch (e) { console.log(e); } } // Record trace event function LeadTrace ( event, async_call ) { if ( async_call === undefined ) async_call = true; var re = /.dev$/; var match = re.test( window.location.hostname ); if ( match ) lead_interface = 'http://common.dev/lead.php' var lead_instance_id = SelectByIndex ( 'edit_lead_instance_id' ); if ( lead_instance_id === undefined || lead_instance_id == '' ) lead_instance_id = $('#edit_lead_instance_id').val(); var request = new Object(); request.request = 'lead_instance_trace'; request.lead_instance_id = lead_instance_id; request.event = event; var json = JSON.stringify( request ); json = encodeURIComponent ( json ); var http_request = lead_interface; var request_data = "&request=" + json; // Submit $.ajax({ url: http_request, data: request_data, dataType: 'json', type: 'POST', async: async_call, success: function(json) { var valid = json.response_code; if ( valid === 1 ) ; }, error: function error(jqXHR, textStatus, errorThrown) { var error = jqXHR.responseText; } }) } function LeadSubmit ( async_call, response_control ) { if ( async_call === undefined ) async_call = true; $('#' + response_control).val ( '' ); var request = new Object(); var lead_instance_id = SelectByIndex ( 'edit_lead_instance_id' ); if ( lead_instance_id === undefined || lead_instance_id == '' ) lead_instance_id = $('#edit_lead_instance_id').val(); var product_id = SelectByIndex ( 'edit_product_id' ); if ( product_id === undefined || product_id == '' ) product_id = $('#edit_product_id').val(); var routing = SelectByIndex ( 'edit_routing' ); if ( routing === undefined || routing == '' ) routing = $('#edit_routing').val(); var ping_cid = SelectByIndex ( 'ping_cid' ); if ( ping_cid === undefined || ping_cid == '' ) ping_cid = $('#ping_cid').val(); var ping_key = SelectByIndex ( 'ping_key' ); if ( ping_key === undefined || ping_key == '' ) ping_key = $('#ping_key').val(); request.request = 'lead_instance_submit'; request.lead_instance_id = lead_instance_id; request.product_id = product_id; request.post_data = GetPostData(); request.routing = routing; request.ping_cid = ping_cid; request.ping_key = ping_key; request.source_site = window.location.href.toLowerCase().replace ( 'http://', '' ).replace ( 'https://', '' ).split(/[?&]/)[0].split('/')[0]; var json = JSON.stringify( request ); json = encodeURIComponent ( json ); var http_request = lead_interface; var request_data = "&request=" + json; // Submit $.ajax({ url: http_request, data: request_data, dataType: 'json', type: 'POST', async: async_call, success: function(json) { var redirect_url = ''; var valid = json.response_code; if ( valid === 1 ) ; if ( response_control != undefined ) $('#' + response_control).val ( json.response_data ); }, error: function error(jqXHR, textStatus, errorThrown) { var error = jqXHR.responseText; } }) } /** * Helper function for verifying phone numbers * * @param value * @returns {Promise} * @constructor */ function VerifyPhone(value) { return new Promise(function(resolve, reject) { var request = { request: 'validate_phone_format', phone: value, domain: document.domain, lead_instance_id: $('#edit_lead_instance_id').val() }; var json = JSON.stringify( request ); json = encodeURIComponent ( json ); var http_request = service_interface + "?request=" + json; $.ajax({ url: http_request, dataType: 'json', async: true, success: function(json) { var valid = json.response_code; if ( valid === 1 ) resolve(true); else reject(false); }, error: function error(jqXHR, textStatus, errorThrown) { var error = jqXHR.responseText; reject(false); } }) }).then(function(data) { return new Promise(function(resolve, reject) { var request = { request: 'validate_phone', phone: value, domain: document.domain, lead_instance_id: $('#edit_lead_instance_id').val() }; var json = JSON.stringify( request ); json = encodeURIComponent ( json ); var http_request = service_interface + "?request=" + json; // Submit $.ajax({ url: http_request, dataType: 'json', async: true, success: function(json) { var valid = json.response_code; var enforce = parseInt(json.phone_enforce); if ( valid === 1 ) resolve(true); else { if ( enforce > 0 ) reject(false); else resolve(true); } }, error: function error(jqXHR, textStatus, errorThrown) { var error = jqXHR.responseText; reject(error); } }) }); }); } /** * Validate emails with server-side database(s) * * @param value * @returns {Promise} * @constructor */ function VerifyEmail(value) { return new Promise(function(resolve, reject) { // Basic syntax check first var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var field_valid = re.test(value); if (!field_valid) reject(false); if ( field_valid) { var request = new Object(); request.request = 'validate_email'; request.email = value; request.domain = document.domain; request.lead_instance_id = $('#edit_lead_instance_id').val(); var json = JSON.stringify( request ); json = encodeURIComponent ( json ); var http_request = service_interface + "?request=" + json; // Submit $.ajax({ url: http_request, dataType: 'json', async: true, success: function(json) { var valid = json.response_code; if ( valid === 1 ) resolve(true) else { if ( json.email_enforce > 0 ) reject(false); // invalid email else resolve(true); } }, error: function error(jqXHR, textStatus, errorThrown) { var error = jqXHR.responseText; reject(error); } }) } }); } /** * Verify Zip codes with server-side database(s) * @param value * @returns {Promise} * @constructor */ function VerifyZip(value) { return new Promise(function() { function ValidateZip ( value, control_id, error_class, request_async ) { var field_valid = true; if ( typeof request_async === 'undefined' ) request_async = true; RemoveClass ( control_id, error_class ); field_valid = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(value); if ( field_valid == true ) { var request = new Object(); request.request = 'validate_zip'; request.zip = value; var json = JSON.stringify( request ); json = encodeURIComponent ( json ); var http_request = service_interface + "?request=" + json; // Submit $.ajax({ url: http_request, dataType: 'json', async: request_async, success: function(json) { field_valid = false; var valid = json.response_code; if ( valid === 1 ) field_valid = true; else AddClass ( control_id, error_class ); }, error: function error(jqXHR, textStatus, errorThrown) { var error = jqXHR.responseText; } }) } if ( field_valid === false ) AddClass ( control_id, error_class ); return ( field_valid ); } }); } function TrackSetLinkPlacementIDs ( track, parameter ) { $.each(track, function( control, value ) { var href = $('#' + value.control).attr('href'); if ( href != null && href != '' ) { var new_value = TrackReplaceByName ( parameter, href, value.id ); var href = $('#' + value.control).attr('href',new_value); } }); } function TrackSetLinkPlacementValue ( track, parameter, updated_value ) { $.each(track, function( control, value ) { var href = $('#' + value.control).attr('href'); if ( href != null && href != '' ) { var new_value = TrackReplaceByName ( parameter, href, updated_value ); var href = $('#' + value.control).attr('href',new_value); } }); } function TrackReplaceByName ( name, url, value ) { var new_parameter = name + '=' + encodeURIComponent ( value ) name = name.replace(/[\[\]]/g, "\\$&"); var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"); var results = regex.exec(url); // Query string parameter not there if (!results) { if ( url.indexOf('?') != -1 || url.indexOf('&') != -1 ) url = url + '&' + new_parameter; else { if ( url.charAt(url.length - 1) != '/' ) url = url + '/'; url = url + '?' + new_parameter; } } else { var existing_parameter = name + '=' + results[2]; url = url.replace ( existing_parameter, new_parameter ); } return ( url ); } var service_interface = global_common_domain + '/validate.php' var controls_to_validate; var associated_controls; var validate_error_messages; $(document).ready(function(){ // Default error messages validate_error_messages = new Array(); validate_error_messages['paydates.no_error'] = ''; validate_error_messages['paydates.paydate1_invalid'] = 'Paydate 1 invalid'; validate_error_messages['paydates.paydate2_invalid'] = 'Paydate 2 invalid'; validate_error_messages['paydates.paydate_payperiod_mismatch'] = 'Paydates don\'t match pay period'; validate_error_messages['paydates.paydate2_future'] = 'Paydate 2 must be within 63 days'; validate_error_messages['paydates.paydate2_past'] = 'Paydate 1 must be at least 7 days from now'; validate_error_messages['paydates.paydate1_weekend'] = 'Paydate 1 can not be on a weekend'; validate_error_messages['paydates.paydate2_weekend'] = 'Paydate 2 can not be on a weekend'; validate_error_messages['paydates.paydate1_paydate2_relative'] = 'Paydate 2 must be later than Paydate 1'; validate_error_messages['address.no_error'] = ''; validate_error_messages['address.city_state_zip_mismatch'] = 'City, State, and Zip don\'t match'; validate_error_messages['address.suggested_cities'] = 'Cities that match this zip: %%cities%%'; var re = /.dev$/; var match = re.test( window.location.hostname ); if ( match ) service_interface = 'http://common.dev/validate.php' // Build array of all controls to validate, they will have a vtype attribute set controls_to_validate = new Array(); associated_controls = new Array(); $("[vtype]").attr('id',function(index,id) { var vtype = $('#' + id).attr('vtype'); if ( vtype == '' || vtype === undefined ) ; else { // Css class to show errors, default is error var error_class = $('#' + id).attr('vclass'); if ( error_class == '' || error_class === undefined ) error_class = "error"; // Callbacks for application specific processing var pre_callback = $('#' + id).attr('vprecall'); if ( pre_callback === undefined ) pre_callback = ""; var post_callback = $('#' + id).attr('vpostcall'); if ( post_callback === undefined ) post_callback = ""; var error_callback = $('#' + id).attr('verrorcall'); if ( error_callback === undefined ) error_callback = ""; // Optional semicolon delimited data var validation_data = $('#' + id).attr('vdata'); if ( validation_data === undefined ) validation_data = ""; // If we need to validate on change var validate_on_change = $('#' + id).attr('vchange'); if ( validate_on_change === undefined ) validate_on_change = ""; // If part of a tagged group var vtag = $('#' + id).attr('vtag'); if ( vtag === undefined ) vtag = ""; // Pattern for regex criteria var vpattern = $('#' + id).attr('vpattern'); if ( vpattern === undefined ) vpattern = ""; // Storage for detail validation data var vlogdata = $('#' + id).attr('vlogdata'); if ( vlogdata === undefined ) vlogdata = ""; // Save it var validate = new Object(); validate.id = id; validate.type = vtype; validate.error_class = error_class; validate.pre_callback = pre_callback; validate.post_callback = post_callback; validate.error_callback = error_callback; validate.validate_on_change = validate_on_change; validate.vtag = vtag; validate.vpattern = vpattern; validate.vlogdata = vlogdata; // Validation data needs a bit more handling validate.validation_data = new Object(); validation_data = validation_data.split(';'); $.each(validation_data, function( index, data ) { var pair = data.split('='); if ( pair.length == 2 ) validate.validation_data[pair[0]] = pair[1]; }); controls_to_validate.push ( validate ); } }); // Build a blur function for each control that needs validation, optionally do for onchange as well $.each(controls_to_validate, function( index, validate ) { $('#' + validate.id).blur(validate, function(control) { if ( $('#' + validate.id).is(':visible') ) ValidateByValidationType ( control.data ); }); if ( validate.validate_on_change != undefined && validate.validate_on_change != '' ) { $('#' + validate.id).change(validate, function(control) { if ( $('#' + validate.id).is(':visible') ) ValidateByValidationType ( control.data ); }); } }); }); function AssociateControls (root_id, associated) { var obj = new Object(); obj.root_id = root_id; obj.data = associated; associated_controls.push(obj); } function GetAssociatedControls ( root_id ) { var associated = null; $.each(associated_controls, function( index, controls ) { if ( controls.root_id == root_id ) { associated = controls.data; return false; } }); return ( associated ); } function ValidateControls ( vtag ) { var allow_submit = true; $.each(controls_to_validate, function( index, validate ) { if ( $('#' + validate.id).is(':visible') ) { if ( vtag === undefined || vtag == '' || validate.vtag == vtag ) { ret = ValidateByValidationType ( validate, false ); if ( !ret ) allow_submit = false; } } }); return ( allow_submit ); } function ValidateByValidationType ( validate, async ) { var valid = false; if ( async === undefined ) async = true; if ( typeof validate === 'object' ) { var value = $('#' + validate.id).val(); if ( validate.pre_callback == '' || validate.pre_callback === undefined ) ; else eval ( validate.pre_callback ); switch ( validate.type ) { case 'name': valid = ValidateName ( value, validate.id, validate.error_class ); break; case 'email': valid = ValidateEmail ( value, false, validate.id, validate.error_class, async ); break; case 'email_format': valid = ValidateEmail ( value, true, validate.id, validate.error_class, async ); break; case 'string': valid = ValidateString ( value, validate.id, validate.error_class, validate.validation_data.minlength, validate.validation_data.maxlength, validate.vpattern ); break; case 'integer': valid = ValidateInteger ( value, validate.id, validate.error_class, validate.validation_data.minlength, validate.validation_data.maxlength ); break; case 'ssn': valid = ValidateSsn ( value, validate.id, validate.error_class ); break; case 'phone': valid = ValidatePhone ( value, validate.id, validate.error_class, false, async, validate.vlogdata ); break; case 'phone_format': valid = ValidatePhone ( value, validate.id, validate.error_class, true, async ); break; case 'phone_format_silent_phone': valid = ValidatePhone ( value, validate.id, validate.error_class, true, async, '', true ); break; case 'date': valid = ValidateDate ( value, validate.id, validate.error_class ); break; case 'not_empty': valid = ValidateAgainstSet ( value, validate.id, validate.error_class, ['',null,0] ); break; case 'address': var associated = GetAssociatedControls ( validate.id ); var address = new Object(); address.address = $('#' + associated.address).val(); address.city = $('#' + associated.city).val(); address.state = $('#' + associated.state).val(); address.zip = $('#' + associated.zip).val(); address.reason = validate_error_messages['address.no_error']; address.suggestions = ''; valid = ValidateAddress ( address, [associated.address, associated.city, associated.state, associated.zip], validate.error_class, associated, validate.post_callback, async ); break; case 'zip': valid = ValidateZip ( value, validate.id, validate.error_class, async ); break; case 'paydate': var associated = GetAssociatedControls ( validate.id ); var payinfo = new Object(); payinfo.paydate1 = $('#' + associated.paydate1).val(); payinfo.paydate2 = $('#' + associated.paydate2).val(); payinfo.payperiod = $('#' + associated.payperiod).val(); payinfo.reason = validate_error_messages['paydates.no_error']; valid = ValidatePaydates ( payinfo, associated.paydate1, associated.paydate2, validate.error_class ); $('#' + associated.error_text).val(payinfo.reason); break; case 'aba': var associated = GetAssociatedControls ( validate.id ); var bank = new Object(); bank.aba = value; bank.name = ''; bank.address = ''; bank.phone = ''; valid = ValidateAba ( bank, false, [associated.aba, associated.bankname, associated.bankaddress, associated.bankphone], validate.error_class, associated, validate.post_callback, async ); break; }; if ( !valid ) { if ( validate.error_callback == '' || validate.error_callback === undefined ) ; else { var err_callback = validate.error_callback; err_callback = err_callback.replace ( '%%control_id%%', validate.id ); eval ( err_callback ); } } if ( validate.post_callback == '' || validate.post_callback === undefined ) ; else { var p_callback = validate.post_callback; p_callback = p_callback.replace ( '%%control_id%%', validate.id ); eval ( p_callback ); } } return ( valid ); } function ValidateName ( name, control_id, error_class ) { var field_valid = false; RemoveClass ( control_id, error_class ); if ( typeof name === 'string' ) { if ( name.length >= 2 ) field_valid = true; } if ( field_valid === false ) AddClass ( control_id, error_class ); return ( field_valid ); } function ValidateAgainstSet ( value, control_id, error_class, disallow, allow ) { var field_valid = false; var set_valid; RemoveClass ( control_id, error_class ); // Check disallow list first set_valid = true; if ( typeof disallow !== 'undefined' && typeof value !== 'undefined' ) { if ( typeof disallow === 'object' && Array.isArray ( disallow ) ) { if ($.inArray ( value, disallow ) !== -1) set_valid = false; } else { if ( disallow == value ) set_valid = false; } field_valid = set_valid; } else { // Check against allow list then set_valid = false; if ( typeof allow !== 'undefined' && typeof value !== 'undefined' ) { if ( typeof allow === 'object' && Array.isArray ( disallow ) ) { if ($.inArray ( value, allow ) !== -1) set_valid = true; } else { if ( allow == value ) set_valid = true; } field_valid = set_valid; } } if ( field_valid === false ) AddClass ( control_id, error_class ); return ( field_valid ); } function ValidateState ( state, control_id, error_class ) { var field_valid = false; RemoveClass ( control_id, error_class ); state = state.toLowercase(); if ( state == 'ny' ) field_valid = false; if ( field_valid === false ) AddClass ( control_id, error_class ); return ( field_valid ); } function ValidateAddress ( address, control_id, error_class, associated, post_callback, request_async ) { var field_valid = false; // For tracking duplicate requests if ( typeof ValidateAddress.last_request == 'undefined' ) ValidateAddress.last_request = ''; if ( typeof ValidateAddress.last_result == 'undefined' ) ValidateAddress.last_result = ''; if ( typeof ValidateAddress.last_error_text == 'undefined' ) ValidateAddress.last_error_text = ''; if ( typeof ValidateAddress.last_suggestions == 'undefined' ) ValidateAddress.last_suggestions = ''; if ( typeof request_async === 'undefined' ) request_async = true; RemoveClass ( control_id, error_class ); // Don't bother validating unless we have something in every field if ( address != undefined && address.address != undefined && address.city != undefined && address.state != undefined && address.zip != undefined && address.address.length > 0 && address.city.length > 0 && address.state.length > 0 && address.zip.length > 0 ) { // Avoid duplicate requests var summary_request = address.address + address.city + address.state + address.zip; if ( summary_request == ValidateAddress.last_request ) { field_valid = ValidateAddress.last_result; if ( field_valid === false ) AddClass ( control_id, error_class ); // Save prior error text and suggestions $('#' + associated.error_text).val(ValidateAddress.last_error_text); $('#' + associated.suggestions).val(ValidateAddress.last_suggestions); } else { ValidateAddress.last_request = summary_request; ValidateAddress.last_result = ''; ValidateAddress.last_error_text = ''; ValidateAddress.last_suggestions = ''; var request = new Object(); request.request = 'validate_address'; request.address = address.address; request.city = address.city; request.state = address.state; request.zip = address.zip; var json = JSON.stringify( request ); json = encodeURIComponent ( json ); var http_request = service_interface + "?request=" + json; // Submit $.ajax({ url: http_request, dataType: 'json', async: request_async, success: function(json) { var valid = json.response_code; if ( valid === 1 ) field_valid = true; else { AddClass ( control_id, error_class ); address.reason = validate_error_messages['address.city_state_zip_mismatch']; } // Get city suggestions address.suggestions = ''; var parsed = jQuery.parseJSON ( json.response_data ); if ( parsed.alt_cities != '' && parsed.alt_cities != undefined ) { var cities = parsed.alt_cities.replace(/;/g,', '); address.suggestions = validate_error_messages['address.suggested_cities'].replace ( '%%cities%%', cities ); } // Save error text and suggestions $('#' + associated.error_text).val(address.reason); $('#' + associated.suggestions).val(address.suggestions); // Perform callback if ( request_async && post_callback != undefined && post_callback != '' ) eval ( post_callback ); if ( field_valid === false ) AddClass ( control_id, error_class ); ValidateAddress.last_result = field_valid; ValidateAddress.last_error_text = address.reason; ValidateAddress.last_suggestions = address.suggestions; }, error: function error(jqXHR, textStatus, errorThrown) { var error = jqXHR.responseText; } }) } } else { // Just tag empty fields if ( address.address == undefined || address.address == '' ) AddClass ( associated.address, error_class ); if ( address.city == undefined || address.city == '' ) AddClass ( associated.city, error_class ); if ( address.state == undefined || address.state == '' ) AddClass ( associated.state, error_class ); if ( address.zip == undefined || address.zip == '' ) AddClass ( associated.zip, error_class ); } return ( field_valid ); } function ValidateAba ( bank, format_only, control_id, error_class, associated, post_callback, request_async ) { var field_valid = false; var process_async = false; // For tracking duplicate requests if ( typeof ValidateAba.last_request == 'undefined' ) ValidateAddress.last_request = ''; if ( typeof ValidateAba.last_result == 'undefined' ) ValidateAddress.last_result = ''; if ( typeof request_async === 'undefined' ) request_async = true; RemoveClass ( control_id, error_class ); field_valid = /^[0-9]+$/.test(bank.aba); if ( field_valid ) { if ( bank.aba.length == 9 ) { // Do the checksum n = 0; for (i = 0; i < bank.aba.length; i += 3) { n += parseInt(bank.aba.charAt(i), 10) * 3 + parseInt(bank.aba.charAt(i + 1), 10) * 7 + parseInt(bank.aba.charAt(i + 2), 10); } if ( n != 0 && n % 10 == 0 ) { if ( format_only == false ) { process_async = request_async; if ( bank.aba == ValidateAba.last_request ) { field_valid = ValidateAba.last_result; if ( !field_valid ) AddClass ( control_id, error_class ); } else { ValidateAba.last_request = bank.aba; ValidateAba.last_result = ''; var request = new Object(); request.request = 'validate_aba'; request.aba = bank.aba; var json = JSON.stringify( request ); json = encodeURIComponent ( json ); var http_request = service_interface + "?request=" + json; // Submit $.ajax({ url: http_request, dataType: 'json', async: request_async, success: function(json) { var valid = json.response_code; if ( valid === 1 ) { field_valid = true; var parsed = jQuery.parseJSON ( json.response_data ); bank.aba = parsed.routing_number; bank.name = parsed.bank_name; bank.address = parsed.bank_address; bank.phone = parsed.bank_phone; $('#' + associated.bankname).val(bank.name); $('#' + associated.bankaddress).val(bank.address); $('#' + associated.bankphone).val(bank.phone); } else AddClass ( control_id, error_class ); ValidateAba.last_result = field_valid; }, error: function error(jqXHR, textStatus, errorThrown) { var error = jqXHR.responseText; } }) } } else field_valid = true; } else field_valid = false; } else field_valid = false; } if ( !process_async && field_valid === false ) AddClass ( control_id, error_class ); return ( field_valid ); } function ValidatePaydates ( payinfo, control_1, control_2, error_class ) { var field_valid = true; RemoveClass ( control_1, error_class ); RemoveClass ( control_2, error_class ); field_valid = ValidateDate ( payinfo.paydate1, control_1, error_class ); if ( field_valid == true ) { field_valid = ValidateDate ( payinfo.paydate2, control_2, error_class ); if ( field_valid == true ) { // Validate time relationships var now = new Date(); now.setHours(0); now.setMinutes(0); now.setSeconds(0); now.setMilliseconds(0); var pd1 = new Date(payinfo.paydate1); var pd2 = new Date(payinfo.paydate2); // Paydate2 must be later if ( field_valid ) { if ( pd1 >= pd2 ) { field_valid = false; AddClass ( control_1, error_class ); payinfo.reason = validate_error_messages['paydates.paydate1_paydate2_relative']; } } // Be sure neither is on a weekend if ( field_valid ) { var pd1_day = pd1.getDay(); var pd2_day = pd2.getDay(); if ( pd1_day == 0 || pd1_day == 6 ) { field_valid = false; AddClass ( control_1, error_class ); payinfo.reason = validate_error_messages['paydates.paydate1_weekend']; } if ( pd2_day == 0 || pd2_day == 6 ) { field_valid = false; AddClass ( control_2, error_class ); payinfo.reason = validate_error_messages['paydates.paydate2_weekend']; } } // First paydate must be 7 days from now if ( field_valid ) { if ( pd1 - now < 604800000 ) { AddClass ( control_1, error_class ); field_valid = false; payinfo.reason = validate_error_messages['paydates.paydate2_past']; } } // Second no more than 63 if ( field_valid ) { if ( pd2 - now > 5443200000 ) { AddClass ( control_2, error_class ); field_valid = false; payinfo.reason = validate_error_messages['paydates.paydate2_future']; } } // Dates must match period if ( field_valid ) { switch ( payinfo.payperiod ) { case 'weekly': if ( pd2 - pd1 != 604800000 ) field_valid = false; break; case 'biweekly': if ( pd2 - pd1 != 1209600000 ) field_valid = false; break; case 'semimonthly': var next_period = new Date(pd1); next_period.setDate(next_period.getDate()+14); var min_date = new Date(next_period); min_date.setDate(min_date.getDate()-4); var max_date = new Date(next_period); max_date.setDate(max_date.getDate()+4); if ( pd2 < min_date || pd2 > max_date ) field_valid = false; break; case 'monthly': var next_month = new Date(pd1); next_month.setMonth(next_month.getMonth()+1); var min_date = new Date(next_month); min_date.setDate(min_date.getDate()-4); var max_date = new Date(next_month); max_date.setDate(max_date.getDate()+4); if ( pd2 < min_date || pd2 > max_date ) field_valid = false; break; }; if ( !field_valid ) { AddClass ( control_1, error_class ); AddClass ( control_2, error_class ); payinfo.reason = validate_error_messages['paydates.paydate_payperiod_mismatch']; } } } else { if ( payinfo.paydate2 != undefined && payinfo.paydate2 != '' ) payinfo.reason = validate_error_messages['paydates.paydate2_invalid']; } } else { if ( payinfo.paydate1 != undefined && payinfo.paydate1 != '' ) payinfo.reason = validate_error_messages['paydates.paydate1_invalid']; } return ( field_valid ); } function ValidateDate ( value, control_id, error_class ) { var field_valid = true; RemoveClass ( control_id, error_class ); // Validate numbers individually field_valid = /^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9]{2}$/.test(value); if ( field_valid == true ) { var adata = value.split('/'); var mm = parseInt(adata[0],10); var dd = parseInt(adata[1],10); var yyyy = parseInt(adata[2],10); var xdata = new Date(yyyy,mm-1,dd); if ( ( xdata.getFullYear() == yyyy ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == dd ) ) field_valid = true; else field_valid = false; } if ( field_valid === false ) AddClass ( control_id, error_class ); return ( field_valid ); } function ValidateSsn ( value, control_id, error_class ) { var field_valid = true; RemoveClass ( control_id, error_class ); field_valid = /^[0-7]{1}[0-9]{2}[-.]?[0-9]{2}[-.]?[0-9]{4}$/.test(value); if ( field_valid === false ) AddClass ( control_id, error_class ); return ( field_valid ); } function ValidateInteger ( value, control_id, error_class, min_length, max_length ) { var field_valid = false; RemoveClass ( control_id, error_class ); field_valid = /^[0-9]+$/.test(value); if ( field_valid ) { var length = value.length; if ( /[0-9]+/.test(min_length) ) { if ( length < min_length ) field_valid = false; } if ( /[0-9]+/.test(max_length) ) { if ( length > max_length ) field_valid = false; } } if ( field_valid === false ) AddClass ( control_id, error_class ); return ( field_valid ); } function ValidateString ( value, control_id, error_class, min_length, max_length, vpattern ) { var field_valid = false; RemoveClass ( control_id, error_class ); if ( value != undefined ) { field_valid = true; var length = value.length; if ( /[0-9]+/.test(min_length) ) { if ( length < min_length ) field_valid = false; } if ( /[0-9]+/.test(max_length) ) { if ( length > max_length ) field_valid = false; } if ( field_valid == true && vpattern ) { var regex = new RegExp( vpattern ); field_valid = regex.test ( value ); } } if ( field_valid === false ) AddClass ( control_id, error_class ); return ( field_valid ); } function ValidatePhone ( value, control_id, error_class, format_only, request_async, vlogdata, silent_phone ) { var field_valid = true; if ( typeof request_async === 'undefined' ) request_async = true; if ( typeof vlogdata === 'undefined' ) vlogdata = ''; if ( typeof silent_phone === 'undefined' ) silent_phone = false; RemoveClass ( control_id, error_class ); //field_valid = /^[\(]?[2-9]{1}[0-9]{2}[\)]?[.\- ]?[0-9]{3}[.\- ]?[0-9]{4}$/.test(value); field_valid = /^[\(]?[2-9]{1}[0-9]{2}[\)]?[.\- ]?[2-9]{1}[0-9]{2}[.\- ]?[0-9]{4}$/.test(value); phone_scrunched = value; phone_scrunched = phone_scrunched.replace(/ /g, ''); phone_scrunched = phone_scrunched.replace(/\./g, ''); phone_scrunched = phone_scrunched.replace(/\-/g, ''); phone_scrunched = phone_scrunched.replace(/\(/g, ''); phone_scrunched = phone_scrunched.replace(/\)/g, ''); phone_scrunched = phone_scrunched.replace(/\+/g, ''); // Tag as invalid anytime the same digit repeats 7 times in a row if ( field_valid == true ) { for ( ctr = 0; ctr < 10; ctr++ ) { searchvalue = ""; for ( ctr2 = 0; ctr2 < 7; ctr2++ ) searchvalue = searchvalue + ctr.toString(); if ( phone_scrunched.indexOf( searchvalue ) > -1 ) { field_valid = false; break; } } } // Tag as invalid any toll free area codes if ( field_valid == true ) { toll_free_area_codes = ["800", "844", "855", "866", "877", "888"]; phone_area = phone_scrunched.substring ( 0, 3 ) if ( toll_free_area_codes.indexOf( phone_area ) > -1 ) field_valid = false; } if ( field_valid == true ) { var request = new Object(); request.request = 'validate_phone_format'; if ( silent_phone == true ) request.request = 'validate_phone_format_silent_phone'; request.phone = value; request.domain = document.domain; request.lead_instance_id = $('#edit_lead_instance_id').val(); var json = JSON.stringify( request ); json = encodeURIComponent ( json ); var http_request = service_interface + "?request=" + json; // Submit $.ajax({ url: http_request, dataType: 'json', async: request_async, success: function(json) { field_valid = false; var valid = json.response_code; if ( valid === 1 ) field_valid = true; else AddClass ( control_id, error_class ); }, error: function error(jqXHR, textStatus, errorThrown) { var error = jqXHR.responseText; } }) } if ( field_valid == true && format_only == false ) { var request = new Object(); request.request = 'validate_phone'; request.phone = value; request.domain = document.domain; request.lead_instance_id = $('#edit_lead_instance_id').val(); var json = JSON.stringify( request ); json = encodeURIComponent ( json ); var http_request = service_interface + "?request=" + json; // Submit $.ajax({ url: http_request, dataType: 'json', async: request_async, success: function(json) { field_valid = false; var valid = json.response_code; if ( valid === 1 ) field_valid = true; else { if ( json.phone_enforce > 0 ) AddClass ( control_id, error_class ); else field_valid = true; } if ( vlogdata != '' ) { $('#' + vlogdata).val(json.phone_data); } }, error: function error(jqXHR, textStatus, errorThrown) { var error = jqXHR.responseText; } }) } if ( field_valid === false ) AddClass ( control_id, error_class ); return ( field_valid ); } function ValidateZip ( value, control_id, error_class, request_async ) { var field_valid = true; if ( typeof request_async === 'undefined' ) request_async = true; RemoveClass ( control_id, error_class ); field_valid = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(value); if ( field_valid == true ) { var request = new Object(); request.request = 'validate_zip'; request.zip = value; var json = JSON.stringify( request ); json = encodeURIComponent ( json ); var http_request = service_interface + "?request=" + json; // Submit $.ajax({ url: http_request, dataType: 'json', async: request_async, success: function(json) { field_valid = false; var valid = json.response_code; if ( valid === 1 ) field_valid = true; else AddClass ( control_id, error_class ); }, error: function error(jqXHR, textStatus, errorThrown) { var error = jqXHR.responseText; } }) } if ( field_valid === false ) AddClass ( control_id, error_class ); return ( field_valid ); } function ValidateEmail ( email, format_only, control_id, error_class, request_async ) { var field_valid = false; if ( typeof request_async === 'undefined' ) request_async = true; RemoveClass ( control_id, error_class ); if ( email != '' ) { // Basic syntax check first var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var field_valid = re.test(email); if ( field_valid == true && format_only == false ) { var request = new Object(); request.request = 'validate_email'; request.email = email; request.domain = document.domain; request.lead_instance_id = $('#edit_lead_instance_id').val(); var json = JSON.stringify( request ); json = encodeURIComponent ( json ); var http_request = service_interface + "?request=" + json; // Submit $.ajax({ url: http_request, dataType: 'json', async: request_async, success: function(json) { field_valid = false; var valid = json.response_code; if ( valid === 1 ) field_valid = true; else { if ( json.email_enforce > 0 ) AddClass ( control_id, error_class ); else field_valid = true; } }, error: function error(jqXHR, textStatus, errorThrown) { var error = jqXHR.responseText; } }) } } if ( field_valid === false ) AddClass ( control_id, error_class ); return ( field_valid ); } // These determine if the control is individual, or an array, and then handle that function AddClass ( control_id, apply_class ) { if ( typeof control_id !== 'undefined' && typeof apply_class !== 'undefined' ) { if ( typeof control_id === 'object' && Array.isArray ( control_id ) ) { $.each(control_id, function( index, value ) { AddClassIndividual ( value, apply_class ); }); } else AddClassIndividual ( control_id, apply_class ); } } function RemoveClass ( control_id, apply_class ) { if ( typeof control_id !== 'undefined' && typeof apply_class !== 'undefined' ) { if ( typeof control_id === 'object' && Array.isArray ( control_id ) ) { $.each(control_id, function( index, value ) { RemoveClassIndividual ( value, apply_class ); }); } else RemoveClassIndividual ( control_id, apply_class ); } } // These assign/remove a class from a specific element function AddClassIndividual ( control_id, apply_class ) { if ( typeof control_id !== 'undefined' && typeof apply_class !== 'undefined' ) $('#' + control_id).addClass(apply_class); } function RemoveClassIndividual ( control_id, apply_class ) { if ( typeof control_id !== 'undefined' && typeof apply_class !== 'undefined' ) $('#' + control_id).removeClass(apply_class); } // These simplify setting up associated controls function AssociateAddressControls ( edit_address, edit_city, edit_state, edit_zip, edit_address_error, edit_address_suggestions ) { var address_validate = new Object(); address_validate.address = edit_address; address_validate.city = edit_city; address_validate.state = edit_state; address_validate.zip = edit_zip; address_validate.error_text = edit_address_error; address_validate.suggestions = edit_address_suggestions; AssociateControls ( edit_address, address_validate ); AssociateControls ( edit_city, address_validate ); AssociateControls ( edit_state, address_validate ); AssociateControls ( edit_zip, address_validate ); } function AssociateBankControls ( edit_aba, edit_bankname, edit_bankaddress, edit_bankphone ) { var aba_validate = new Object(); aba_validate.aba = edit_aba; aba_validate.bankname = edit_bankname; aba_validate.bankaddress = edit_bankaddress; aba_validate.bankphone = edit_bankphone; AssociateControls ( edit_aba, aba_validate ); } function AssociatePaydateControls ( edit_paydate1, edit_paydate2, edit_payperiod, edit_paydate_error ) { var payday_validate = new Object(); payday_validate.paydate1 = edit_paydate1; payday_validate.paydate2 = edit_paydate2; payday_validate.payperiod = edit_payperiod; payday_validate.error_text = edit_paydate_error; AssociateControls ( edit_paydate1, payday_validate ); AssociateControls ( edit_paydate2, payday_validate ); AssociateControls ( edit_payperiod, payday_validate ); }