(function (window) {
  {
    var unknown = 'N/A';

    // screen
    var screenSize = '';
    if (screen.width) {
      width = screen.width ? screen.width : '';
      height = screen.height ? screen.height : '';
      screenSize += '' + width + ' x ' + height;
    }

    //View Port
    var viewPortW = Math.max(
      document.documentElement.clientWidth,
      window.innerWidth || 0
    );
    var viewPortH = Math.max(
      document.documentElement.clientHeight,
      window.innerHeight || 0
    );
    var viewPort = viewPortW + ' x ' + viewPortH;

    //browser
    var nVer = navigator.appVersion;
    var nAgt = navigator.userAgent;
    var browser = navigator.appName;
    var version = '' + parseFloat(navigator.appVersion);
    var majorVersion = parseInt(navigator.appVersion, 10);
    var nameOffset, verOffset, ix;

    // Opera
    if ((verOffset = nAgt.indexOf('Opera')) != -1) {
      browser = 'Opera';
      version = nAgt.substring(verOffset + 6);
      if ((verOffset = nAgt.indexOf('Version')) != -1) {
        version = nAgt.substring(verOffset + 8);
      }
    }
    // MSIE
    else if ((verOffset = nAgt.indexOf('MSIE')) != -1) {
      browser = 'Microsoft Internet Explorer';
      version = nAgt.substring(verOffset + 5);
    }

    //IE 11 no longer identifies itself as MS IE, so trap it
    //http://stackoverflow.com/questions/17907445/how-to-detect-ie11
    else if (browser == 'Netscape' && nAgt.indexOf('Trident/') != -1) {
      browser = 'Microsoft Internet Explorer';
      version = nAgt.substring(verOffset + 5);
      if ((verOffset = nAgt.indexOf('rv:')) != -1) {
        version = nAgt.substring(verOffset + 3);
      }
    }

    // Chrome
    else if ((verOffset = nAgt.indexOf('Chrome')) != -1) {
      browser = 'Chrome';
      version = nAgt.substring(verOffset + 7);
    }
    // Safari
    else if ((verOffset = nAgt.indexOf('Safari')) != -1) {
      browser = 'Safari';
      version = nAgt.substring(verOffset + 7);
      if ((verOffset = nAgt.indexOf('Version')) != -1) {
        version = nAgt.substring(verOffset + 8);
      }

      // Chrome on iPad identifies itself as Safari. Actual results do not match what Google claims
      //  at: https://developers.google.com/chrome/mobile/docs/user-agent?hl=ja
      //  No mention of chrome in the user agent string. However it does mention CriOS, which presumably
      //  can be keyed on to detect it.
      if (nAgt.indexOf('CriOS') != -1) {
        //Chrome on iPad spoofing Safari...correct it.
        browser = 'Chrome';
        //Don't believe there is a way to grab the accurate version number, so leaving that for now.
      }
    }
    // Firefox
    else if ((verOffset = nAgt.indexOf('Firefox')) != -1) {
      browser = 'Firefox';
      version = nAgt.substring(verOffset + 8);
    }
    // Other browsers
    else if (
      (nameOffset = nAgt.lastIndexOf(' ') + 1) <
      (verOffset = nAgt.lastIndexOf('/'))
    ) {
      browser = nAgt.substring(nameOffset, verOffset);
      version = nAgt.substring(verOffset + 1);
      if (browser.toLowerCase() == browser.toUpperCase()) {
        browser = navigator.appName;
      }
    }
    // trim the version string
    if ((ix = version.indexOf(';')) != -1) version = version.substring(0, ix);
    if ((ix = version.indexOf(' ')) != -1) version = version.substring(0, ix);
    if ((ix = version.indexOf(')')) != -1) version = version.substring(0, ix);

    majorVersion = parseInt('' + version, 10);
    if (isNaN(majorVersion)) {
      version = '' + parseFloat(navigator.appVersion);
      majorVersion = parseInt(navigator.appVersion, 10);
    }

    // mobile version
    var mobile = /Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(nVer);

    // cookie
    var cookieEnabled = navigator.cookieEnabled ? true : false;

    if (typeof navigator.cookieEnabled == 'undefined' && !cookieEnabled) {
      document.cookie = 'testcookie';
      cookieEnabled =
        document.cookie.indexOf('testcookie') != -1 ? true : false;
    }

    // system
    var os = unknown;
    var clientStrings = [
      { s: 'Windows 3.11', r: /Win16/ },
      { s: 'Windows 95', r: /(Windows 95|Win95|Windows_95)/ },
      { s: 'Windows ME', r: /(Win 9x 4.90|Windows ME)/ },
      { s: 'Windows 98', r: /(Windows 98|Win98)/ },
      { s: 'Windows CE', r: /Windows CE/ },
      { s: 'Windows 2000', r: /(Windows NT 5.0|Windows 2000)/ },
      { s: 'Windows XP', r: /(Windows NT 5.1|Windows XP)/ },
      { s: 'Windows Server 2003', r: /Windows NT 5.2/ },
      { s: 'Windows Vista', r: /Windows NT 6.0/ },
      { s: 'Windows 7', r: /(Windows 7|Windows NT 6.1)/ },
      { s: 'Windows 8.1', r: /(Windows 8.1|Windows NT 6.3)/ },
      { s: 'Windows 8', r: /(Windows 8|Windows NT 6.2)/ },
      {
        s: 'Windows NT 4.0',
        r: /(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/,
      },
      { s: 'Windows ME', r: /Windows ME/ },
      { s: 'Android', r: /Android/ },
      { s: 'Open BSD', r: /OpenBSD/ },
      { s: 'Sun OS', r: /SunOS/ },
      { s: 'Linux', r: /(Linux|X11)/ },
      { s: 'iOS', r: /(iPhone|iPad|iPod)/ },
      { s: 'Mac OS X', r: /Mac OS X/ },
      { s: 'Mac OS', r: /(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/ },
      { s: 'QNX', r: /QNX/ },
      { s: 'UNIX', r: /UNIX/ },
      { s: 'BeOS', r: /BeOS/ },
      { s: 'OS/2', r: /OS\/2/ },
      {
        s: 'Search Bot',
        r: /(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/,
      },
    ];
    for (var id in clientStrings) {
      var cs = clientStrings[id];
      if (cs.r.test(nAgt)) {
        os = cs.s;
        break;
      }
    }

    var osVersion = unknown;

    if (/Windows/.test(os)) {
      osVersion = /Windows (.*)/.exec(os)[1];
      os = 'Windows';
    }

    switch (os) {
      case 'Mac OS X':
        osVersion = /Mac OS X ([\.\_\d]+)/.exec(nAgt)[1];
        break;

      case 'Android':
        osVersion = /Android ([\.\_\d]+)/.exec(nAgt)[1];
        break;

      case 'iOS':
        osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer);
        osVersion =
          osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
        break;
    }
  }

  window.browserInfo = {
    screen: screenSize,
    viewport: viewPort,
    browser: browser,
    browserVersion: version,
    mobile: mobile,
    os: os,
    osVersion: osVersion,
    cookies: cookieEnabled,
    userAgent: nAgt,
  };
})(this);
async function hideCommandsOnTicketReview() {
  const END_URL =
    '/api/v2/ticket_forms/show_many.json?include=ticket_fields&locale=nl&associated_to_brand=true&end_user_visible=true&active=true';
  let data = await $.getJSON(END_URL);
  let hideAbleCommands = [];
  if (data.count > 0 && data.ticket_fields.length > 0) {
    data.ticket_fields.forEach((element) => {
      if (
        element.title &&
        element.type === 'checkbox' &&
        element.description.includes('{{') &&
        element.description.includes('}}')
      ) {
        $(`dt:contains(${element.title.trim()})`).hide();
        $(`dt:contains(${element.title.trim()})`).next().hide();
      }
    });
  }
}
hideCommandsOnTicketReview();
function reverseString(str) {
  let newString = '';
  for (let i = str.length - 1; i >= 0; i--) {
    newString += str[i];
  }
  return newString;
}
let progressButtonBackgroundColor = '#1f73b7';
let progressButtonBackground = '#1f73b7';
let progressButtonColor = '#FFF';
var cssAnimation = document.createElement('style');
cssAnimation.type = 'text/css';
var rules = document.createTextNode(
  '@-webkit-keyframes wave {' +
  '0% { background-position: -468px 0;}' +
  '100% { background-position: 468px 0; }' +
  '}'
);
cssAnimation.appendChild(rules);
document.getElementsByTagName('head')[0].appendChild(cssAnimation);
let zendeskGrid = document.createElement('link');
zendeskGrid.setAttribute('rel', 'stylesheet');
zendeskGrid.setAttribute('type', 'text/css');
zendeskGrid.setAttribute(
  'href',
  'https://cdn.jsdelivr.net/combine/npm/@zendeskgarden/css-buttons@6.0,npm/@zendeskgarden/css-forms@7.0.20,npm/@zendeskgarden/css-grid@0.1,npm/@zendeskgarden/css-callouts,npm/@zendeskgarden/css-utilities@4.5.5,npm/@zendeskgarden/css-menus@9.0.20'
);
document.getElementsByTagName('head')[0].appendChild(zendeskGrid);
let countriesList = [
  { name: 'Afghanistan', dial_code: '+93', code: 'AF' },
  { name: 'Aland Islands', dial_code: '+358', code: 'AX' },
  { name: 'Albania', dial_code: '+355', code: 'AL' },
  { name: 'Algeria', dial_code: '+213', code: 'DZ' },
  { name: 'AmericanSamoa', dial_code: '+1684', code: 'AS' },
  { name: 'Andorra', dial_code: '+376', code: 'AD' },
  { name: 'Angola', dial_code: '+244', code: 'AO' },
  { name: 'Anguilla', dial_code: '+1264', code: 'AI' },
  { name: 'Antarctica', dial_code: '+672', code: 'AQ' },
  { name: 'Antigua and Barbuda', dial_code: '+1268', code: 'AG' },
  { name: 'Argentina', dial_code: '+54', code: 'AR' },
  { name: 'Armenia', dial_code: '+374', code: 'AM' },
  { name: 'Aruba', dial_code: '+297', code: 'AW' },
  { name: 'Australia', dial_code: '+61', code: 'AU' },
  { name: 'Austria', dial_code: '+43', code: 'AT' },
  { name: 'Azerbaijan', dial_code: '+994', code: 'AZ' },
  { name: 'Bahamas', dial_code: '+1242', code: 'BS' },
  { name: 'Bahrain', dial_code: '+973', code: 'BH' },
  { name: 'Bangladesh', dial_code: '+880', code: 'BD' },
  { name: 'Barbados', dial_code: '+1246', code: 'BB' },
  { name: 'Belarus', dial_code: '+375', code: 'BY' },
  { name: 'Belgium', dial_code: '+32', code: 'BE' },
  { name: 'Belize', dial_code: '+501', code: 'BZ' },
  { name: 'Benin', dial_code: '+229', code: 'BJ' },
  { name: 'Bermuda', dial_code: '+1441', code: 'BM' },
  { name: 'Bhutan', dial_code: '+975', code: 'BT' },
  { name: 'Bolivia, Plurinational State of', dial_code: '+591', code: 'BO' },
  { name: 'Bosnia and Herzegovina', dial_code: '+387', code: 'BA' },
  { name: 'Botswana', dial_code: '+267', code: 'BW' },
  { name: 'Brazil', dial_code: '+55', code: 'BR' },
  { name: 'British Indian Ocean Territory', dial_code: '+246', code: 'IO' },
  { name: 'Brunei Darussalam', dial_code: '+673', code: 'BN' },
  { name: 'Bulgaria', dial_code: '+359', code: 'BG' },
  { name: 'Burkina Faso', dial_code: '+226', code: 'BF' },
  { name: 'Burundi', dial_code: '+257', code: 'BI' },
  { name: 'Cambodia', dial_code: '+855', code: 'KH' },
  { name: 'Cameroon', dial_code: '+237', code: 'CM' },
  { name: 'Canada', dial_code: '+1', code: 'CA' },
  { name: 'Cape Verde', dial_code: '+238', code: 'CV' },
  { name: 'Cayman Islands', dial_code: '+ 345', code: 'KY' },
  { name: 'Central African Republic', dial_code: '+236', code: 'CF' },
  { name: 'Chad', dial_code: '+235', code: 'TD' },
  { name: 'Chile', dial_code: '+56', code: 'CL' },
  { name: 'China', dial_code: '+86', code: 'CN' },
  { name: 'Christmas Island', dial_code: '+61', code: 'CX' },
  { name: 'Cocos (Keeling) Islands', dial_code: '+61', code: 'CC' },
  { name: 'Colombia', dial_code: '+57', code: 'CO' },
  { name: 'Comoros', dial_code: '+269', code: 'KM' },
  { name: 'Congo', dial_code: '+242', code: 'CG' },
  {
    name: 'Congo, The Democratic Republic of the Congo',
    dial_code: '+243',
    code: 'CD',
  },
  { name: 'Cook Islands', dial_code: '+682', code: 'CK' },
  { name: 'Costa Rica', dial_code: '+506', code: 'CR' },
  { name: "Cote d'Ivoire", dial_code: '+225', code: 'CI' },
  { name: 'Croatia', dial_code: '+385', code: 'HR' },
  { name: 'Cuba', dial_code: '+53', code: 'CU' },
  { name: 'Cyprus', dial_code: '+357', code: 'CY' },
  { name: 'Czech Republic', dial_code: '+420', code: 'CZ' },
  { name: 'Denmark', dial_code: '+45', code: 'DK' },
  { name: 'Djibouti', dial_code: '+253', code: 'DJ' },
  { name: 'Dominica', dial_code: '+1767', code: 'DM' },
  { name: 'Dominican Republic', dial_code: '+1849', code: 'DO' },
  { name: 'Ecuador', dial_code: '+593', code: 'EC' },
  { name: 'Egypt', dial_code: '+20', code: 'EG' },
  { name: 'El Salvador', dial_code: '+503', code: 'SV' },
  { name: 'Equatorial Guinea', dial_code: '+240', code: 'GQ' },
  { name: 'Eritrea', dial_code: '+291', code: 'ER' },
  { name: 'Estonia', dial_code: '+372', code: 'EE' },
  { name: 'Ethiopia', dial_code: '+251', code: 'ET' },
  { name: 'Falkland Islands (Malvinas)', dial_code: '+500', code: 'FK' },
  { name: 'Faroe Islands', dial_code: '+298', code: 'FO' },
  { name: 'Fiji', dial_code: '+679', code: 'FJ' },
  { name: 'Finland', dial_code: '+358', code: 'FI' },
  { name: 'France', dial_code: '+33', code: 'FR' },
  { name: 'French Guiana', dial_code: '+594', code: 'GF' },
  { name: 'French Polynesia', dial_code: '+689', code: 'PF' },
  { name: 'Gabon', dial_code: '+241', code: 'GA' },
  { name: 'Gambia', dial_code: '+220', code: 'GM' },
  { name: 'Georgia', dial_code: '+995', code: 'GE' },
  { name: 'Germany', dial_code: '+49', code: 'DE' },
  { name: 'Ghana', dial_code: '+233', code: 'GH' },
  { name: 'Gibraltar', dial_code: '+350', code: 'GI' },
  { name: 'Greece', dial_code: '+30', code: 'GR' },
  { name: 'Greenland', dial_code: '+299', code: 'GL' },
  { name: 'Grenada', dial_code: '+1473', code: 'GD' },
  { name: 'Guadeloupe', dial_code: '+590', code: 'GP' },
  { name: 'Guam', dial_code: '+1671', code: 'GU' },
  { name: 'Guatemala', dial_code: '+502', code: 'GT' },
  { name: 'Guernsey', dial_code: '+44', code: 'GG' },
  { name: 'Guinea', dial_code: '+224', code: 'GN' },
  { name: 'Guinea-Bissau', dial_code: '+245', code: 'GW' },
  { name: 'Guyana', dial_code: '+595', code: 'GY' },
  { name: 'Haiti', dial_code: '+509', code: 'HT' },
  { name: 'Holy See (Vatican City State)', dial_code: '+379', code: 'VA' },
  { name: 'Honduras', dial_code: '+504', code: 'HN' },
  { name: 'Hong Kong', dial_code: '+852', code: 'HK' },
  { name: 'Hungary', dial_code: '+36', code: 'HU' },
  { name: 'Iceland', dial_code: '+354', code: 'IS' },
  { name: 'India', dial_code: '+91', code: 'IN' },
  { name: 'Indonesia', dial_code: '+62', code: 'ID' },
  {
    name: 'Iran, Islamic Republic of Persian Gulf',
    dial_code: '+98',
    code: 'IR',
  },
  { name: 'Iraq', dial_code: '+964', code: 'IQ' },
  { name: 'Ireland', dial_code: '+353', code: 'IE' },
  { name: 'Isle of Man', dial_code: '+44', code: 'IM' },
  { name: 'Israel', dial_code: '+972', code: 'IL' },
  { name: 'Italy', dial_code: '+39', code: 'IT' },
  { name: 'Jamaica', dial_code: '+1876', code: 'JM' },
  { name: 'Japan', dial_code: '+81', code: 'JP' },
  { name: 'Jersey', dial_code: '+44', code: 'JE' },
  { name: 'Jordan', dial_code: '+962', code: 'JO' },
  { name: 'Kazakhstan', dial_code: '+77', code: 'KZ' },
  { name: 'Kenya', dial_code: '+254', code: 'KE' },
  { name: 'Kiribati', dial_code: '+686', code: 'KI' },
  {
    name: "Korea, Democratic People's Republic of Korea",
    dial_code: '+850',
    code: 'KP',
  },
  { name: 'Korea, Republic of South Korea', dial_code: '+82', code: 'KR' },
  { name: 'Kuwait', dial_code: '+965', code: 'KW' },
  { name: 'Kyrgyzstan', dial_code: '+996', code: 'KG' },
  { name: 'Laos', dial_code: '+856', code: 'LA' },
  { name: 'Latvia', dial_code: '+371', code: 'LV' },
  { name: 'Lebanon', dial_code: '+961', code: 'LB' },
  { name: 'Lesotho', dial_code: '+266', code: 'LS' },
  { name: 'Liberia', dial_code: '+231', code: 'LR' },
  { name: 'Libyan Arab Jamahiriya', dial_code: '+218', code: 'LY' },
  { name: 'Liechtenstein', dial_code: '+423', code: 'LI' },
  { name: 'Lithuania', dial_code: '+370', code: 'LT' },
  { name: 'Luxembourg', dial_code: '+352', code: 'LU' },
  { name: 'Macao', dial_code: '+853', code: 'MO' },
  { name: 'Macedonia', dial_code: '+389', code: 'MK' },
  { name: 'Madagascar', dial_code: '+261', code: 'MG' },
  { name: 'Malawi', dial_code: '+265', code: 'MW' },
  { name: 'Malaysia', dial_code: '+60', code: 'MY' },
  { name: 'Maldives', dial_code: '+960', code: 'MV' },
  { name: 'Mali', dial_code: '+223', code: 'ML' },
  { name: 'Malta', dial_code: '+356', code: 'MT' },
  { name: 'Marshall Islands', dial_code: '+692', code: 'MH' },
  { name: 'Martinique', dial_code: '+596', code: 'MQ' },
  { name: 'Mauritania', dial_code: '+222', code: 'MR' },
  { name: 'Mauritius', dial_code: '+230', code: 'MU' },
  { name: 'Mayotte', dial_code: '+262', code: 'YT' },
  { name: 'Mexico', dial_code: '+52', code: 'MX' },
  {
    name: 'Micronesia, Federated States of Micronesia',
    dial_code: '+691',
    code: 'FM',
  },
  { name: 'Moldova', dial_code: '+373', code: 'MD' },
  { name: 'Monaco', dial_code: '+377', code: 'MC' },
  { name: 'Mongolia', dial_code: '+976', code: 'MN' },
  { name: 'Montenegro', dial_code: '+382', code: 'ME' },
  { name: 'Montserrat', dial_code: '+1664', code: 'MS' },
  { name: 'Morocco', dial_code: '+212', code: 'MA' },
  { name: 'Mozambique', dial_code: '+258', code: 'MZ' },
  { name: 'Myanmar', dial_code: '+95', code: 'MM' },
  { name: 'Namibia', dial_code: '+264', code: 'NA' },
  { name: 'Nauru', dial_code: '+674', code: 'NR' },
  { name: 'Nepal', dial_code: '+977', code: 'NP' },
  { name: 'Netherlands', dial_code: '+31', code: 'NL' },
  { name: 'Netherlands Antilles', dial_code: '+599', code: 'AN' },
  { name: 'New Caledonia', dial_code: '+687', code: 'NC' },
  { name: 'New Zealand', dial_code: '+64', code: 'NZ' },
  { name: 'Nicaragua', dial_code: '+505', code: 'NI' },
  { name: 'Niger', dial_code: '+227', code: 'NE' },
  { name: 'Nigeria', dial_code: '+234', code: 'NG' },
  { name: 'Niue', dial_code: '+683', code: 'NU' },
  { name: 'Norfolk Island', dial_code: '+672', code: 'NF' },
  { name: 'Northern Mariana Islands', dial_code: '+1670', code: 'MP' },
  { name: 'Norway', dial_code: '+47', code: 'NO' },
  { name: 'Oman', dial_code: '+968', code: 'OM' },
  { name: 'Pakistan', dial_code: '+92', code: 'PK' },
  { name: 'Palau', dial_code: '+680', code: 'PW' },
  { name: 'Palestinian Territory, Occupied', dial_code: '+970', code: 'PS' },
  { name: 'Panama', dial_code: '+507', code: 'PA' },
  { name: 'Papua New Guinea', dial_code: '+675', code: 'PG' },
  { name: 'Paraguay', dial_code: '+595', code: 'PY' },
  { name: 'Peru', dial_code: '+51', code: 'PE' },
  { name: 'Philippines', dial_code: '+63', code: 'PH' },
  { name: 'Pitcairn', dial_code: '+872', code: 'PN' },
  { name: 'Poland', dial_code: '+48', code: 'PL' },
  { name: 'Portugal', dial_code: '+351', code: 'PT' },
  { name: 'Puerto Rico', dial_code: '+1939', code: 'PR' },
  { name: 'Qatar', dial_code: '+974', code: 'QA' },
  { name: 'Romania', dial_code: '+40', code: 'RO' },
  { name: 'Russia', dial_code: '+7', code: 'RU' },
  { name: 'Rwanda', dial_code: '+250', code: 'RW' },
  { name: 'Reunion', dial_code: '+262', code: 'RE' },
  { name: 'Saint Barthelemy', dial_code: '+590', code: 'BL' },
  {
    name: 'Saint Helena, Ascension and Tristan Da Cunha',
    dial_code: '+290',
    code: 'SH',
  },
  { name: 'Saint Kitts and Nevis', dial_code: '+1869', code: 'KN' },
  { name: 'Saint Lucia', dial_code: '+1758', code: 'LC' },
  { name: 'Saint Martin', dial_code: '+590', code: 'MF' },
  { name: 'Saint Pierre and Miquelon', dial_code: '+508', code: 'PM' },
  { name: 'Saint Vincent and the Grenadines', dial_code: '+1784', code: 'VC' },
  { name: 'Samoa', dial_code: '+685', code: 'WS' },
  { name: 'San Marino', dial_code: '+378', code: 'SM' },
  { name: 'Sao Tome and Principe', dial_code: '+239', code: 'ST' },
  { name: 'Saudi Arabia', dial_code: '+966', code: 'SA' },
  { name: 'Senegal', dial_code: '+221', code: 'SN' },
  { name: 'Serbia', dial_code: '+381', code: 'RS' },
  { name: 'Seychelles', dial_code: '+248', code: 'SC' },
  { name: 'Sierra Leone', dial_code: '+232', code: 'SL' },
  { name: 'Singapore', dial_code: '+65', code: 'SG' },
  { name: 'Slovakia', dial_code: '+421', code: 'SK' },
  { name: 'Slovenia', dial_code: '+386', code: 'SI' },
  { name: 'Solomon Islands', dial_code: '+677', code: 'SB' },
  { name: 'Somalia', dial_code: '+252', code: 'SO' },
  { name: 'South Africa', dial_code: '+27', code: 'ZA' },
  { name: 'South Sudan', dial_code: '+211', code: 'SS' },
  {
    name: 'South Georgia and the South Sandwich Islands',
    dial_code: '+500',
    code: 'GS',
  },
  { name: 'Spain', dial_code: '+34', code: 'ES' },
  { name: 'Sri Lanka', dial_code: '+94', code: 'LK' },
  { name: 'Sudan', dial_code: '+249', code: 'SD' },
  { name: 'Suriname', dial_code: '+597', code: 'SR' },
  { name: 'Svalbard and Jan Mayen', dial_code: '+47', code: 'SJ' },
  { name: 'Swaziland', dial_code: '+268', code: 'SZ' },
  { name: 'Sweden', dial_code: '+46', code: 'SE' },
  { name: 'Switzerland', dial_code: '+41', code: 'CH' },
  { name: 'Syrian Arab Republic', dial_code: '+963', code: 'SY' },
  { name: 'Taiwan', dial_code: '+886', code: 'TW' },
  { name: 'Tajikistan', dial_code: '+992', code: 'TJ' },
  {
    name: 'Tanzania, United Republic of Tanzania',
    dial_code: '+255',
    code: 'TZ',
  },
  { name: 'Thailand', dial_code: '+66', code: 'TH' },
  { name: 'Timor-Leste', dial_code: '+670', code: 'TL' },
  { name: 'Togo', dial_code: '+228', code: 'TG' },
  { name: 'Tokelau', dial_code: '+690', code: 'TK' },
  { name: 'Tonga', dial_code: '+676', code: 'TO' },
  { name: 'Trinidad and Tobago', dial_code: '+1868', code: 'TT' },
  { name: 'Tunisia', dial_code: '+216', code: 'TN' },
  { name: 'Turkey', dial_code: '+90', code: 'TR' },
  { name: 'Turkmenistan', dial_code: '+993', code: 'TM' },
  { name: 'Turks and Caicos Islands', dial_code: '+1649', code: 'TC' },
  { name: 'Tuvalu', dial_code: '+688', code: 'TV' },
  { name: 'Uganda', dial_code: '+256', code: 'UG' },
  { name: 'Ukraine', dial_code: '+380', code: 'UA' },
  { name: 'United Arab Emirates', dial_code: '+971', code: 'AE' },
  { name: 'United Kingdom', dial_code: '+44', code: 'GB' },
  { name: 'United States', dial_code: '+1', code: 'US' },
  { name: 'Uruguay', dial_code: '+598', code: 'UY' },
  { name: 'Uzbekistan', dial_code: '+998', code: 'UZ' },
  { name: 'Vanuatu', dial_code: '+678', code: 'VU' },
  {
    name: 'Venezuela, Bolivarian Republic of Venezuela',
    dial_code: '+58',
    code: 'VE',
  },
  { name: 'Vietnam', dial_code: '+84', code: 'VN' },
  { name: 'Virgin Islands, British', dial_code: '+1284', code: 'VG' },
  { name: 'Virgin Islands, U.S.', dial_code: '+1340', code: 'VI' },
  { name: 'Wallis and Futuna', dial_code: '+681', code: 'WF' },
  { name: 'Yemen', dial_code: '+967', code: 'YE' },
  { name: 'Zambia', dial_code: '+260', code: 'ZM' },
  { name: 'Zimbabwe', dial_code: '+263', code: 'ZW' },
];
let commonCurrencies = {
  USD: { symbol: '$', symbol_native: '$', code: 'USD' },
  CAD: { symbol: 'CA$', symbol_native: '$', code: 'CAD' },
  EUR: { symbol: '€', symbol_native: '€', code: 'EUR' },
  AED: { symbol: 'AED', symbol_native: 'د.إ.', code: 'AED' },
  AFN: { symbol: 'Af', symbol_native: '؋', code: 'AFN' },
  ALL: { symbol: 'ALL', symbol_native: 'Lek', code: 'ALL' },
  AMD: { symbol: 'AMD', symbol_native: 'դր.', code: 'AMD' },
  ARS: { symbol: 'AR$', symbol_native: '$', code: 'ARS' },
  AUD: { symbol: 'AU$', symbol_native: '$', code: 'AUD' },
  AZN: { symbol: 'man.', symbol_native: 'ман.', code: 'AZN' },
  BAM: { symbol: 'KM', symbol_native: 'KM', code: 'BAM' },
  BDT: { symbol: 'Tk', symbol_native: '৳', code: 'BDT' },
  BGN: { symbol: 'BGN', symbol_native: 'лв.', code: 'BGN' },
  BHD: { symbol: 'BD', symbol_native: 'د.ب.', code: 'BHD' },
  BIF: { symbol: 'FBu', symbol_native: 'FBu', code: 'BIF' },
  BND: { symbol: 'BN$', symbol_native: '$', code: 'BND' },
  BOB: { symbol: 'Bs', symbol_native: 'Bs', code: 'BOB' },
  BRL: { symbol: 'R$', symbol_native: 'R$', code: 'BRL' },
  BWP: { symbol: 'BWP', symbol_native: 'P', code: 'BWP' },
  BYN: { symbol: 'Br', symbol_native: 'руб.', code: 'BYN' },
  BZD: { symbol: 'BZ$', symbol_native: '$', code: 'BZD' },
  CDF: { symbol: 'CDF', symbol_native: 'FrCD', code: 'CDF' },
  CHF: { symbol: 'CHF', symbol_native: 'CHF', code: 'CHF' },
  CLP: { symbol: 'CL$', symbol_native: '$', code: 'CLP' },
  CNY: { symbol: 'CN¥', symbol_native: 'CN¥', code: 'CNY' },
  COP: { symbol: 'CO$', symbol_native: '$', code: 'COP' },
  CRC: { symbol: '₡', symbol_native: '₡', code: 'CRC' },
  CVE: { symbol: 'CV$', symbol_native: 'CV$', code: 'CVE' },
  CZK: { symbol: 'Kč', symbol_native: 'Kč', code: 'CZK' },
  DJF: { symbol: 'Fdj', symbol_native: 'Fdj', code: 'DJF' },
  DKK: { symbol: 'Dkr', symbol_native: 'kr', code: 'DKK' },
  DOP: { symbol: 'RD$', symbol_native: 'RD$', code: 'DOP' },
  DZD: { symbol: 'DA', symbol_native: 'د.ج.', code: 'DZD' },
  EEK: { symbol: 'Ekr', symbol_native: 'kr', code: 'EEK' },
  EGP: { symbol: 'EGP', symbol_native: 'ج.م.', code: 'EGP' },
  ERN: { symbol: 'Nfk', symbol_native: 'Nfk', code: 'ERN' },
  ETB: { symbol: 'Br', symbol_native: 'Br', code: 'ETB' },
  GBP: { symbol: '£', symbol_native: '£', code: 'GBP' },
  GEL: { symbol: 'GEL', symbol_native: 'GEL', code: 'GEL' },
  GHS: { symbol: 'GH₵', symbol_native: 'GH₵', code: 'GHS' },
  GNF: { symbol: 'FG', symbol_native: 'FG', code: 'GNF' },
  GTQ: { symbol: 'GTQ', symbol_native: 'Q', code: 'GTQ' },
  HKD: { symbol: 'HK$', symbol_native: '$', code: 'HKD' },
  HNL: { symbol: 'HNL', symbol_native: 'L', code: 'HNL' },
  HRK: { symbol: 'kn', symbol_native: 'kn', code: 'HRK' },
  HUF: { symbol: 'Ft', symbol_native: 'Ft', code: 'HUF' },
  IDR: { symbol: 'Rp', symbol_native: 'Rp', code: 'IDR' },
  ILS: { symbol: '₪', symbol_native: '₪', code: 'ILS' },
  INR: { symbol: 'Rs', symbol_native: 'টকা', code: 'INR' },
  IQD: { symbol: 'IQD', symbol_native: 'د.ع.', code: 'IQD' },
  IRR: { symbol: 'IRR', symbol_native: '﷼', code: 'IRR' },
  ISK: { symbol: 'Ikr', symbol_native: 'kr', code: 'ISK' },
  JMD: { symbol: 'J$', symbol_native: '$', code: 'JMD' },
  JOD: { symbol: 'JD', symbol_native: 'د.أ.', code: 'JOD' },
  JPY: { symbol: '¥', symbol_native: '￥', code: 'JPY' },
  KES: { symbol: 'Ksh', symbol_native: 'Ksh', code: 'KES' },
  KHR: { symbol: 'KHR', symbol_native: '៛', code: 'KHR' },
  KMF: { symbol: 'CF', symbol_native: 'FC', code: 'KMF' },
  KRW: { symbol: '₩', symbol_native: '₩', code: 'KRW' },
  KWD: { symbol: 'KD', symbol_native: 'د.ك.', code: 'KWD' },
  KZT: { symbol: 'KZT', symbol_native: 'тңг.', code: 'KZT' },
  LBP: { symbol: 'L.L.', symbol_native: 'ل.ل.', code: 'LBP' },
  LKR: { symbol: 'SLRs', symbol_native: 'SL Re', code: 'LKR' },
  LTL: { symbol: 'Lt', symbol_native: 'Lt', code: 'LTL' },
  LVL: { symbol: 'Ls', symbol_native: 'Ls', code: 'LVL' },
  LYD: { symbol: 'LD', symbol_native: 'د.ل.', code: 'LYD' },
  MAD: { symbol: 'MAD', symbol_native: 'د.م.', code: 'MAD' },
  MDL: { symbol: 'MDL', symbol_native: 'MDL', code: 'MDL' },
  MGA: { symbol: 'MGA', symbol_native: 'MGA', code: 'MGA' },
  MKD: { symbol: 'MKD', symbol_native: 'MKD', code: 'MKD' },
  MMK: { symbol: 'MMK', symbol_native: 'K', code: 'MMK' },
  MOP: { symbol: 'MOP$', symbol_native: 'MOP$', code: 'MOP' },
  MUR: { symbol: 'MURs', symbol_native: 'MURs', code: 'MUR' },
  MXN: { symbol: 'MX$', symbol_native: '$', code: 'MXN' },
  MYR: { symbol: 'RM', symbol_native: 'RM', code: 'MYR' },
  MZN: { symbol: 'MTn', symbol_native: 'MTn', code: 'MZN' },
  NAD: { symbol: 'N$', symbol_native: 'N$', code: 'NAD' },
  NGN: { symbol: '₦', symbol_native: '₦', code: 'NGN' },
  NIO: { symbol: 'C$', symbol_native: 'C$', code: 'NIO' },
  NOK: { symbol: 'Nkr', symbol_native: 'kr', code: 'NOK' },
  NPR: { symbol: 'NPRs', symbol_native: 'नेरू', code: 'NPR' },
  NZD: { symbol: 'NZ$', symbol_native: '$', code: 'NZD' },
  OMR: { symbol: 'OMR', symbol_native: 'ر.ع.', code: 'OMR' },
  PAB: { symbol: 'B/.', symbol_native: 'B/.', code: 'PAB' },
  PEN: { symbol: 'S/.', symbol_native: 'S/.', code: 'PEN' },
  PHP: { symbol: '₱', symbol_native: '₱', code: 'PHP' },
  PKR: { symbol: 'PKRs', symbol_native: '₨', code: 'PKR' },
  PLN: { symbol: 'zł', symbol_native: 'zł', code: 'PLN' },
  PYG: { symbol: '₲', symbol_native: '₲', code: 'PYG' },
  QAR: { symbol: 'QR', symbol_native: 'ر.ق.', code: 'QAR' },
  RON: { symbol: 'RON', symbol_native: 'RON', code: 'RON' },
  RSD: { symbol: 'din.', symbol_native: 'дин.', code: 'RSD' },
  RUB: { symbol: 'RUB', symbol_native: '₽.', code: 'RUB' },
  RWF: { symbol: 'RWF', symbol_native: 'FR', code: 'RWF' },
  SAR: { symbol: 'SR', symbol_native: 'ر.س.', code: 'SAR' },
  SDG: { symbol: 'SDG', symbol_native: 'SDG', code: 'SDG' },
  SEK: { symbol: 'Skr', symbol_native: 'kr', code: 'SEK' },
  SGD: { symbol: 'S$', symbol_native: '$', code: 'SGD' },
  SOS: { symbol: 'Ssh', symbol_native: 'Ssh', code: 'SOS' },
  SYP: { symbol: 'SY£', symbol_native: 'ل.س.', code: 'SYP' },
  THB: { symbol: '฿', symbol_native: '฿', code: 'THB' },
  TND: { symbol: 'DT', symbol_native: 'د.ت.', code: 'TND' },
  TOP: { symbol: 'T$', symbol_native: 'T$', code: 'TOP' },
  TRY: { symbol: 'TL', symbol_native: 'TL', code: 'TRY' },
  TTD: { symbol: 'TT$', symbol_native: '$', code: 'TTD' },
  TWD: { symbol: 'NT$', symbol_native: 'NT$', code: 'TWD' },
  TZS: { symbol: 'TSh', symbol_native: 'TSh', code: 'TZS' },
  UAH: { symbol: '₴', symbol_native: '₴', code: 'UAH' },
  UGX: { symbol: 'USh', symbol_native: 'USh', code: 'UGX' },
  UYU: { symbol: '$U', symbol_native: '$', code: 'UYU' },
  UZS: { symbol: 'UZS', symbol_native: 'UZS', code: 'UZS' },
  VEF: { symbol: 'Bs.F.', symbol_native: 'Bs.F.', code: 'VEF' },
  VND: { symbol: '₫', symbol_native: '₫', code: 'VND' },
  XAF: { symbol: 'FCFA', symbol_native: 'FCFA', code: 'XAF' },
  XOF: { symbol: 'CFA', symbol_native: 'CFA', code: 'XOF' },
  YER: { symbol: 'YR', symbol_native: 'ر.ي.', code: 'YER' },
  ZAR: { symbol: 'R', symbol_native: 'R', code: 'ZAR' },
  ZMK: { symbol: 'ZK', symbol_native: 'ZK', code: 'ZMK' },
  ZWL: { symbol: 'ZWL$', symbol_native: 'ZWL$', code: 'ZWL' },
};

let uploading_attachment;
let addressArray = [];
let hasTime = false;
let hasRange = false;
let placeApiKey;
let autoFillData = {};
let autoFillOnSubmit = false;
let autoFilledRequestDescrioptionContent;
let prependAutoFilledRequestDescrioptionContent = true;
let submitConditions = {};

$(document).ready(function () {
  let queryString = window.location.search;
  let urlParams = new URLSearchParams(queryString);
  let no_hide = urlParams.get('nohide');
  if (no_hide && no_hide !== '') {
    const sentryLoad=window.Sentry
    $('body').append(`
    <script type="module" defer>
        window.Sentry.init({
            dsn: "https://2170e301c6eb45529de8ae6f6a1d6d8a@o4504116164755456.ingest.sentry.io/4504257697939456",
            integrations: [new Sentry.BrowserTracing()],
            tracesSampleRate: 1.0,
        });
      </script>
    `
    );
  };
  let stepCount = 0;
  let stepTitle = '';
  let activeType = '';
  let allowRequestSubmit = true;
  let fieldModifierValue = new Array();
  let externalGuideLookupEnabled = false;
  let externalSearchObject = {};
  let hideNext = false;
  if (
    $('footer').find('input').css('background-color') &&
    $('footer').find('input').css('background-color') !== ''
  ) {
    progressButtonBackgroundColor = $('footer')
      .find('input')
      .css('background-color');
    progressButtonBackground = $('footer').find('input').css('background');
    progressButtonColor = $('footer').find('input').css('color');
  }
  $('form#new_request')
    .children('div.form-field')
    .each(function (index) {
      if (index === 0) {
        $(this).parent().hide();
        $(this)
          .parent()
          .after(
            '<div id="skeleton"><div class="loading" style="animation-duration: 1s; animation-fill-mode: forwards; animation-iteration-count: infinite; animation-name: wave; animation-timing-function: linear; background: #DDDDDD; background-image: -webkit-gradient(linear, left center, right center, from(#DDDDDD), color-stop(.2, #F5F5F5), color-stop(.4, #E5E5E5), to(#DDDDDD)); background-image: -webkit-linear-gradient(left, #DDDDDD 0%, #F5F5F5 20%, #E5E5E5 40%, #DDDDDD 100%); background-image: -moz-gradient(linear, left center, right center, from(#DDDDDD), color-stop(.2, #F5F5F5), color-stop(.4, #E5E5E5), to(#DDDDDD)); background-image: -moz-linear-gradient(left, #DDDDDD 0%, #F5F5F5 20%, #E5E5E5 40%, #DDDDDD 100%); background-repeat: no-repeat; background-size: 800px 104px; height: 15px; position: relative; margin-top: 12px;"></div><div class="loading" style="animation-duration: 1s; animation-fill-mode: forwards; animation-iteration-count: infinite; animation-name: wave; animation-timing-function: linear; background: #DDDDDD; background-image: -webkit-gradient(linear, left center, right center, from(#DDDDDD), color-stop(.2, #F5F5F5), color-stop(.4, #E5E5E5), to(#DDDDDD)); background-image: -webkit-linear-gradient(left, #DDDDDD 0%, #F5F5F5 20%, #E5E5E5 40%, #DDDDDD 100%); background-image: -moz-gradient(linear, left center, right center, from(#DDDDDD), color-stop(.2, #F5F5F5), color-stop(.4, #E5E5E5), to(#DDDDDD)); background-image: -moz-linear-gradient(left, #DDDDDD 0%, #F5F5F5 20%, #E5E5E5 40%, #DDDDDD 100%); background-repeat: no-repeat; background-size: 800px 104px; height: 30px; position: relative; margin-top: 12px;"></div><body><div class="loading" style="animation-duration: 1s; animation-fill-mode: forwards; animation-iteration-count: infinite; animation-name: wave; animation-timing-function: linear; background: #DDDDDD; background-image: -webkit-gradient(linear, left center, right center, from(#DDDDDD), color-stop(.2, #F5F5F5), color-stop(.4, #E5E5E5), to(#DDDDDD)); background-image: -webkit-linear-gradient(left, #DDDDDD 0%, #F5F5F5 20%, #E5E5E5 40%, #DDDDDD 100%); background-image: -moz-gradient(linear, left center, right center, from(#DDDDDD), color-stop(.2, #F5F5F5), color-stop(.4, #E5E5E5), to(#DDDDDD)); background-image: -moz-linear-gradient(left, #DDDDDD 0%, #F5F5F5 20%, #E5E5E5 40%, #DDDDDD 100%); background-repeat: no-repeat; background-size: 800px 104px; height: 15px; position: relative; margin-top: 12px;"></div><div class="loading" style="animation-duration: 1s; animation-fill-mode: forwards; animation-iteration-count: infinite; animation-name: wave; animation-timing-function: linear; background: #DDDDDD; background-image: -webkit-gradient(linear, left center, right center, from(#DDDDDD), color-stop(.2, #F5F5F5), color-stop(.4, #E5E5E5), to(#DDDDDD)); background-image: -webkit-linear-gradient(left, #DDDDDD 0%, #F5F5F5 20%, #E5E5E5 40%, #DDDDDD 100%); background-image: -moz-gradient(linear, left center, right center, from(#DDDDDD), color-stop(.2, #F5F5F5), color-stop(.4, #E5E5E5), to(#DDDDDD)); background-image: -moz-linear-gradient(left, #DDDDDD 0%, #F5F5F5 20%, #E5E5E5 40%, #DDDDDD 100%); background-repeat: no-repeat; background-size: 800px 104px; height: 30px; position: relative; margin-top: 12px;"></div><body><div class="loading" style="animation-duration: 1s; animation-fill-mode: forwards; animation-iteration-count: infinite; animation-name: wave; animation-timing-function: linear; background: #DDDDDD; background-image: -webkit-gradient(linear, left center, right center, from(#DDDDDD), color-stop(.2, #F5F5F5), color-stop(.4, #E5E5E5), to(#DDDDDD)); background-image: -webkit-linear-gradient(left, #DDDDDD 0%, #F5F5F5 20%, #E5E5E5 40%, #DDDDDD 100%); background-image: -moz-gradient(linear, left center, right center, from(#DDDDDD), color-stop(.2, #F5F5F5), color-stop(.4, #E5E5E5), to(#DDDDDD)); background-image: -moz-linear-gradient(left, #DDDDDD 0%, #F5F5F5 20%, #E5E5E5 40%, #DDDDDD 100%); background-repeat: no-repeat; background-size: 800px 104px; height: 15px; position: relative; margin-top: 20px;"></div><div class="loading" style="animation-duration: 1s; animation-fill-mode: forwards; animation-iteration-count: infinite; animation-name: wave; animation-timing-function: linear; background: #DDDDDD; background-image: -webkit-gradient(linear, left center, right center, from(#DDDDDD), color-stop(.2, #F5F5F5), color-stop(.4, #E5E5E5), to(#DDDDDD)); background-image: -webkit-linear-gradient(left, #DDDDDD 0%, #F5F5F5 20%, #E5E5E5 40%, #DDDDDD 100%); background-image: -moz-gradient(linear, left center, right center, from(#DDDDDD), color-stop(.2, #F5F5F5), color-stop(.4, #E5E5E5), to(#DDDDDD)); background-image: -moz-linear-gradient(left, #DDDDDD 0%, #F5F5F5 20%, #E5E5E5 40%, #DDDDDD 100%); background-repeat: no-repeat; background-size: 800px 104px; height: 80px; position: relative; margin-top: 12px;"></div><body><div class="loading" style="animation-duration: 1s; animation-fill-mode: forwards; animation-iteration-count: infinite; animation-name: wave; animation-timing-function: linear; background: #DDDDDD; background-image: -webkit-gradient(linear, left center, right center, from(#DDDDDD), color-stop(.2, #F5F5F5), color-stop(.4, #E5E5E5), to(#DDDDDD)); background-image: -webkit-linear-gradient(left, #DDDDDD 0%, #F5F5F5 20%, #E5E5E5 40%, #DDDDDD 100%); background-image: -moz-gradient(linear, left center, right center, from(#DDDDDD), color-stop(.2, #F5F5F5), color-stop(.4, #E5E5E5), to(#DDDDDD)); background-image: -moz-linear-gradient(left, #DDDDDD 0%, #F5F5F5 20%, #E5E5E5 40%, #DDDDDD 100%); background-repeat: no-repeat; background-size: 800px 104px; height: 15px; position: relative; margin-top: 12px;"></div><div class="loading" style="animation-duration: 1s; animation-fill-mode: forwards; animation-iteration-count: infinite; animation-name: wave; animation-timing-function: linear; background: #DDDDDD; background-image: -webkit-gradient(linear, left center, right center, from(#DDDDDD), color-stop(.2, #F5F5F5), color-stop(.4, #E5E5E5), to(#DDDDDD)); background-image: -webkit-linear-gradient(left, #DDDDDD 0%, #F5F5F5 20%, #E5E5E5 40%, #DDDDDD 100%); background-image: -moz-gradient(linear, left center, right center, from(#DDDDDD), color-stop(.2, #F5F5F5), color-stop(.4, #E5E5E5), to(#DDDDDD)); background-image: -moz-linear-gradient(left, #DDDDDD 0%, #F5F5F5 20%, #E5E5E5 40%, #DDDDDD 100%); background-repeat: no-repeat; background-size: 800px 104px; height: 30px; position: relative; margin-top: 12px;"></div><div class="loading" style="animation-duration: 1s; animation-fill-mode: forwards; animation-iteration-count: infinite; animation-name: wave; animation-timing-function: linear; background: #DDDDDD; background-image: -webkit-gradient(linear, left center, right center, from(#DDDDDD), color-stop(.2, #F5F5F5), color-stop(.4, #E5E5E5), to(#DDDDDD)); background-image: -webkit-linear-gradient(left, #DDDDDD 0%, #F5F5F5 20%, #E5E5E5 40%, #DDDDDD 100%); background-image: -moz-gradient(linear, left center, right center, from(#DDDDDD), color-stop(.2, #F5F5F5), color-stop(.4, #E5E5E5), to(#DDDDDD)); background-image: -moz-linear-gradient(left, #DDDDDD 0%, #F5F5F5 20%, #E5E5E5 40%, #DDDDDD 100%); background-repeat: no-repeat; background-size: 800px 104px; height: 40px; position: relative; border-radius: 20px; margin-top: 30px;"></div></div>'
          );
      }
    });
  $('.ticket-form-magic').show();
  $('form')
    .children('footer')
    .each(function (index) {
      $(this).hide();
    });
  var replaceElements = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
  setTimeout(function () {
    var removeSkeletolTimeout = 300;
    var hasStepOrAddress = false;
    $('div.form-field p').each(function () {
      let dynamicContetnExpression = /\[(.*?)\]/g;
      var regexExpression = /{{(\#|\/)?((([^}][^}]?|[^}]}?)*))}}/g; //regex expression to get anything inside curly brackets
      var content = $(this).html();
      content = content.replace(/\[\[/g, '{{').replace(/\]\]/g, '}}');

      $(this).html(content);
      var matchedContent;
      var allCommands = [];
      var type;

      while ((matchedContent = regexExpression.exec(content))) {
        type = null;

        //strips html tags
        matchedContent[2] = matchedContent[2].replace(/(<([^>]+)>)/gi, '');

        if (matchedContent[1]) {
          if (matchedContent[1] == '#') {
            type = 'function';
          } else if (matchedContent[1] == '/') {
            type = 'closing';
          }
        } else {
          type = 'command';
        }
        if (type) {
          var commandData = getParametersAndCommand(matchedContent[2]);
          allCommands.push({
            type: type,
            command: commandData.command,
            parameters: commandData.parameters,
            index: matchedContent.index,
            length: matchedContent.length,
          });
        }
      }

      var executableCommands = getExecutableCommands(allCommands);
      var commandData;

      if (executableCommands.length > 0) {
        for (commandData of executableCommands) {
          runCommand($(this), commandData.command, commandData.parameters);
          if ($.inArray(commandData.command, ['address', 'step'])) {
            hasStepOrAddress = true;
          }
        }
      }
    });

    if (hasStepOrAddress) {
      removeSkeletolTimeout += 300;
    }

    setTimeout(function () {
      populateStepFields();

      $('form#new_request')
        .children('div.form-field')
        .each(function (index) {
          if (index === 0) {
            $(this).parent().show();
          }
        });

      restoreFormFields();
      $('#skeleton').remove();

      if (allowRequestSubmit) {
        $('form')
          .children('footer')
          .each(function (index) {
            $(this).show();
          });
      }

      $(document).on('click', '.radio-single', function () {
        var radioName = $(this).attr('name');
        $('#' + radioName).val(
          $('input[name=' + radioName + ']:checked').val()
        );
      });
    }, removeSkeletolTimeout);
  }, 600);
  setTimeout(function () {
    if (hasTime) {
      $('body').append(
        `<script src="https://cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script>`
      );

      $('head').append(
        `<style>
        .ui-timepicker-container {
            position: absolute;
            overflow: hidden;
            box-sizing: border-box;
        }

        .ui-timepicker {
            box-sizing: content-box;
            display: block;
            height: 205px;
            list-style: none outside none;
            margin: 0;
            padding: 0 1px;
            text-align: center;
        }

        .ui-timepicker-viewport {
            box-sizing: content-box;
            display: block;
            height: 205px;
            margin: 0;
            padding: 0;
            overflow: auto;
            overflow-x: hidden; /* IE */
        }

        .ui-timepicker-standard {
            font-size: 12px;
            background-color: #FFF;
            border: 1px solid #AAA;
            color: #222;
            /* overwrites .ui-menu */
            margin: 0;
            padding: 0;
        }
        .ui-timepicker-standard a {
            border: 1px solid transparent;
            color: #222;
            display: block;
            padding: 0.2em 0.4em;
            text-decoration: none;
            text-align: left;
            cursor: pointer;
        }
        .ui-timepicker-standard .ui-state-hover {
            background-color: #Ddd;
            font-weight: normal;
            color: #212121;
        }
        .ui-timepicker-standard .ui-menu-item {
            margin: 0;
            padding: 0;
        }

        .ui-timepicker-corners,
        .ui-timepicker-corners .ui-corner-all {
            -moz-border-radius: 4px;
            -webkit-border-radius: 4px;
            border-radius: 4px;
        }

        .ui-timepicker-hidden {
            /* overwrites .ui-helper-hidden */
            display: none;
        }

        .ui-timepicker-no-scrollbar .ui-timepicker {
            border: none;
        }
        .timepicker-wrap{
          position: relative;
        }
        .timepicker-wrap .clock-icon {
          display: block;
          content: 'X';
          height : 16px;
          width : 16px;
          position: absolute;
          top: 10px;
          text-indent: -9999px;
          cursor:pointer;
        }
        .timepicker-wrap .clock-icon {
          left : 10px;
          background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' focusable='false' viewBox='0 0 16 16' role='presentation'%3E%3Cg fill='none' stroke='currentColor'%3E%3Ccircle cx='8' cy='8' r='7.5'%3E%3C/circle%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' d='M7.5 3v5.5H11'%3E%3C/path%3E%3C/g%3E%3C/svg%3E");
        }
        .timepicker-wrap .arrow-icon:after {
          color: rgb(153, 153, 153);
          content: "▾";
          line-height: 1em;
          position: absolute;
          right: 10px;
          top: 25%;
          display:block;
          font-style:normal;
          cursor: pointer;
        }
        
        .timepicker-wrap input{
          padding-left: 30px;
          padding-right: 30px;
        }
        </style>`
      );

      var wrapDiv = $("<div class='timepicker-wrap' />");
      $("<div class='time-element' />").appendTo(wrapDiv);
      $("<i class='clock-icon'>Clock</i>").appendTo(wrapDiv);
      $("<i class='arrow-icon'></i>").appendTo(wrapDiv);

      $('input[type=time].timepicker').each(function () {
        $(this).wrap(wrapDiv);
      });

      $('input[type=time].timepicker').on('focus blur', function (e) {
        if (e.type == 'focus') {
          $(this).closest('.timepicker-wrap').addClass('active-picker');
        } else {
          var $this = $(this);
          setTimeout(function () {
            $this.closest('.timepicker-wrap').removeClass('active-picker');
          }, 300);
        }
      });

      $('.timepicker-wrap .clock-icon, .timepicker-wrap .arrow-icon').on(
        'click',
        function (e) {
          e.preventDefault();
          var $this = $(this);
          var parentNode = $this.closest('.timepicker-wrap');
          if (!parentNode.hasClass('active-picker')) {
            setTimeout(function () {
              parentNode.find('input.timepicker').trigger('focus');
            }, 100);
          }
        }
      );

      setTimeout(function () {
        let timeScript = `<script>`;
        $('input[type=time].timepicker').each(function () {
          $(this).attr('type', 'text');
          let format = $(this).data('format')
            ? $(this).data('format')
            : 'h:mm p';
          let dynamic = true;
          if ($(this).data('dynamic')) {
            dynamic = $(this).data('dynamic') == 'true' ? true : false;
          }
          let interval = $(this).attr('step')
            ? parseInt($(this).attr('step'))
            : 15;
          let min = $(this).attr('min') ? $(this).attr('min') : '00:00';
          let max = $(this).attr('max') ? $(this).attr('max') : '23:59';
          let value = $(this).val() ? $(this).val() : '';
          let id = $(this).attr('id');

          timeScript += `$("#${id}").timepicker({
          timeFormat: "${format}",
          interval: ${interval},
          minTime: "${min}",
          maxTime: "${max}",
          defaultTime: "${value}",
          dynamic: ${dynamic},
          dropdown: true,
          scrollbar: true
        });`;
        });
        timeScript += `</script>`;
        $('body').append(timeScript);
      }, 1000);
    }
    if (hasRange) {
      $('head').append(
        `<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/rangeslider.js/2.3.3/rangeslider.min.css" integrity="sha512-Rp0yZ3NMh1xOUZ4VHYggmX4pq4ZJdpcOETH03qBD5qNDsqTBw1MzUnX0T5PcTJmr2mNTOmtbxsHaGwzjylNpHA==" crossorigin="anonymous" />`
      );

      $('body').append(
        `<script src="https://cdnjs.cloudflare.com/ajax/libs/rangeslider.js/2.3.3/rangeslider.min.js" integrity="sha512-BUlWdwDeJo24GIubM+z40xcj/pjw7RuULBkxOTc+0L9BaGwZPwiwtbiSVzv31qR7TWx7bs6OPTE5IyfLOorboQ==" crossorigin="anonymous"></script>`
      );

      $('head').append(
        `<style>
        .rangeslider--horizontal .rangeslider__handle{
          top : -8px;
        }
        .rangeslider__handle{
          height : 25px;
          width :25px;
        }
        .rangeslider__handle:after{
          width :12px;
          height : 12px;
        }
        .rangeslider--horizontal {
          height : 10px;
        }
        .rangeslider__fill {
          background: #1f73b7;
        }
        input[type=range] {
          border: none;
          -webkit-appearance: none;
          width: 100%;
          padding: 0px;
          border-radius: 3px;
          height: 7px;
        }
        input[type=range]:focus {
          outline: none;
          border: 0px;
        }
        input[type=range]::-webkit-slider-runnable-track {
          width: 100%;
          height: 7px;
          cursor: pointer;
          background: transparent;
          border-radius: 3px;
        }
        input[type=range]::-webkit-slider-thumb {
          height: 20px;
          width: 20px;
          border-radius: 10px;
          background:#1F73B7;
          cursor: pointer;
          -webkit-appearance: none;
          margin-top: -6px;
          box-shadow: rgba(47, 57, 65, 0.24) 0px 4px 8px 0px;
          border: 0px;
        }
        input[type=range]::-webkit-slider-thumb:hover {
          background: #144A75;
        }

        input[type=range]::-moz-range-track {
          width: 100%;
          height: 7px;
          cursor: pointer;
          background: transparent;
          border-radius: 3px;
        }
        input[type=range]::-moz-range-thumb {
          height: 20px;
          width: 20px;
          border-radius: 10px;
          background:#1F73B7;
          cursor: pointer;
          margin-top: -5px;
          box-shadow: rgba(47, 57, 65, 0.24) 0px 4px 8px 0px;
          border: 0px;
        }
        input[type=range]::-moz-range-thumb:hover {
          background: #144A75;
        }
        input[type=range]::-ms-track {
          width: 100%;
          height: 7px;
          cursor: pointer;
          background: transparent;
          border-color: transparent;
          color: transparent;
        }
        input[type=range]::-ms-fill-lower {
          background: #1F73B7;
          border-radius: 5px;
        }
        input[type=range]::-ms-fill-upper {
          background: #E9EBED;
          border-radius: 5px;
        }
        input[type=range]::-ms-thumb {
          height: 20px;
          width: 20px;
          border-radius: 10px;
          background:#1F73B7;
          cursor: pointer;
          margin-top: -5px;
        }
        input[type=range]:focus::-ms-fill-lower {
          background: #1F73B7;
        }
        input[type=range]:focus::-ms-fill-upper {
          background: #E9EBED;
        }
        </style>
        `
      );
      $('input[type=range]').on('change', function () {
        let value = $(this).val();
        let prepend = $(this).data('prepend')
          ? $(this).data('prepend') + ' '
          : '';
        let append = $(this).data('append') ? ' ' + $(this).data('append') : '';
        $(this)
          .closest('.form-field')
          .find('.range-value')
          .text(prepend + value + append);
      });
      $('input[type=range]').on('input', function () {
        var minValue = $(this).attr('min') ? $(this).attr('min') : 0;
        var maxValue = $(this).attr('max') ? $(this).attr('max') : 100;
        var calculatedValue =
          ($(this).val() - minValue) / (maxValue - minValue);
        var percentValue = calculatedValue * 100;

        $(this).css(
          'background-image',
          '-webkit-gradient(linear, left top, right top, ' +
          'color-stop(' +
          percentValue +
          '%, #1F73B7), ' +
          'color-stop(' +
          percentValue +
          '%, #E9EBED)' +
          ')'
        );

        $(this).css(
          'background-image',
          '-moz-linear-gradient(left center, #1F73B7 0%, #1F73B7 ' +
          percentValue +
          '%, #E9EBED ' +
          percentValue +
          '%, #E9EBED 100%)'
        );
      });

      $('input[type=range]').each(function () {
        $(this)
          .closest('.form-field')
          .find('label')
          .after('<div class="range-value"></div>');
        $(this).trigger('change');
        $(this).trigger('input');
      });

      setTimeout(function () {
        let rangeScript = `<script>$("input[type=range]").rangeslider();</script>`;
        $('body').append(rangeScript);
      }, 1000);
    }
    if (addressArray.length > 0) {
      $('head').append(
        `<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>`
      );
      $('head').append(
        `<script src="https://maps.googleapis.com/maps/api/js?key=${placeApiKey}&callback=initAutocomplete&libraries=places&v=weekly" async></script>`
      );
      let autoCompleteScript = `
        <script>
        let autoComplete;
        const componentForm = {
          locality: "long_name",
          administrative_area_level_1: "short_name",
          country: "long_name",
          postal_code: "short_name"
        };
        function initAutocomplete() {`;
      addressArray.forEach((parameters) => {
        autoCompleteScript = autoCompleteScript.concat(`
          let autocomplete_${parameters['address1']} = new google.maps.places.Autocomplete(
            document.getElementById('request_custom_fields_${parameters['address1']}'),
            { types: ["geocode"] }
          );
          autocomplete_${parameters['address1']}.setFields(["address_component"]);
          autoComplete = autocomplete_${parameters['address1']};
          autocomplete_${parameters['address1']}.addListener("place_changed", function(){
            $('#request_custom_fields_${parameters['address1']}').trigger("change");
            let place = autocomplete_${parameters['address1']}.getPlace();
            for (const component of place.address_components) {
              const addressType = component.types[0];
              switch(addressType){
                case "locality":
                  if (
                    ${parameters['city']} != undefined &&
                    $("#new_request").find(
                      '#request_custom_fields_${parameters['city']}'
                    ).length > 0
                  ) {
                    const city_val = component[componentForm[addressType]];
                    $('#request_custom_fields_${parameters['city']}').val(city_val);
                    $('#request_custom_fields_${parameters['city']}').trigger("change");
                  }
                  break;
                case "administrative_area_level_1":
                  if (
                    ${parameters['state']} != undefined &&
                    $("#new_request").find(
                      '#request_custom_fields_${parameters['state']}'
                    ).length > 0
                  ) {
                    const state_val = component[componentForm[addressType]];
                    $('#request_custom_fields_${parameters['state']}').val(state_val);
                    $('#request_custom_fields_${parameters['state']}').trigger("change");
                  }
                  break;
                case "country":
                  if (
                    ${parameters['country']} != undefined &&
                    $("#new_request").find(
                      '#request_custom_fields_${parameters['country']}'
                    ).length > 0
                  ) {
                    const country_val = component[componentForm[addressType]];
                    $('#request_custom_fields_${parameters['country']}').val(country_val);
                    $('#request_custom_fields_${parameters['country']}').trigger("change");
                    $('#request_custom_fields_${parameters['country']}').parent().show();
                    $('#request_custom_fields_${parameters['country']}').parent().parent().find('#country-select').remove();
                    if(${parameters['country_iso']} != undefined &&
                    $("#new_request").find(
                      '#request_custom_fields_${parameters['country_iso']}'
                    ).length > 0){
                      const country_iso = component["short_name"];
                      $('#request_custom_fields_${parameters['country_iso']}').val(country_iso);
                      $('#request_custom_fields_${parameters['country_iso']}').trigger("change");
                    }
                  }
                  break;
                case "postal_code":
                  if (
                    ${parameters['zip']} != undefined &&
                    $("#new_request").find(
                      '#request_custom_fields_${parameters['zip']}'
                    ).length > 0
                  ) {
                    const zip_val = component[componentForm[addressType]];
                    $('#request_custom_fields_${parameters['zip']}').val(zip_val);
                    $('#request_custom_fields_${parameters['zip']}').trigger("change");
                  }
                  break;
              }
            }
          });
        `);
      });
      autoCompleteScript = autoCompleteScript.concat(`}
        function geolocate() {
          if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition((position) => {
              const geolocation = {
                lat: position.coords.latitude,
                lng: position.coords.longitude,
              };
              const circle = new google.maps.Circle({
                center: geolocation,
                radius: position.coords.accuracy,
              });
              autocomplete.setBounds(circle.getBounds());
            });
          }
        }
        </script>`);
      $('head').append(autoCompleteScript);
    }

    // check required address checkbox on input change
    $(document).on('change', '.required-field', function (event) {
      let address1 = $(this)
        .closest('div.required')
        .find('input[data-for="address1"]')
        .val();
      let city = $(this)
        .closest('div.required')
        .find('input[data-for="city"]')
        .val();
      let zip = $(this)
        .closest('div.required')
        .find('input[data-for="zip"]')
        .val();
      let country = $(this)
        .closest('div.required')
        .find('input[data-for="country"]')
        .val();
      if (address1 !== '' && city !== '' && zip !== '' && country !== '') {
        $(this)
          .closest('div.required')
          .find('input[type="checkbox"]')
          .prop('checked', true);
      } else {
        $(this)
          .closest('div.required')
          .find('input[type="checkbox"]')
          .prop('checked', false);
      }
    });
    // autofill form
    let auto_fill = urlParams.get('auto_fill');

    if (auto_fill && auto_fill !== '') {
      try {
        autoFillData = atob(auto_fill);
        autoFillData = JSON.parse(autoFillData);
      } catch (error) {
        autoFillData = {};
        console.error('Invalid JSON');
      }
    }

    urlParams.forEach(function (value, key) {
      autoFillData[key] = value;
    });

    delete autoFillData['auto_fill'];
    delete autoFillData['ticket_form_id'];

    if (autoFillData['email']) {
      autoFillData['anonymous_requester_email'] = autoFillData['email'];
    }
    if (autoFillData['onSubmit'] && autoFillData['onSubmit'] == 'true') {
      // create replica of input with a button
      let autofillSubmitButton = document.createElement('button');
      autofillSubmitButton.innerHTML = $('#new_request')
        .find('footer')
        .find('input')
        .val();
      let backgroundColor = $('#new_request')
        .find('footer')
        .find('input')
        .css('background');
      let fontSize = $('#new_request')
        .find('footer')
        .find('input')
        .css('font-size');
      let fontWeight = $('#new_request')
        .find('footer')
        .find('input')
        .css('font-weight');
      let minWidth = $('#new_request')
        .find('footer')
        .find('input')
        .css('min-width');
      let lineHeight = $('#new_request')
        .find('footer')
        .find('input')
        .css('line-height');
      let height = $('#new_request')
        .find('footer')
        .find('input')
        .css('line-height');
      let borderColor = $('#new_request')
        .find('footer')
        .find('input')
        .css(' border-color');
      let color = $('#new_request').find('footer').find('input').css('color');
      let width = $('#new_request').find('footer').find('input').css('width');
      autofillSubmitButton.style.cssText = `display: inline-flex; -moz-box-align: center; align-items: center; -moz-box-pack: center; justify-content: center; transition: border-color 0.25s ease-in-out 0s, box-shadow 0.1s ease-in-out 0s, background-color 0.25s ease-in-out 0s, color 0.25s ease-in-out 0s; margin: 0px; border: none; border-radius: 4px; cursor: pointer; overflow: hidden; text-decoration: none; text-overflow: ellipsis; white-space: nowrap; font-family: inherit; font-weight: ${fontWeight}; box-sizing: border-box; user-select: none; padding: 0px 1.07143em; height: ${height}; font-size: ${fontSize};min-width: ${minWidth};width: ${width}; background: ${backgroundColor};outline: none;color:${color};border-color:${borderColor};line-height:${lineHeight}`;
      autofillSubmitButton.setAttribute('id', 'autofill_on_submit');
      $('#new_request').find('footer').find('input').hide();
      $('#new_request').find('footer').append(autofillSubmitButton);
      autoFillOnSubmit = true;
    } else {
      fillValues(autoFillData);
    }
    // create new request on form submit
    $('#submit_request').click(function (event) {
      event.preventDefault();
      $('#new_request').find('footer').find('input').trigger('click');
    });
  }, 1800);

  $(document).on('click', 'button#autofill_on_submit', function (event) {
    event.preventDefault();
    if (autoFillOnSubmit) {
      fillValues(autoFillData);
      $('#new_request').find('footer').find('input').trigger('click');
    }
  });

  function commandApplicable(field) {
    if ($(`.${field}`).prop('hidden') && $(`#${field}`).prop('disabled')) {
      return false;
    } else {
      return true;
    }
  }
  function fillValues(data) {
    for (const key in data) {
      if (Object.hasOwnProperty.call(data, key)) {
        const element = data[key];
        var regex = /\d/g;

        let fillField = regex.test(key)
          ? $(`#request_custom_fields_${key}`)
          : $(`#request_${key}`);

        if (fillField.length > 0) {
          if (
            key === 'description' &&
            fillField.data('helper') == 'wysiwyg' &&
            typeof tinymce !== 'undefined'
          ) {
            var currentContent = tinymce
              .get('request_description')
              .getContent();
            let newString = element.split('\\n').join('<br />');

            if (data[`prepend_${key}`] && data[`prepend_${key}`] == 'true') {
              let finalContent = newString.concat(currentContent);
              tinymce.get('request_description').setContent(finalContent);
            } else {
              prependAutoFilledRequestDescrioptionContent = false;
              let finalContent = currentContent.concat(newString);
              tinymce.get('request_description').setContent(finalContent);
            }
          } else if (fillField.attr('type') === 'checkbox' && element) {
            $(`#request_custom_fields_${key}`).prop('checked', true);
          } else {
            if (data[`prepend_${key}`] && data[`prepend_${key}`] == 'true') {
              let currentValue = fillField.val();
              let newValue = `${element} ${currentValue}`;
              fillField.val(newValue);
            } else {
              let currentValue = fillField.val();
              let newValue = `${currentValue} ${element}`;
              fillField.val(newValue);
            }
          }
        }
        if (!autoFillOnSubmit) {
          autoFilledRequestDescrioptionContent = tinymce
            .get('request_description')
            .getContent();
        }
      }
    }
  }

  function populateStepFields() {
    let stepC = 0;
    $('div.form-field').each(function () {
      if ($(this).hasClass('step')) {
        stepC = parseInt(stepC) + 1;
      }
      if (
        stepC > 0 &&
        !$(this).closest('div').hasClass('collective-form-field')
      ) {
        $(this).addClass('step-' + stepC);
      }
      if (activeType == 'progress') {
        $('.step-' + stepC).appendTo('#progress-item-' + stepC);
      }
      if (activeType == 'accordion') {
        $('.step-' + stepC).appendTo('#block-accordion-item-' + stepC);
      }
      if (activeType == 'horizontal') {
        $('.step-' + stepC).prependTo('#block-stepper-' + stepC);
      }
      if (activeType == 'vertical') {
        $('.step-' + stepC).prependTo('#vertical-item-' + stepC);
      }
    });
    $('.progress-bar').attr('data-id', stepC);
    $('.progress-bar').css('width', 100 / parseInt(stepC) + '%');
    if (hideNext) {
      $('form').find("button[type='submit']").hide();
      $('form').find("button[type='submit']").prop('disabled', true);
    }

    // hide vertical step if no content
    let formFieldCount = 0;
    let listCount = 0;
    $('.block-stepper-body-inner').each(function (index) {
      formFieldCount = 0;
      $(this)
        .find('.form-field')
        .each(function (form_field_index) {
          if ($(this).css('display') === 'block') {
            formFieldCount += 1;
          }
        });
      if (formFieldCount === 0) {
        if (index === 0) {
          $(this).find('.block-stepper-action-next').trigger('click');
        }
        $(this).parent().parent().remove();
      }
    });
    // manage steps count for vertical if no content
    $('.block-stepper-vertical')
      .children('li')
      .each(function (list_index) {
        if ($(this).find('.stepper-number').length > 0) {
          listCount += 1;
          $(this).find('.stepper-number').html(listCount);
        }
        if (list_index === 0) {
          $(this).find('.block-stepper-action-back').remove();
        }
      });
    // hide horizontal step if no content
    $('.block-stepper-horizontal')
      .find('.block-stepper-body')
      .each(function (index) {
        formFieldCount = 0;
        $(this)
          .find('.form-field')
          .each(function (form_field_index) {
            if ($(this).css('display') === 'block') {
              formFieldCount += 1;
            }
          });
        if (formFieldCount === 0) {
          if (index === 0) {
            $(this).find('.block-stepper-action-next').trigger('click');
          }
          $(this)
            .parent()
            .find('#horizontal-item')
            .find(`li[data-id=block-stepper-${index + 1}]`)
            .remove();
          $(this).remove();
        }
      });
    // manage horizontal steps if no content
    $('#horizontal-item')
      .children('li')
      .each(function (list_index) {
        if ($(this).find('.stepper-number').length > 0) {
          listCount += 1;
          $(this).find('.stepper-number').html(listCount);
        }
        if (list_index === 0) {
          $(this).find('.step_line').remove();
        }
      });
    // manage horizontal previous
    $('.block-stepper-horizontal')
      .children('div')
      .each(function (div_index) {
        if (div_index === 0) {
          $(this).find('.block-stepper-action-back').remove();
        }
      });
    // hide accordion content if no content
    $('.block-accordion-body-inner').each(function (index) {
      formFieldCount = 0;
      $(this)
        .find('.form-field')
        .each(function (form_field_index) {
          if ($(this).css('display') === 'block') {
            formFieldCount += 1;
          }
        });
      if (formFieldCount === 0) {
        $(this).parent().parent().remove();
      }
    });

    $('.progress-body').each(function (index) {
      formFieldCount = 0;
      $(this)
        .find('.form-field')
        .each(function (form_field_index) {
          if ($(this).css('display') === 'block') {
            formFieldCount += 1;
          }
        });
      if (formFieldCount === 0) {
        if (index === 0) {
          $(this).parent().find('.progress-next').trigger('click');
        }
        $(this).parent().remove();
      }
    });
    // remove previous button for progress if neded
    $('#progress-div')
      .children('div')
      .each(function (div_index) {
        $(this).attr('id', `progress-block-${div_index + 1}`);
        $(this)
          .find('button')
          .attr('data-id', `${div_index + 1}`);
        if (div_index === 0 && $(this).find('.progress-back').length > 0) {
          $(this).find('.progress-back').remove();
        }
      });
  }

  function getParametersAndCommand(commandText) {
    var actionFieldRegex = /(\w+)\=\"([^\"]*)\"|\w+/gi;
    var actionFieldCount = 0;
    var command = '';
    var parameters = {};
    var actionField;

    while ((actionField = actionFieldRegex.exec(commandText))) {
      if (actionFieldCount == 0) {
        command = actionField[0];
      } else {
        if (typeof actionField[1] != 'undefined') {
          parameters[actionField[1]] = actionField[2];
        } else {
          parameters[actionField[0]] = null;
        }
      }
      actionFieldCount++;
    }
    return {
      command: command,
      parameters: parameters,
    };
  }

  function getFunctionData(command, commandArray, commandIndex) {
    var nextIndex = commandIndex + 1;
    var remainingCommands = commandArray.slice(nextIndex);
    var closingCommandIndex = remainingCommands.findIndex(
      (commandDetail) =>
        commandDetail.type === 'closing' && commandDetail.command === command
    );

    if (closingCommandIndex >= 0) {
      return {
        functionCommands: remainingCommands.slice(0, closingCommandIndex),
        closingCommandIndex: nextIndex + closingCommandIndex,
      };
    } else {
      return {
        functionCommands: [],
        closingCommandIndex: -1,
      };
    }
  }

  function getExecutableCommands(commandArray) {
    var commandIndex = 0;
    var executeCommand = [];
    while (commandIndex < commandArray.length) {
      if (commandArray[commandIndex].type == 'function') {
        var functionData = getFunctionData(
          commandArray[commandIndex].command,
          commandArray,
          commandIndex
        );
        if (functionData.closingCommandIndex !== -1) {
          var commandCount = 0;
          var caseCommand = {
            command: commandArray[commandIndex].command,
            parameters: commandArray[commandIndex].parameters,
          };
          caseCommand.parameters.commands = functionData.functionCommands;
          executeCommand.push(caseCommand);
          commandIndex = functionData.closingCommandIndex;
        } else {
          console.error(
            'No closing tag found for ' +
            commandIndex +
            ' ' +
            commandArray[commandIndex].command
          );
          commandIndex = commandArray.length;
        }
      } else if (commandArray[commandIndex].type == 'command') {
        executeCommand.push({
          command: commandArray[commandIndex].command,
          parameters: commandArray[commandIndex].parameters,
        });
        commandIndex++;
      } else {
        commandIndex++;
      }
    }
    return executeCommand;
  }

  function runCommand($this, command, parameters) {
    var form = $this.closest('form');
    var formField = $this.closest('.form-field');
    var prependLabel = document.createElement('label');
    prependLabel.style.display = 'none';
    if ($.inArray(command, replaceElements) !== -1) {
      $this.parent().html(function () {
        var labelText = '';
        if (typeof parameters['text'] != 'undefined') {
          labelText = parameters['text'];
        } else {
          $(this).find('label').find('span').remove();
          labelText = $('<div/>').html($(this).find('label').contents()).text();
        }
        return $('<' + command + '/>').append(labelText);
      });
      formField.prepend(prependLabel);
      formField.show();
    } else if (command == 'infobox') {
      $this.parent().html(function () {
        var labelText = '';
        if (typeof parameters['text'] != 'undefined') {
          labelText = parameters['text'];
        } else {
          $(this).find('label').find('span').remove();
          labelText = $('<div/>').html($(this).find('label').contents()).text();
        }
        return (
          "<div class='alert alert-primary' /><p>" + labelText + '</p><div/>'
        );
      });
      formField.prepend(prependLabel);
    } else if (command == 'email') {
      if ($('#request_anonymous_requester_email').length > 0) {
        $this
          .closest('.form-field')
          .replaceWith(
            $('#request_anonymous_requester_email').closest('.form-field')
          );
      } else {
        $this.parent().hide();
      }
    } else if (command == 'user_details') {
      var userDetails = '';
      userDetails +=
        'OS: ' +
        window.browserInfo.os +
        ' ' +
        window.browserInfo.osVersion +
        ' \n';
      userDetails +=
        'Browser: ' +
        window.browserInfo.browser +
        ' ' +
        window.browserInfo.browserVersion +
        ' \n';
      userDetails += 'Mobile: ' + window.browserInfo.mobile + ' \n';
      userDetails += 'Cookies: ' + window.browserInfo.cookies + ' \n';
      userDetails += 'Screensize: ' + window.browserInfo.screen + ' \n';
      userDetails += 'Viewportsize: ' + window.browserInfo.viewport + '\n';
      userDetails += 'Full user agent: ' + window.browserInfo.userAgent;
      var descriptionField = $this.parent().find('textarea');

      if (
        descriptionField.data('helper') == 'wysiwyg' &&
        typeof tinymce !== 'undefined'
      ) {
        tinymce
          .get('request_description')
          .setContent(userDetails.replace(/\n/g, '<br />'));
      } else {
        descriptionField.val(userDetails);
      }
      $this.parent().hide();
    } else if (command == 'subject') {
      if (typeof parameters['ticket_form_name'] != 'undefined') {
        setSubjectForForm(false);
        $this.parent().hide();
      }
      if (typeof parameters['custom_fields'] != 'undefined') {
        $this.parent().hide();
        var includeFields =
          typeof parameters['includes'] != 'undefined'
            ? parameters['includes'].split(',')
            : [];

        var excludeFields =
          typeof parameters['excludes'] != 'undefined'
            ? parameters['excludes'].split(',')
            : [];

        $(
          "input[name*='request[custom_fields]'], textarea[name*='request[custom_fields]'], select[name*='request[custom_fields]']"
        ).each(function () {
          if (checkAddToDescription($(this), includeFields, excludeFields)) {
            $(this).addClass('addToTitle');
          } else {
            $(this).removeClass('addToTitle');
          }
        });

        setTitleData();
        $(document).delegate(
          "input[name*='request[custom_fields]'], textarea[name*='request[custom_fields]'], select[name*='request[custom_fields]']",
          'change',
          function () {
            //code goes her
            if (checkAddToDescription($(this), includeFields, excludeFields)) {
              $(this).addClass('addToTitle');
            } else {
              $(this).removeClass('addToTitle');
            }

            setTitleData();
          }
        );
      }
      if (typeof parameters['set'] != 'undefined') {
        $("input[name='request[subject]']").val(parameters['set']);
      }
      if (typeof parameters['hide'] != 'undefined') {
        $("input[name='request[subject]']").parent().hide();
      }
      if (typeof parameters['disabled'] != 'undefined') {
        $("input[name='request[subject]']").prop('readonly', true);
      }
      $this.hide();
    } else if (command == 'hide') {
      if (typeof parameters['request_cc_emails'] != 'undefined') {
        $('#request_collaborators_').closest('.form-field').hide();
        $this.parent().hide();
      }
      if (typeof parameters['attachments'] != 'undefined') {
        $('#request-attachments').closest('.form-field').hide();
        $this.parent().hide();
      }
      if (
        typeof parameters['submit'] != 'undefined' &&
        !$('input[type="checkbox"]').is('[disabled]')
      ) {
        form.find("input[type='submit']").prop('disabled', false);
        form.find("input[type='submit']").hide();
        $this.parent().hide();
      }
      if (typeof parameters['optional'] != 'undefined') {
        form.find('span.optional').hide();
        $this.parent().hide();
      }
    } else if (command == 'description') {
      if (typeof parameters['custom_fields'] != 'undefined') {
        if (typeof parameters['show_desc'] == 'undefined') {
          $("textarea[name='request[description]']").parent().hide();
        }
        var includeFields =
          typeof parameters['includes'] != 'undefined'
            ? parameters['includes'].split(',')
            : [];

        var excludeFields =
          typeof parameters['excludes'] != 'undefined'
            ? parameters['excludes'].split(',')
            : [];
        $(document).delegate(
          "input[name*='request[custom_fields]'], textarea[name*='request[custom_fields]'], select[name*='request[custom_fields]']",
          'change',
          function () {
            //code goes her
            if (checkAddToDescription($(this), includeFields, excludeFields)) {
              $(this).addClass('addToDescriptionField');
            } else {
              $(this).removeClass('addToDescriptionField');
            }
            let customFieldValues = '';
            if (
              autoFilledRequestDescrioptionContent &&
              prependAutoFilledRequestDescrioptionContent
            ) {
              customFieldValues = autoFilledRequestDescrioptionContent;
            }

            $('.addToDescriptionField').each(function (e) {
              let fieldId = $(this).attr('id');
              if (fieldId && fieldId !== '') {
                customFieldValues +=
                  $(`#${fieldId}_label`).text().replace('(optional)', '') +
                  ' : ' +
                  $(this).val() +
                  '\n';
              }
            });
            if (
              autoFilledRequestDescrioptionContent &&
              !prependAutoFilledRequestDescrioptionContent
            ) {
              customFieldValues += autoFilledRequestDescrioptionContent;
            }
            if (
              $("textarea[name='request[description]']").data('helper') ==
              'wysiwyg' &&
              typeof tinymce !== 'undefined'
            ) {
              tinymce
                .get('request_description')
                .setContent(customFieldValues.replace(/\n/g, '<br />'));
            } else {
              $("textarea[name='request[description]']").val(customFieldValues);
            }
          }
        );
        let customFieldInitialValues = '';
        if (
          autoFilledRequestDescrioptionContent &&
          prependAutoFilledRequestDescrioptionContent
        ) {
          customFieldInitialValues = autoFilledRequestDescrioptionContent;
        }
        $(
          "input[name*='request[custom_fields]'], textarea[name*='request[custom_fields]'], select[name*='request[custom_fields]']"
        ).each(function () {
          if (checkAddToDescription($(this), includeFields, excludeFields)) {
            $(this).addClass('addToDescriptionField');
            let fieldId = $(this).attr('id');
            if (fieldId) {
              customFieldInitialValues +=
                $(`#${fieldId}_label`).text().replace('(optional)', '') +
                ' : ' +
                $(this).val() +
                '\n';
            }
          } else {
            $(this).removeClass('addToDescriptionField');
          }
        });
        if (
          autoFilledRequestDescrioptionContent &&
          !prependAutoFilledRequestDescrioptionContent
        ) {
          customFieldInitialValues += autoFilledRequestDescrioptionContent;
        }
        if (
          $("textarea[name='request[description]']").data('helper') ==
          'wysiwyg' &&
          typeof tinymce !== 'undefined'
        ) {
          tinymce
            .get('request_description')
            .setContent(customFieldInitialValues.replace(/\n/g, '<br />'));
        } else {
          $("textarea[name='request[description]']").val(
            customFieldInitialValues
          );
        }
        if (typeof parameters['show_field'] != 'undefined') {
          $this.hide();
        } else {
          $this.parent().hide();
        }
      }
    } else if (command == 'submit') {
      if (typeof parameters['block'] != 'undefined') {
        (function ($) {
          $.each(['show', 'hide'], function (i, ev) {
            var el = $.fn[ev];
            $.fn[ev] = function () {
              this.trigger(ev);
              return el.apply(this, arguments);
            };
          });
        })(jQuery);

        var descriptionId = $this.attr('id');
        var parentId = descriptionId + '_parent';
        $this.parent().attr('id', parentId);
        var observer = new MutationObserver(function (mutations) {
          mutations.forEach(function (mutationRecord) {
            if ($('#' + parentId)[0].hasAttribute('hidden')) {
              form.find("input[type='submit']").prop('disabled', false);
            } else {
              form.find("input[type='submit']").prop('disabled', true);
            }
            if (typeof parameters['show_field'] == 'undefined') {
              $('#' + parentId).hide();
            }
          });
        });

        var target = document.getElementById(parentId);
        observer.observe(target, {
          attributes: true,
          attributeFilter: ['hidden', 'style'],
        });
        if (typeof parameters['show_field'] == 'undefined') {
          $this.parent().hide();
        }
      }
    } else if (command == 'field_modifier' && parameters['id']) {
      $this.parent().hide();
      let commandFieldHtmlId = $this
        .parent()
        .find('input[type=checkbox]')
        .attr('id');
      let fieldId = parameters['id'];
      let excludeTags = parameters['exclude']
        ? parameters['exclude'].split(',')
        : [];
      let includeTags = parameters['include']
        ? parameters['include'].split(',')
        : [];
      let min = parameters['min'] ? parameters['min'] : 0;
      let max = parameters['max'] ? parameters['max'] : 0;
      let tagsUrl = parameters['url'] ? parameters['url'] : null;
      let verification =
        parameters['verification'] != undefined && tagsUrl ? true : false;

      if (excludeTags.length > 0 || includeTags.length > 0) {
        let fieldType = checFieldType(fieldId);
        if (fieldType === 'Multi-select') {
          let multiSelectValue = '';
          let wildCard = /[*]/;
          let excludeIsWildCard = false;
          let includeIsWildCard = false;
          let unExcludedTags = [];
          $(`#request_custom_fields_${fieldId}`)
            .parent()
            .find('.hc-multiselect-menu ul li')
            .each(function () {
              multiSelectValue = $(this).find('input').val();
              if (excludeTags.length > 0) {
                excludeTags.forEach((element) => {
                  // Tesing for presence of wildcard *
                  if (wildCard.test(element)) {
                    let willdCardTagsArray = element.split('*');
                    if (willdCardTagsArray.length > 1) {
                      excludeIsWildCard = true;
                      if (multiSelectValue.includes(willdCardTagsArray[0])) {
                        $(this).hide();
                        $(this).addClass('shouldBeRemoved');
                      }
                    }
                  } else {
                    if (multiSelectValue == element) {
                      $(this).hide();
                      $(this).addClass('shouldBeRemoved');
                    }
                  }
                });
                if (!$(this).hasClass('shouldBeRemoved')) {
                  unExcludedTags.push(multiSelectValue);
                }
              }
              if (includeTags.length > 0) {
                includeTags.forEach((element) => {
                  // Tesing for presence of wildcard *
                  if (wildCard.test(element)) {
                    let willdCardTagsArray = element.split('*');
                    if (willdCardTagsArray.length > 1) {
                      includeIsWildCard = true;
                      if (
                        !multiSelectValue.includes(willdCardTagsArray[0]) &&
                        !$(this).hasClass('shouldNotBeRemoved')
                      ) {
                        $(this).hide();
                        $(this).addClass('shouldBeRemoved');
                      } else {
                        $(this).show();
                        $(this).addClass('shouldNotBeRemoved');
                        $(this).removeClass('shouldBeRemoved');
                      }
                    }
                  } else {
                    if (
                      !multiSelectValue.includes(element) &&
                      !$(this).hasClass('shouldNotBeRemoved')
                    ) {
                      $(this).hide();
                      $(this).addClass('shouldBeRemoved');
                    } else {
                      $(this).show();
                      $(this).addClass('shouldNotBeRemoved');
                      $(this).removeClass('shouldBeRemoved');
                    }
                  }
                });
              }
              if (excludeIsWildCard && includeTags.length > 0) {
                if (unExcludedTags.includes(multiSelectValue)) {
                  $(this).show();
                  $(this).removeClass('shouldBeRemoved');
                }
              }
              if (includeIsWildCard && excludeTags.length > 0) {
                if (excludeTags.includes(multiSelectValue)) {
                  $(this).hide();
                }
              }
            });
        }
        let area_control = $(`.request_custom_fields_${fieldId}`)
          .find('.nesty-input')
          .attr('aria-controls');
        if (fieldType === 'Drop-down') {
          let filteredTagNames = getFormFields(
            fieldId,
            includeTags,
            excludeTags
          );
          let multiSelectValue = '';
          let wildCard = /[*]/;
          let excludeIsWildCard = false;
          let includeIsWildCard = false;
          let unExcludedTags = [];
          function observeNestyPanelChanges(area_control, commandFieldHtmlId, includeTags, excludeTags) {
            const observer = new MutationObserver(function(mutations) {
              mutations.forEach(function(mutation) {
                if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
                  mutation.addedNodes.forEach(function(node) {
                    if (node.nodeType === Node.ELEMENT_NODE) {
                      const $panel = $(node).closest('.nesty-panel');
                      if ($panel.length > 0 && 
                          $panel.attr('id') === area_control &&
                          commandFieldHtmlId &&
                          commandApplicable(commandFieldHtmlId)) {
                        
                        let multiSelectValue = '';
                        let wildCard = /[*]/;
                        let excludeIsWildCard = false;
                        let includeIsWildCard = false;
                        let unExcludedTags = [];
                        
                        $panel.find('li').each(function (params) {
                          multiSelectValue = $(this).attr('id');
                          if (
                            !$(this).hasClass('nesty-expand') &&
                            !$(this).hasClass('nesty-collapse')
                          ) {
                            if (excludeTags.length > 0) {
                              excludeTags.forEach((element) => {
                                if (wildCard.test(element)) {
                                  let willdCardTagsArray = element.split('*');
                                  if (willdCardTagsArray.length > 1) {
                                    excludeIsWildCard = true;
                                    if (multiSelectValue.includes(willdCardTagsArray[0])) {
                                      $(this).hide();
                                      $(this).addClass('shouldBeRemoved');
                                    }
                                  }
                                } else {
                                  if (multiSelectValue === element) {
                                    $(this).hide();
                                    $(this).addClass('shouldBeRemoved');
                                  }
                                }
                              });
                              if ($(this).is(':visible')) {
                                unExcludedTags.push(multiSelectValue);
                              }
                            }
                            if (includeTags.length > 0) {
                              includeTags.forEach((element) => {
                                if (wildCard.test(element)) {
                                  let willdCardTagsArray = element.split('*');
                                  if (willdCardTagsArray.length > 1) {
                                    includeIsWildCard = true;
                                    if (
                                      !multiSelectValue.includes(willdCardTagsArray[0]) &&
                                      !$(this).hasClass('shouldNotBeRemoved')
                                    ) {
                                      $(this).hide();
                                      $(this).addClass('shouldBeRemoved');
                                    } else {
                                      $(this).show();
                                      $(this).addClass('shouldNotBeRemoved');
                                    }
                                  }
                                } else {
                                  if (
                                    !multiSelectValue.includes(element) &&
                                    !$(this).hasClass('shouldNotBeRemoved')
                                  ) {
                                    $(this).hide();
                                    $(this).addClass('shouldBeRemoved');
                                  } else {
                                    $(this).show();
                                    $(this).addClass('shouldNotBeRemoved');
                                    $(this).removeClass('shouldBeRemoved');
                                  }
                                }
                              });
                            }
                            if (excludeIsWildCard && includeTags.length > 0) {
                              if (unExcludedTags.includes(multiSelectValue)) {
                                $(this).show();
                              }
                            }
                            if (includeIsWildCard && excludeTags.length > 0) {
                              if (excludeTags.includes(multiSelectValue)) {
                                $(this).hide();
                              }
                            }
                          } else if ($(this).hasClass('nesty-expand')) {
                            filteredTagNames
                              .then((result) => {
                                let tagName = $(this).html();
                                if (
                                  result.excludeAbleTagNames &&
                                  result.excludeAbleTagNames.length > 0
                                ) {
                                  if (
                                    result.excludeAbleTagNames.includes(tagName) &&
                                    !result.includeAbleTagNames.includes(tagName)
                                  ) {
                                    $(this).hide();
                                  }
                                }
                                if (
                                  result.includeAbleTagNames &&
                                  result.includeAbleTagNames.length > 0
                                ) {
                                  if (!result.includeAbleTagNames.includes(tagName)) {
                                    $(this).hide();
                                  }
                                }
                              })
                              .catch((err) => { });
                          }
                        });
                      }
                    }
                  });
                }
              });
            });

            // Start observing
            const targetElement = document.body;
            observer.observe(targetElement, {
              childList: true,
              subtree: true
            });
            
            return observer;
          }

          // Call the observer function
          observeNestyPanelChanges(area_control, commandFieldHtmlId, includeTags, excludeTags);
        }
      }
      if (min) {
        allowRequestSubmit = false;
        $(`#request_custom_fields_${fieldId}_label`).append(
          `<small>(minimum ${min} tags required)</small>`
        );
        $('.request-form')
          .find('footer')
          .find('input')
          .attr('disabled', 'disabled');
        hideNext = true;
      }
      if (max) {
        $(`#request_custom_fields_${fieldId}_label`).append(
          `<small>(maximum ${max} tags allowed)</small>`
        );
      }
      if (min || max) {
        $(`#request_custom_fields_${fieldId}`)
          .parent()
          .find('.hc-multiselect-menu')
          .click(function () {
            let selectedTagsNumber = $(`#request_custom_fields_${fieldId}`)
              .find('ul')
              .find('li').length;
            if (min) {
              if (selectedTagsNumber >= min) {
                $('form')
                  .children('footer')
                  .each(function (index) {
                    $(this).show();
                  });
                $('.request-form')
                  .find('footer')
                  .find('input')
                  .removeAttr('disabled');
                $('form').find("button[type='submit']").show();
                $('form').find("button[type='submit']").prop('disabled', false);
              } else {
                $('form')
                  .children('footer')
                  .each(function (index) {
                    $(this).hide();
                  });
                $('.request-form')
                  .find('footer')
                  .find('input')
                  .attr('disabled', 'disabled');
                $('form').find("button[type='submit']").hide();
                $('form').find("button[type='submit']").prop('disabled', true);
              }
            }
            if (max) {
              if (selectedTagsNumber > max) {
                $('form')
                  .children('footer')
                  .each(function (index) {
                    $(this).hide();
                  });
                $('.request-form')
                  .find('footer')
                  .find('input')
                  .attr('disabled', 'disabled');
                $('form').find("button[type='submit']").hide();
                $('form').find("button[type='submit']").prop('disabled', true);
              } else {
                $('form')
                  .children('footer')
                  .each(function (index) {
                    $(this).show();
                  });
                $('.request-form')
                  .find('footer')
                  .find('input')
                  .removeAttr('disabled');
                $('form').find("button[type='submit']").show();
                $('form').find("button[type='submit']").prop('disabled', false);
              }
            }
          });
        $(`#request_custom_fields_${fieldId}`).click(function () {
          let selectedTagsNumber = $(`#request_custom_fields_${fieldId}`)
            .find('ul')
            .find('li').length;
          if (min) {
            if (selectedTagsNumber >= min) {
              $('form')
                .children('footer')
                .each(function (index) {
                  $(this).show();
                });
              $('.request-form')
                .find('footer')
                .find('input')
                .removeAttr('disabled');
              $('form').find("button[type='submit']").show();
              $('form').find("button[type='submit']").prop('disabled', false);
            } else {
              $('form')
                .children('footer')
                .each(function (index) {
                  $(this).hide();
                });
              $('.request-form')
                .find('footer')
                .find('input')
                .attr('disabled', 'disabled');
              $('form').find("button[type='submit']").hide();
              $('form').find("button[type='submit']").prop('disabled', true);
            }
          }
          if (max) {
            if (selectedTagsNumber > max) {
              $('form')
                .children('footer')
                .each(function (index) {
                  $(this).hide();
                });
              $('.request-form')
                .find('footer')
                .find('input')
                .attr('disabled', 'disabled');
              $('form').find("button[type='submit']").hide();
              $('form').find("button[type='submit']").prop('disabled', true);
            } else {
              $('form')
                .children('footer')
                .each(function (index) {
                  $(this).show();
                });
              $('.request-form')
                .find('footer')
                .find('input')
                .removeAttr('disabled');
              $('form').find("button[type='submit']").show();
              $('form').find("button[type='submit']").prop('disabled', false);
            }
          }
        });
      }
      if (tagsUrl) {
        $.get(tagsUrl, function (tags, status) {
          let availableTags = new Array();
          let availableTitle = new Array();
          if (tags.length > 0) {
            tags.data.forEach((element) => {
              availableTags.push(element.tag);
              availableTitle.push(element.title);
            });
          } else {
            tags.data = [];
          }
          let fieldType = checFieldType(fieldId);
          switch (fieldType) {
            case 'Other-field':
              let tagsHtml = `<div class="c-txt u-mb"><label class="c-txt__label" for="select-demo">Select value</label><select class="c-txt__input c-txt__input--select" id="select-tag"><option disabled selected>Select value</option>`;
              tags.data.forEach((element) => {
                tagsHtml = tagsHtml.concat(
                  `<option vaue="${element.title}">${element.title}</option>`
                );
              });
              tagsHtml = tagsHtml.concat(`</select></div>`);
              if (!verification) {
                $(`#request_custom_fields_${fieldId}_label`).after(tagsHtml);
              }
              $('#select-tag').change(function (event) {
                fieldModifierValue = [];
                if (
                  $(`.request_custom_fields_${fieldId}`).find('textarea')
                    .length > 0
                ) {
                  $(`.request_custom_fields_${fieldId}`)
                    .find('textarea')
                    .val(event.target.value);
                }
                if (
                  $(`.request_custom_fields_${fieldId}`).find('input').length >
                  0
                ) {
                  $(`.request_custom_fields_${fieldId}`)
                    .find('input')
                    .val(event.target.value);
                }
                $(`#request_custom_fields_${fieldId}`).trigger('change');
                if (!verification) {
                  tags.data.forEach((element) => {
                    if (element.title === event.target.value) {
                      fieldModifierValue.push({
                        'End-user title': `You can order parts for this product in <a href="${element.data.part_url}">our webshop</a>.`,
                        Description: '{p}',
                        tag: element.tag,
                        section: element.data.section_id.toString(),
                      });
                    }
                  });
                }
                // use formFieldModifier value to sugest article
                if (externalGuideLookupEnabled) {
                  suggestFormFieldModifierArticle(
                    fieldId,
                    fieldModifierValue,
                    externalSearchObject
                  );
                }
              });
              break;
            case 'Drop-down':
              let area_control = $(`.request_custom_fields_${fieldId}`)
                .find('.nesty-input')
                .attr('aria-controls');
              let filteredTagNames = getFormFields(fieldId, availableTags, []);
              function observeNestyPanelForTags(area_control, availableTags, filteredTagNames) {
                const observer = new MutationObserver(function(mutations) {
                  mutations.forEach(function(mutation) {
                    if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
                      mutation.addedNodes.forEach(function(node) {
                        if (node.nodeType === Node.ELEMENT_NODE) {
                          const $panel = $(node).closest('.nesty-panel');
                          if ($panel.length > 0 && $panel.attr('id') === area_control) {
                            
                            $panel.find('li').each(function (params) {
                              if (
                                !$(this).hasClass('nesty-expand') &&
                                !$(this).hasClass('nesty-collapse')
                              ) {
                                if (!availableTags.includes($(this).attr('id'))) {
                                  $(this).addClass('shouldBeRemoved');
                                  $(this).hide();
                                }
                              } else {
                                filteredTagNames
                                  .then((result) => {
                                    let tagName = $(this).html();
                                    if (
                                      result.excludeAbleTagNames &&
                                      result.excludeAbleTagNames.length > 0
                                    ) {
                                      if (
                                        result.excludeAbleTagNames.includes(tagName) &&
                                        !result.includeAbleTagNames.includes(tagName)
                                      ) {
                                        $(this).hide();
                                      }
                                    }
                                    if (
                                      result.includeAbleTagNames &&
                                      result.includeAbleTagNames.length > 0
                                    ) {
                                      if (!result.includeAbleTagNames.includes(tagName)) {
                                        $(this).hide();
                                      }
                                    }
                                  })
                                  .catch((err) => { });
                              }
                            });
                          }
                        }
                      });
                    }
                  });
                });

                // Start observing
                const targetElement = document.body;
                observer.observe(targetElement, {
                  childList: true,
                  subtree: true
                });
                
                return observer;
              }

              // Call the observer function
              observeNestyPanelForTags(area_control, availableTags, filteredTagNames);
              $(`#request_custom_fields_${fieldId}`).on(
                'change',
                function (event) {
                  fieldModifierValue = [];
                  if (!verification) {
                    tags.data.forEach((element) => {
                      if (element.tag === event.target.value) {
                        fieldModifierValue.push({
                          'End-user title': `You can order parts for this product in <a href="${element.data.part_url}">our webshop</a>.`,
                          Description: '{p}',
                          tag: element.tag,
                          section: element.data.section_id.toString(),
                        });
                      }
                    });
                  }
                  // use formFieldModifier value to sugest article
                  if (externalGuideLookupEnabled) {
                    suggestFormFieldModifierArticle(
                      fieldId,
                      fieldModifierValue,
                      externalSearchObject
                    );
                  }
                }
              );
              break;
            case 'Multi-select':
              $(`#request_custom_fields_${fieldId}`)
                .parent()
                .find('.hc-multiselect-menu ul li')
                .each(function () {
                  let multiSelectValue = $(this).find('input').val();
                  if (!availableTags.includes(multiSelectValue)) {
                    $(this).addClass('shouldBeRemoved');
                    $(this).hide();
                  }
                });
              $(`#request_custom_fields_${fieldId}`)
                .parent()
                .find('.hc-multiselect-menu')
                .click(function () {
                  fieldModifierValue = [];
                  $(`#request_custom_fields_${fieldId}`)
                    .find('ul')
                    .find('li')
                    .each(function () {
                      let selectedTagValue = $(this).find('input').val();
                      if (!verification) {
                        tags.data.forEach((element) => {
                          if (element.tag === selectedTagValue) {
                            fieldModifierValue.push({
                              'End-user title': `You can order parts for this product in <a href="${element.data.part_url}">our webshop</a>.`,
                              Description: '{p}',
                              tag: element.tag,
                              section: element.data.section_id.toString(),
                            });
                          }
                        });
                      }
                    });
                  // use formFieldModifier value to sugest article
                  if (externalGuideLookupEnabled) {
                    suggestFormFieldModifierArticle(
                      fieldId,
                      fieldModifierValue,
                      externalSearchObject
                    );
                  }
                });
              $(`#request_custom_fields_${fieldId}`).click(function () {
                fieldModifierValue = [];
                $(`#request_custom_fields_${fieldId}`)
                  .find('ul')
                  .find('li')
                  .each(function () {
                    let selectedTagValue = $(this).find('input').val();
                    if (!verification) {
                      tags.data.forEach((element) => {
                        if (element.tag === selectedTagValue) {
                          fieldModifierValue.push({
                            'End-user title': `You can order parts for this product in <a href="${element.data.part_url}">our webshop</a>.`,
                            Description: '{p}',
                            tag: element.tag,
                            section: element.data.section_id.toString(),
                          });
                        }
                      });
                    }
                  });
                // use formFieldModifier value to sugest article
                if (externalGuideLookupEnabled) {
                  suggestFormFieldModifierArticle(
                    fieldId,
                    fieldModifierValue,
                    externalSearchObject
                  );
                }
              });
              break;
          }
          if (verification) {
            $(`#request_custom_fields_${fieldId}`).change(function () {
              let selectedValue = $(this).val();
              if (
                !availableTitle.includes(selectedValue) &&
                selectedValue !== ''
              ) {
                let warning = `<div role="alert" data-garden-id="forms.input_message" data-garden-version="8.35.0" class="warning-message" style="display: inline-block;position: relative;vertical-align: middle;line-height: 1.33333;font-size: 12px;color: rgb(173, 89, 24);margin-top: 8px;padding: 10p;"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" focusable="false" role="presentation" data-garden-id="forms.input_message_icon" data-garden-version="8.35.0" class="sc-cHGsZl bdFJgB"><path fill="none" stroke="currentColor" stroke-linecap="round" d="M.88 13.77L7.06 1.86c.19-.36.7-.36.89 0l6.18 11.91c.17.33-.07.73-.44.73H1.32c-.37 0-.61-.4-.44-.73zM7.5 6v3.5"></path><circle cx="7.5" cy="12" r="1" fill="currentColor"></circle></svg><span style="margin-left:5px">Value could be incorrect.</span></div>`;
                if ($(this).parent().find('.warning-message').length <= 0) {
                  $(this).parent().append(warning);
                  $(this).css('border', '1px solid rgb(237, 143, 28)');
                }
                manageSubmit('field_modifier', false);
              } else {
                $(this).parent().find('.warning-message').remove();
                $(this).css('border', '');
                manageSubmit('field_modifier', true);
              }
            });
          }
        });
      }
    } else if (command === 'field_verification' && parameters['id']) {
      let fieldId = parameters['id'];
      let verificationUrl = parameters['url'] ? parameters['url'] : null;
      let verification =
        parameters['verification'] != undefined && verificationUrl
          ? true
          : false;
      $this.parent().hide();
      $(`#request_custom_fields_${fieldId}`).change(function () {
        let $selectedFied = $(this);
        let selectedValue = $(this).val();
        if (verificationUrl.includes('$$VARIABLE$$') && selectedValue != '') {
          let newVerificationUrl = verificationUrl.replace(
            '$$VARIABLE$$',
            selectedValue
          );
          $.get(newVerificationUrl, function (response, status) {
            if (response && !response.valid) {
              if (verification) {
                let warning = `<div role="alert" data-garden-id="forms.input_message" data-garden-version="8.35.0" class="warning-message" style="display: inline-block;position: relative;vertical-align: middle;line-height: 1.33333;font-size: 12px;color: rgb(173, 89, 24);margin-top: 8px;padding: 10p;"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" focusable="false" role="presentation" data-garden-id="forms.input_message_icon" data-garden-version="8.35.0" class="sc-cHGsZl bdFJgB"><path fill="none" stroke="currentColor" stroke-linecap="round" d="M.88 13.77L7.06 1.86c.19-.36.7-.36.89 0l6.18 11.91c.17.33-.07.73-.44.73H1.32c-.37 0-.61-.4-.44-.73zM7.5 6v3.5"></path><circle cx="7.5" cy="12" r="1" fill="currentColor"></circle></svg><span style="margin-left:5px">Value could be incorrect.</span></div>`;
                if (
                  $selectedFied.parent().find('.warning-message').length <= 0
                ) {
                  $selectedFied.parent().append(warning);
                  $selectedFied.css('border', '1px solid rgb(237, 143, 28)');
                }
              }
              manageSubmit('field_verification', false);
            } else {
              if (verification) {
                $selectedFied.parent().find('.warning-message').remove();
                $selectedFied.css('border', '');
              }
              manageSubmit('field_verification', true);
            }
          });
        } else {
          $selectedFied.parent().find('.warning-message').remove();
          $selectedFied.css('border', '');
          manageSubmit('field_verification', true);
        }
      });
    } else if (command === 'valid_regex' && parameters['id']) {
      let fieldId = parameters['id'];
      let expression = parameters['expression'];
      let flags = parameters['flags'] ? parameters['flags'] : null;
      let verification = parameters['message'] ? true : false;

      $this.parent().hide();
      let regExp = new RegExp(expression, flags);
      $(`#request_custom_fields_${fieldId}`).change(function () {
        let $selectedFied = $(this);
        let selectedValue = $(this).val();
        if (selectedValue != '') {
          if (!regExp.test(selectedValue)) {
            if (verification) {
              let warning = `<div role="alert" data-garden-id="forms.input_message" data-garden-version="8.35.0" class="warning-message" style="display: inline-block;position: relative;vertical-align: middle;line-height: 1.33333;font-size: 12px;color: rgb(173, 89, 24);margin-top: 8px;padding: 10p;"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" focusable="false" role="presentation" data-garden-id="forms.input_message_icon" data-garden-version="8.35.0" class="sc-cHGsZl bdFJgB"><path fill="none" stroke="currentColor" stroke-linecap="round" d="M.88 13.77L7.06 1.86c.19-.36.7-.36.89 0l6.18 11.91c.17.33-.07.73-.44.73H1.32c-.37 0-.61-.4-.44-.73zM7.5 6v3.5"></path><circle cx="7.5" cy="12" r="1" fill="currentColor"></circle></svg><span style="margin-left:5px">${parameters['message']}</span></div>`;
              if ($selectedFied.parent().find('.warning-message').length <= 0) {
                $selectedFied.parent().append(warning);
                $selectedFied.css('border', '1px solid rgb(237, 143, 28)');
              }
            }
            manageSubmit('valid_regex', false);
          } else {
            if (verification) {
              $selectedFied.parent().find('.warning-message').remove();
              $selectedFied.css('border', '');
            }
            manageSubmit('valid_regex', true);
          }
        } else {
          $selectedFied.parent().find('.warning-message').remove();
          $selectedFied.css('border', '');
          manageSubmit('valid_regex', true);
        }
      });
    } else if (command == 'guide_lookup') {
      $this.parent().hide();
      let fieldId = parameters['id'];
      let searchObject = {};
      let incomingLabels = '';
      if (parameters['brand_id']) {
        searchObject['brand_id'] = parameters['brand_id'];
      }
      if (parameters['category']) {
        searchObject['category'] = parameters['category'];
      }
      if (parameters['created_after']) {
        searchObject['created_after'] = parameters['created_after'];
      }
      if (parameters['label_names']) {
        searchObject['label_names'] = parameters['label_names'];
        incomingLabels = parameters['label_names'];
      }
      if (parameters['locale']) {
        searchObject['locale'] = parameters['locale'];
      }
      if (parameters['multibrand']) {
        searchObject['multibrand'] = parameters['multibrand'];
      }
      if (parameters['section']) {
        searchObject['section'] = parameters['section'];
      }
      if (parameters['sort_by']) {
        searchObject['sort_by'] = parameters['sort_by'];
      }
      if (parameters['sort_order']) {
        searchObject['sort_order'] = parameters['sort_order'];
      }
      if (parameters['created_at']) {
        searchObject['created_at'] = parameters['created_at'];
      }
      if (parameters['updated_after']) {
        searchObject['updated_after'] = parameters['updated_after'];
      }
      if (parameters['updated_at']) {
        searchObject['updated_at'] = parameters['updated_at'];
      }
      if (parameters['updated_before']) {
        searchObject['updated_before'] = parameters['updated_before'];
      }
      if (parameters['external'] && parameters['external'] === 'true') {
        externalGuideLookupEnabled = true;
        externalSearchObject = searchObject;
      }

      let fieldType = checFieldType(fieldId);
      if (
        $(`.request_custom_fields_${fieldId}`).find('.suggested-article')
          .length === 0
      ) {
        $(`.request_custom_fields_${fieldId}`).append(
          '<div class="suggested-article" style="display:none;"><p>Suggested articles</p><ul></ul></div>'
        );
      }
      switch (fieldType) {
        case 'Other-field':
          let timer = '';
          if (
            $(`.request_custom_fields_${fieldId}`).find('textarea').length > 0
          ) {
            $(`.request_custom_fields_${fieldId}`)
              .find('textarea')
              .on('change keyup paste', function (event) {
                let $this = $(this);
                clearTimeout(timer);
                if ($this.val() === '') {
                  $('.suggested-article').hide();
                  $('.suggested-article').find('ul').html('');
                  return;
                }
                timer = setTimeout(function () {
                  searchObject['query'] = $this.val();
                  suggestArticle(fieldId, searchObject);
                }, 1000);
              });
          }
          if ($(`.request_custom_fields_${fieldId}`).find('input').length > 0) {
            $(`.request_custom_fields_${fieldId}`)
              .find('input')
              .on('change keyup paste', function (event) {
                let $this = $(this);
                clearTimeout(timer);
                if ($this.val() === '') {
                  $(`.request_custom_fields_${fieldId}`)
                    .find('.suggested-article')
                    .hide();
                  $(`.request_custom_fields_${fieldId}`)
                    .find('.suggested-article')
                    .find('ul')
                    .html('');
                  return;
                }
                timer = setTimeout(function () {
                  searchObject['query'] = $this.val();
                  suggestArticle(fieldId, searchObject);
                }, 1000);
              });
          }
          break;

        case 'Multi-select':
          let selectedTagValue;
          $(`#request_custom_fields_${fieldId}`)
            .parent()
            .find('.hc-multiselect-menu')
            .click(function () {
              selectedTagValue = '';
              $(`#request_custom_fields_${fieldId}`)
                .find('ul')
                .find('li')
                .each(function () {
                  if (selectedTagValue === '') {
                    selectedTagValue = `${fieldId}_${$(this)
                      .find('input')
                      .val()}`;
                  } else {
                    selectedTagValue = selectedTagValue.concat(
                      `,${fieldId}_${$(this).find('input').val()}`
                    );
                  }
                });
              searchObject['query'] = '';
              if (incomingLabels && incomingLabels !== '') {
                searchObject['label_names'] = '';
                let newLabels = incomingLabels.concat(`,${selectedTagValue}`);
                searchObject['label_names'] = newLabels;
              } else {
                searchObject['label_names'] = '';
                searchObject['label_names'] = selectedTagValue;
              }
              if (searchObject['label_names'] !== '') {
                suggestArticle(fieldId, searchObject);
              } else {
                $(`.request_custom_fields_${fieldId}`)
                  .find('.suggested-article')
                  .hide();
                $(`.request_custom_fields_${fieldId}`)
                  .find('.suggested-article')
                  .find('ul')
                  .html('');
              }
            });
          $(`#request_custom_fields_${fieldId}`).click(function () {
            selectedTagValue = '';
            $(`#request_custom_fields_${fieldId}`)
              .find('ul')
              .find('li')
              .each(function () {
                if (selectedTagValue === '') {
                  selectedTagValue = `${fieldId}_${$(this)
                    .find('input')
                    .val()}`;
                } else {
                  selectedTagValue = selectedTagValue.concat(
                    `,${fieldId}_${$(this).find('input').val()}`
                  );
                }
              });
            searchObject['query'] = '';
            if (incomingLabels && incomingLabels !== '') {
              searchObject['label_names'] = '';
              let newLabels = incomingLabels.concat(`,${selectedTagValue}`);
              searchObject['label_names'] = newLabels;
            } else {
              searchObject['label_names'] = '';
              searchObject['label_names'] = selectedTagValue;
            }
            if (searchObject['label_names'] !== '') {
              suggestArticle(fieldId, searchObject);
            } else {
              $(`.request_custom_fields_${fieldId}`)
                .find('.suggested-article')
                .hide();
              $(`.request_custom_fields_${fieldId}`)
                .find('.suggested-article')
                .find('ul')
                .html('');
            }
          });
          break;
        case 'Drop-down':
          let selectedDropdownTag;
          $(`#request_custom_fields_${fieldId}`).on('change', function (event) {
            selectedDropdownTag = event.target.value;
            searchObject['query'] = '';
            if (incomingLabels && incomingLabels !== '') {
              searchObject['label_names'] = '';
              let newLabels = incomingLabels.concat(
                `,${fieldId}_${selectedDropdownTag}`
              );
              searchObject['label_names'] = newLabels;
            } else {
              searchObject['label_names'] = '';
              searchObject['label_names'] = `${fieldId}_${selectedDropdownTag}`;
            }
            if (searchObject['label_names'] !== '') {
              suggestArticle(fieldId, searchObject);
            } else {
              $(`.request_custom_fields_${fieldId}`)
                .find('.suggested-article')
                .hide();
              $(`.request_custom_fields_${fieldId}`)
                .find('.suggested-article')
                .find('ul')
                .html('');
            }
          });
          break;
      }
    } else if (command === 'address') {
      // setting default column
      let col = '12';
      let form_field_id = $this
        .parent()
        .find('input[type="checkbox"]')
        .attr('id');
      if (
        parameters['address1'] != undefined &&
        $('#new_request').find(
          `.request_custom_fields_${parameters['address1']}`
        ).length > 0
      ) {
        $this.parent().find('input').attr('style', 'display:none');
        $this.parent().find('label').hide();
        $this.hide();
        $this
          .parent()
          .append(
            `<div id="address_${form_field_id}" style="background-color: rgba(206, 226, 242, 0.35); padding:10px; border-radious:10px;" class="address u-mt-lg"></div>`
          );
        // if (parameters['title'] != undefined) {
        //   $(`#address_${form_field_id}`).append(
        //     `<h4>${parameters['title']}</h4>`
        //   );
        // }
        // address 1
        let address1 = $('#new_request')
          .find(`.request_custom_fields_${parameters['address1']}`)
          .clone();
        $('#new_request')
          .find(`.request_custom_fields_${parameters['address1']}`)
          .remove();
        address1.addClass('collective-form-field');
        address1
          .find(`#request_custom_fields_${parameters['address1']}`)
          .attr('data-for', 'address1');
        $(`#address_${form_field_id}`).append(address1);
        if (parameters['address1_label'] != undefined) {
          $(`#address_${form_field_id}`)
            .find(`#request_custom_fields_${parameters['address1']}_label`)
            .html(parameters['address1_label']);
        }
      } else {
        $this.parent().hide();
      }
      // address 2
      if (
        parameters['address2'] != undefined &&
        $('#new_request').find(
          `.request_custom_fields_${parameters['address2']}`
        ).length > 0
      ) {
        let address2 = $('#new_request')
          .find(`.request_custom_fields_${parameters['address2']}`)
          .clone();
        $('#new_request')
          .find(`.request_custom_fields_${parameters['address2']}`)
          .remove();
        address2.addClass('collective-form-field');
        address2
          .find(`#request_custom_fields_${parameters['address2']}`)
          .attr('data-for', 'address2');
        $(`#address_${form_field_id}`).append(address2);
        if (parameters['address2_label'] != undefined) {
          $(`#address_${form_field_id}`)
            .find(`#request_custom_fields_${parameters['address2']}_label`)
            .html(parameters['address2_label']);
        }
      }
      // zip and state width adjustment
      if (
        (parameters['zip'] != undefined &&
          $('#new_request').find(`.request_custom_fields_${parameters['zip']}`)
            .length > 0) ||
        (parameters['state'] != undefined &&
          $('#new_request').find(
            `.request_custom_fields_${parameters['state']}`
          ).length > 0)
      ) {
        $(`#address_${form_field_id}`).append(
          `<div id="zip_state" class="row"><div id="zip" class="u-mt-lg"></div><div id="state" class="u-mt-lg"></div></div>`
        );
        // set col 6 if both present
        parameters['zip'] != undefined &&
          $('#new_request').find(`.request_custom_fields_${parameters['zip']}`)
            .length > 0 &&
          parameters['state'] != undefined &&
          $('#new_request').find(`.request_custom_fields_${parameters['state']}`)
            .length > 0
          ? (col = 6)
          : (col = 12);
        if (
          parameters['zip'] != undefined &&
          $('#new_request').find(`.request_custom_fields_${parameters['zip']}`)
            .length > 0
        ) {
          let zip = $('#new_request')
            .find(`.request_custom_fields_${parameters['zip']}`)
            .clone();
          zip.addClass('collective-form-field');
          zip
            .find(`#request_custom_fields_${parameters['zip']}`)
            .attr('data-for', 'zip');
          $('#new_request')
            .find(`.request_custom_fields_${parameters['zip']}`)
            .remove();
          $(`#address_${form_field_id}`)
            .find('#zip_state')
            .find('#zip')
            .addClass(`col-md-${col}`);
          $(`#address_${form_field_id}`)
            .find('#zip_state')
            .find('#zip')
            .append(zip);
          if (parameters['zip_label'] != undefined) {
            $(`#address_${form_field_id}`)
              .find(`#request_custom_fields_${parameters['zip']}_label`)
              .html(parameters['zip_label']);
          }
        }
        if (
          parameters['state'] != undefined &&
          $('#new_request').find(
            `.request_custom_fields_${parameters['state']}`
          ).length > 0
        ) {
          let state = $('#new_request')
            .find(`.request_custom_fields_${parameters['state']}`)
            .clone();
          state.addClass('collective-form-field');
          state
            .find(`#request_custom_fields_${parameters['state']}`)
            .attr('data-for', 'state');
          $('#new_request')
            .find(`.request_custom_fields_${parameters['state']}`)
            .remove();
          $(`#address_${form_field_id}`)
            .find('#zip_state')
            .find('#state')
            .addClass(`col-md-${col}`);
          $(`#address_${form_field_id}`)
            .find('#zip_state')
            .find('#state')
            .append(state);
          if (parameters['state_label'] != undefined) {
            $(`#address_${form_field_id}`)
              .find(`#request_custom_fields_${parameters['state']}_label`)
              .html(parameters['state_label']);
          }
        }
      }

      // city and country width adjustment
      if (
        (parameters['city'] != undefined &&
          $('#new_request').find(`.request_custom_fields_${parameters['city']}`)
            .length > 0) ||
        (parameters['country'] != undefined &&
          $('#new_request').find(
            `.request_custom_fields_${parameters['country']}`
          ).length > 0)
      ) {
        $(`#address_${form_field_id}`).append(
          `<div id="city_country" class="row"><div id="city" class="u-mt-lg"></div><div id="country" class="u-mt-lg"></div></div>`
        );

        // set col 6 if both present
        parameters['city'] != undefined &&
          $('#new_request').find(`.request_custom_fields_${parameters['city']}`)
            .length > 0 &&
          parameters['country'] != undefined &&
          $('#new_request').find(
            `.request_custom_fields_${parameters['country']}`
          ).length > 0
          ? (col = 6)
          : (col = 12);
        if (
          parameters['city'] != undefined &&
          $('#new_request').find(`.request_custom_fields_${parameters['city']}`)
            .length > 0
        ) {
          let city = $('#new_request')
            .find(`.request_custom_fields_${parameters['city']}`)
            .clone();
          city.addClass('collective-form-field');
          city
            .find(`#request_custom_fields_${parameters['city']}`)
            .attr('data-for', 'city');
          $('#new_request')
            .find(`.request_custom_fields_${parameters['city']}`)
            .remove();
          $(`#address_${form_field_id}`)
            .find('#city_country')
            .find('#city')
            .addClass(`col-md-${col}`);
          $(`#address_${form_field_id}`)
            .find('#city_country')
            .find('#city')
            .append(city);
          if (parameters['city_label'] != undefined) {
            $(`#address_${form_field_id}`)
              .find(`#request_custom_fields_${parameters['city']}_label`)
              .html(parameters['city_label']);
          }
        }

        if (
          parameters['country'] != undefined &&
          $('#new_request').find(
            `.request_custom_fields_${parameters['country']}`
          ).length > 0
        ) {
          let country = $('#new_request')
            .find(`.request_custom_fields_${parameters['country']}`)
            .clone();
          country.addClass('collective-form-field');
          country
            .find(`#request_custom_fields_${parameters['country']}`)
            .attr('data-for', 'country');
          $('#new_request')
            .find(`.request_custom_fields_${parameters['country']}`)
            .remove();
          $(`#address_${form_field_id}`)
            .find('#city_country')
            .find('#country')
            .addClass(`col-md-${col}`);
          $(`#address_${form_field_id}`)
            .find('#city_country')
            .find('#country')
            .append(country);
          if (parameters['country_label'] != undefined) {
            $(`#address_${form_field_id}`)
              .find(`#request_custom_fields_${parameters['country']}_label`)
              .html(parameters['country_label']);
          }
          if (
            $(`#request_custom_fields_${parameters['country']}`).length > 0 &&
            $(`#request_custom_fields_${parameters['country']}`).attr(
              'type'
            ) === 'text'
          ) {
            country.css('display', 'none');
            let countrySelectList = `
              <div id="country-select" class="form-field u-mb-lg u-position-relative collective-form-field">
                <div class="c-txt">
                    <label>Country</label>
                    <div class="c-txt__input c-txt__input--select selected-value ${parameters['country']}_select" contenteditable="false">-</div>
                </div>
                <div class="menu-container u-1/1">
                    <ul class="c-menu c-menu--down" id="${parameters['country']}_country_menu" style="max-height: 400px;margin: 0;overflow: auto;padding: 0;width: 100%;background: #FFF !important;z-index: 2;display: none;">
                      <li class="c-menu__item" data-value="" disabled="true">-</li>
                    </ul>
                </div>
              </div>`;
            $(`#address_${form_field_id}`)
              .find('#city_country')
              .find('#country')
              .prepend(countrySelectList);

            countriesList.forEach((country) => {
              $(`#${parameters['country']}_country_menu`).append(
                `<li class="c-menu__item ${parameters['country']}_item ${parameters['default_country'] === country.code
                  ? 'default_country'
                  : ''
                }" data-value='${JSON.stringify(country)}' data-name="${country.name
                }">${country.name}</li>`
              );
            });
            $(document).on(
              'click',
              `.${parameters['country']}_select`,
              function (event) {
                if ($(this).parent().parent().find('.c-menu').is(':visible')) {
                  $(this).parent().parent().find('.c-menu').hide();
                } else {
                  $(this).parent().parent().find('.c-menu').show();
                }
              }
            );
            $(document).on(
              'click',
              `.${parameters['country']}_item`,
              function (event) {
                const selectedValue = JSON.parse($(this).attr('data-value'));
                const selectedText = $(this).text();
                $(this).parent().parent().find('.c-menu').hide();
                $(this)
                  .parent()
                  .parent()
                  .parent()
                  .find('.selected-value')
                  .html(selectedText);
                $(this).parent().find('.is-checked').removeClass('is-checked');
                $(this).addClass('is-checked');
                $(`#request_custom_fields_${parameters['country']}`).val(
                  selectedValue.name
                );
                $(`#request_custom_fields_${parameters['country']}`).trigger(
                  'change'
                );
                if (parameters['country_iso'] != undefined) {
                  $(`#request_custom_fields_${parameters['country_iso']}`).val(
                    selectedValue.code
                  );
                  $(
                    `#request_custom_fields_${parameters['country_iso']}`
                  ).trigger('change');
                }
              }
            );
          }

          $(`.${parameters['country']}_item.default_country`).trigger('click');
        }
      }
      // country iso
      if (
        parameters['country_iso'] != undefined &&
        $('#new_request').find(
          `.request_custom_fields_${parameters['country_iso']}`
        ).length > 0
      ) {
        let country_iso = $('#new_request')
          .find(`.request_custom_fields_${parameters['country_iso']}`)
          .clone();
        country_iso.addClass('collective-form-field');
        country_iso
          .find(`#request_custom_fields_${parameters['country_iso']}`)
          .attr('data-for', 'country_iso');
        $('#new_request')
          .find(`.request_custom_fields_${parameters['country_iso']}`)
          .remove();
        $(`#address_${form_field_id}`).append(country_iso);

        if (
          $(`#request_custom_fields_${parameters['country_iso']}`).attr(
            'type'
          ) === 'text'
        ) {
          country_iso.hide();
        }
      }
      // copy address field
      if (
        parameters['copy'] != undefined &&
        parameters['copy_label'] != undefined &&
        $('#new_request').find(`.request_custom_fields_${parameters['copy']}`)
          .length > 0
      ) {
        let copyOnCheck = true;
        if (
          parameters['copy_action'] != undefined &&
          parameters['copy_action'] === 'uncheck'
        ) {
          copyOnCheck = false;
        }

        let checkBoxState = false;
        if (parameters['checked'] != undefined) {
          checkBoxState = true;
        }

        function addCopyClass() {
          $(`.request_custom_fields_${parameters['copy']}`)
            .find('.address')
            .find('input')
            .each(function () {
              $(this).addClass('copy_sources');
            });
          $(`.${form_field_id}`).addClass('copy_destination');
        }

        $(
          `<div><input aria-required="false" type="checkbox" data-value=${parameters['copy']
          } id="copy_address_${form_field_id}" ${checkBoxState ? 'checked' : ''
          }><label for="copy_address_${form_field_id}" style="font-size: 13px;margin-top: -21px;margin-left: 21px;">${parameters['copy_label']
          }</label></div>`
        ).insertBefore(`#address_${form_field_id}`);
        if (checkBoxState) {
          if (copyOnCheck) {
            addCopyClass();
            $(`#address_${form_field_id}`).hide();
          } else {
            $(`#address_${form_field_id}`).show();
          }
        } else {
          if (copyOnCheck) {
            $(`#address_${form_field_id}`).show();
          } else {
            addCopyClass();
            $(`#address_${form_field_id}`).hide();
          }
        }
        $(`#copy_address_${form_field_id}`).click(function () {
          let sourceAddressField = $(this).attr('data-value');
          if ($(this).is(':checked')) {
            if (copyOnCheck) {
              $(this).parent().parent().addClass('copy_destination');
              $(`.request_custom_fields_${sourceAddressField}`)
                .find('input')
                .each(function () {
                  $(this).addClass('copy_sources');
                  $(this).trigger('change');
                });
              $(this).parent().parent().find('.address').hide();
            } else {
              $(this).parent().parent().find('.address').show();
              $(this).parent().parent().removeClass('copy_destination');
              $(`.request_custom_fields_${sourceAddressField}`)
                .find('input')
                .each(function () {
                  $(this).removeClass('copy_sources');
                });
            }
          } else {
            if (copyOnCheck) {
              $(this).parent().parent().find('.address').show();
              $(this).parent().parent().removeClass('copy_destination');
              $(`.request_custom_fields_${sourceAddressField}`)
                .find('input')
                .each(function () {
                  $(this).removeClass('copy_sources');
                });
            } else {
              $(this).parent().parent().addClass('copy_destination');
              $(`.request_custom_fields_${sourceAddressField}`)
                .find('input')
                .each(function () {
                  $(this).addClass('copy_sources');
                  $(this).trigger('change');
                });
              $(this).parent().parent().find('.address').hide();
            }
          }
        });
        $(document).on('change', '.copy_sources', function () {
          let dataFor = $(this).attr('data-for');
          let value = $(this).val();
          $('.copy_destination')
            .find(`input[data-for="${dataFor}"]`)
            .val(value);
          $('.copy_destination')
            .find(`input[data-for="${dataFor}"]`)
            .trigger('change');
        });
      }
      // Auto complete management
      if (
        parameters['autocomplete'] &&
        parameters['autocomplete'] != undefined &&
        parameters['address1'] != undefined &&
        $('#new_request').find(
          `.request_custom_fields_${parameters['address1']}`
        ).length > 0
      ) {
        addressArray.push(parameters);
        $(`#request_custom_fields_${parameters['address1']}`).addClass(
          'place_map_query'
        );
        placeApiKey = parameters['autocomplete'];
      }
      if ($this.parent().hasClass('required')) {
        $this.parent().find('input[type="text"]').addClass('required-field');
      }
      $this.parent().find('span.optional').remove();
    } else if (command === 'step') {
      stepCount = parseInt(stepCount) + 1;
      if (typeof parameters['type'] != 'undefined') {
        activeType = parameters['type'];
      }
      if (typeof parameters['title'] != 'undefined') {
        stepTitle = parameters['title'];
      } else {
        stepTitle = `Step ${stepCount}`;
      }
      if (
        typeof parameters['submit'] != 'undefined' &&
        parameters['submit'] === 'true'
      ) {
        form.find("input[type='submit']").prop('disabled', false);
        form.find("input[type='submit']").hide();
      }

      createStepButtons(
        parameters,
        $this.parent(),
        stepCount,
        stepTitle,
        activeType
      );
      $this.parent().hide();
      $this.parent().addClass('step');
    } else if (command == 'webwidget') {
      if (typeof zE == 'function') {
        if (typeof parameters['addTags'] != 'undefined') {
          zE('webWidget', 'chat:addTags', parameters['addTags'].split(','));
        }

        if (typeof parameters['removeTags'] != 'undefined') {
          zE(
            'webWidget',
            'chat:removeTags',
            parameters['removeTags'].split(',')
          );
        }

        if (typeof parameters['send'] != 'undefined') {
          zE('webWidget', 'chat:send', parameters['send']);
        }

        if (typeof parameters['updatePath'] != 'undefined') {
          zE('webWidget', 'updatePath', {
            url: parameters['updatePath'],
          });
        }

        if (typeof parameters['open'] != 'undefined') {
          zE('webWidget', 'open');
        }

        if (typeof parameters['setSuggestions'] != 'undefined') {
          try {
            var suggestionData = JSON.parse(parameters['setSuggestions']);
            if (suggestionData) {
              zE('webWidget', 'helpCenter:setSuggestions', suggestionData);
            }
          } catch (error) { }
        }
      }
      if (typeof parameters['hide_field'] != 'undefined') {
        $this.parent().hide();
      }
    } else if (command == 'case') {
      if (typeof parameters['chatDepartment'] != 'undefined') {
        if (typeof zE == 'function') {
          zE('webWidget', 'on', 'chat:status', function (status) {
            if (status.name == parameters['chatDepartment']) {
              performChatAction(parameters['commands'], status, $this);
            }
          });
        }
      }
      $this.parent().hide();
    } else if (command == 'radio') {
      var selectNode = $this.closest('.form-field').find('select');
      var inputNode = $this.closest('.form-field').find('input');

      if (selectNode.length > 0 || inputNode.length > 0) {
        var radioOptions = document.createElement('div');
        radioOptions.className = 'radio-options';
        var selectId = selectNode.attr('id');

        if (selectNode.length > 0) {
          selectNode.find('option').each(function (index) {
            var optionValue = $(this).attr('value');
            var optionText = $(this).html();

            if (optionValue != '-') {
              var isSelected = $(this).is(':selected') ? true : false;
              var radioWrap = getOptionWrap(
                selectId,
                index,
                optionValue,
                optionText,
                isSelected
              );
              radioOptions.appendChild(radioWrap);
            }
          });
        }

        if (inputNode.length > 0) {
          var selectedValue = inputNode.val();
          var selectValues = inputNode.data('tagger');
          var valueIndex;
          var selectId = inputNode.attr('id');

          if (selectValues) {
            for (
              valueIndex = 0;
              valueIndex < selectValues.length;
              valueIndex++
            ) {
              var optionValue = selectValues[valueIndex].value;
              var optionText = selectValues[valueIndex].label;

              if (optionValue != '') {
                var isSelected = optionValue == selectedValue ? true : false;
                var radioWrap = getOptionWrap(
                  selectId,
                  valueIndex,
                  optionValue,
                  optionText,
                  isSelected
                );
                radioOptions.appendChild(radioWrap);
              }
            }
          }
        }

        $this
          .closest('.form-field')
          .find('.nesty-input')
          .replaceWith(radioOptions);
      }
      $this.hide();
    } else if (command == 'field_group') {
      var extraClass = parameters['class'] ? parameters['class'] : '';
      var fieldClass = parameters['field_class']
        ? parameters['field_class']
        : null;

      var groupDiv = $('<div/>', {
        class: 'group-fields ' + extraClass,
      });
      try {
        var fieldsArray = JSON.parse(parameters['fields'].replace(/'/g, '"'));

        $this.closest('.form-field');

        var field;
        for (field of fieldsArray) {
          if (Array.isArray(field)) {
            var rowDiv = $('<div/>', {
              class: 'row',
            });

            var colClass = 'col-' + Math.floor(12 / field.length);
            var col;

            for (col of field) {
              var classPrefix = isNaN(col)
                ? '.request_'
                : '.request_custom_fields_';
              var sourceDiv = $(classPrefix + col);

              var colDiv = $('<div/>', {
                class: colClass,
              });

              sourceDiv.appendTo(colDiv);
              colDiv.appendTo(rowDiv);
            }

            if (fieldClass) {
              rowDiv.addClass(fieldClass);
            }
            rowDiv.appendTo(groupDiv);
          } else {
            var classPrefix = isNaN(field)
              ? '.request_'
              : '.request_custom_fields_';
            var sourceDiv = $(classPrefix + field);

            if (sourceDiv.length > 0) {
              if (fieldClass) {
                sourceDiv.addClass(fieldClass);
              }
              sourceDiv.appendTo(groupDiv);
            }
          }
        }
      } catch (error) { }
      $this.closest('.form-field').replaceWith(groupDiv);
    } else if (command == 'sidecheck') {
      var parentNode = $this.closest('.form-field');
      parentNode.addClass('side-checkbox');
      var labelNode = parentNode.find('label');
      labelNode.find('span').remove();
      labelNode.html(labelNode.text());
      labelNode.find('.infobox > span').hide();
      labelNode
        .find('.infobox > span')
        .prepend(
          '<div class="remove-sidecheck" style="position: absolute;top: 10px;right: 10px;left: initial;height: 25px;width: 25px;text-align: center;border-radius: 50%;cursor: pointer;color: rgb(42, 121, 193) !important;vertical-align: middle;"><img src="//theme.zdassets.com/theme_assets/2023731/33defba4f8d9236d49cb220df1614e2c5d90f0e1.svg" class="client-components-Editor-components-AssetViewer-index__image--2oZA9" alt="asset"></div>'
        );
      labelNode.css('display', 'inline-block');
      labelNode.appendTo(parentNode);
      formField.prepend(prependLabel);
      $this.remove();
      $(document).on('click', '.infobox a', function (event) {
        let $this = $(this);
        setTimeout(() => {
          event.preventDefault();
          if ($this.parent().find('span').is(':visible')) {
            $('a.active-info').removeClass('active-info');
            $this.addClass('active-info');
            $('.infobox').each(function () {
              if (!$(this).find('a').hasClass('active-info')) {
                $(this).find('span').hide();
              }
            });
          } else {
            $this.removeClass('active-info');
          }
        }, 10);
      });
      $(document).on('click', '.remove-sidecheck', function (event) {
        event.preventDefault();
        let $this = $(this);
        $this.closest('span').hide();
        $this.closest('span.infobox').find('a').removeClass('active-info');
      });
    } else if (command == 'split_field') {
      if (parameters['field_names']) {
        var hintId = $this.attr('id');
        var parentNode = $this.closest('.form-field');
        var inputNode = parentNode.find('input');
        var inputId = inputNode.attr('id');

        var fieldNames = parameters['field_names'].split(',');

        var rowDiv = $('<div/>', {
          class: 'row',
        });

        var colClass = 'split-single col-' + Math.floor(12 / fieldNames.length);

        var fieldCount = 0;

        while (fieldCount < fieldNames.length) {
          var colDiv = $('<div/>', {
            class: colClass + ' split-' + inputId,
            id: 'split-' + inputId + '-' + fieldCount,
          });
          let fieldName = fieldNames[fieldCount];

          if (!isNaN(fieldName)) {
            let inputDiv = $('#new_request')
              .find(`.request_custom_fields_${fieldName}`)
              .clone();
            $('#new_request')
              .find(`.request_custom_fields_${fieldName}`)
              .remove();
            inputDiv.appendTo(colDiv);
          } else {
            var labelDiv = $('<label/>').text(fieldNames[fieldCount]);

            labelDiv.appendTo(colDiv);

            var inputField = $('<input/>')
              .attr('type', 'text')
              .addClass('split-input inputs-' + inputId)
              .attr('id', inputId + '-' + fieldCount);

            inputField.appendTo(colDiv);
          }

          colDiv.appendTo(rowDiv);

          fieldCount++;
        }
        $(`#${inputId}`).closest('.form-field ').find('label').hide();
        $(`#${inputId}`).closest('.form-field ').append(rowDiv);
        $(`#${inputId}`).prepend(prependLabel);
        $(document).on(
          'change',
          'input[id^=' + inputId + ']',
          function (event) {
            var newValue = '';
            $('.inputs-' + inputId).each(function () {
              var fieldValue = $(this).val();
              if (fieldValue.trim() != '') {
                if (newValue != '') {
                  newValue += ' ';
                }
                newValue += fieldValue.trim();
              }
            });
            if ($(event.target).hasClass('split-input')) {
              $('#' + inputId).val(newValue);
              $('#' + inputId).trigger('change');
            }
          }
        );
        $(`#${hintId}`).hide();
        $(`#${inputId}`).hide();
      }
    } else if (command == 'time') {
      var parentNode = $this.closest('.form-field');
      var inputField = parentNode.find('input[type=text]');
      inputField.attr('type', 'time');

      if (parameters['value']) {
        inputField.val(parameters['value']);
      }

      if (parameters['min']) {
        inputField.attr('min', parameters['min']);
      }

      if (parameters['max']) {
        inputField.attr('max', parameters['max']);
      }

      if (parameters['format']) {
        inputField.attr('data-format', parameters['format']);
      }

      if (parameters['dynamic']) {
        inputField.attr('data-dynamic', parameters['dynamic']);
      }

      if (parameters['step']) {
        inputField.attr('step', parameters['step']);
      }

      if (typeof parameters['timepicker'] != 'undefined') {
        inputField.addClass('timepicker');
        hasTime = true;
      }

      if (parameters['pattern']) {
        inputField.attr('pattern', parameters['pattern']);
      } else {
        inputField.attr('pattern', '[0-9]{2}:[0-9]{2}');
      }

      $this.remove();
    } else if (command == 'slider') {
      var parentNode = $this.closest('.form-field');
      var inputField = parentNode.find('input');
      var inputId = inputField.attr('id');
      var prependText = '';
      var appendText = '';

      inputField.attr('type', 'range');

      if (parameters['prepend']) {
        prependText = parameters['prepend'] + ' ';
        inputField.data('prepend', parameters['prepend']);
      }

      if (parameters['append']) {
        appendText = ' ' + parameters['append'];
        inputField.data('append', parameters['append']);
      }

      if (parameters['step']) {
        inputField.attr('step', parameters['step']);
      }

      if (parameters['value']) {
        inputField.val(parameters['value']);
      }

      if (parameters['min']) {
        inputField.attr('min', parameters['min']);
      }

      if (parameters['max']) {
        inputField.attr('max', parameters['max']);
      }

      if (parameters['orient']) {
        inputField.attr('orient', parameters['step']);
      }

      var listItem, listSingle, listItemValue, listItemLabel;
      if (parameters['list']) {
        try {
          var sliderDataList = JSON.parse(
            parameters['list'].replace(/'/g, '"')
          );
          var listWrap = $('<datalist />');
          listWrap.attr('id', inputId + '-datalist');
          for (listItem of sliderDataList) {
            if (typeof listItem == 'object') {
              listItemValue = listItem[0];
              listItemLabel = listItem[1];
            } else {
              listItemValue = listItemLabel = listItem;
              listItemLabel = prependText + listItemLabel + appendText;
            }
            listSingle = $('<option />')
              .attr('value', listItemValue)
              .attr('label', listItemLabel);
            listSingle.appendTo(listWrap);
          }
          listWrap.appendTo(parentNode);
          inputField.attr('list', inputId + '-datalist');
        } catch (error) {
          console.error(error);
        }
      } else if (
        parameters['min'] &&
        parameters['max'] &&
        parameters['scale']
      ) {
        var sliderStep = parameters['step'] ? parseInt(parameters['step']) : 1;

        var sliderValue;
        var listWrap = $('<datalist />');
        listWrap.attr('id', inputId + '-datalist');
        for (
          sliderValue = parseInt(parameters['min']);
          sliderValue <= parseInt(parameters['max']);
          sliderValue += sliderStep
        ) {
          listItemValue = listItemLabel = sliderValue;
          listItemLabel = prependText + listItemLabel + appendText;

          listSingle = $('<option />')
            .attr('value', listItemValue)
            .attr('label', listItemLabel);
          listSingle.appendTo(listWrap);
        }
        listWrap.appendTo(parentNode);
        inputField.attr('list', inputId + '-datalist');
      }
      hasRange = true;
      $this.remove();
    } else if (command == 'hide_form_dropdown') {
      let queryString = window.location.search;
      let urlParams = new URLSearchParams(queryString);
      let ticket_form_id = urlParams.get('ticket_form_id');
      if (
        parameters['ticket_form_id'] &&
        parameters['ticket_form_id'] == ticket_form_id
      ) {
        $('.request_ticket_form_id').hide();
      }
      $this.parent().hide();
    } else if (command == 'rename_submit_button') {
      let queryString = window.location.search;
      let urlParams = new URLSearchParams(queryString);
      let ticket_form_id = urlParams.get('ticket_form_id');
      if (
        parameters['ticket_form_id'] &&
        parameters['ticket_form_id'] == ticket_form_id &&
        parameters['name'] &&
        parameters['name'] !== ''
      ) {
        $('footer').find('input').val(parameters['name']);
      }
      $this.parent().hide();
    } else if (command === 'reposition_attachments') {
      if (
        parameters['hide_original'] &&
        parameters['hide_original'] === 'true'
      ) {
        $('#upload-dropzone').closest('div.form-field').hide();
      }
      let dataDropZoneElement = $('#upload-dropzone')
        .closest('div.form-field')
        .clone();
      dataDropZoneElement
        .find('#upload-dropzone')
        .addClass('upload-dropzone-duplicate');
      dataDropZoneElement.find('#upload-dropzone').removeAttr('id');
      dataDropZoneElement
        .find('#request-attachments')
        .addClass('request-attachments-duplicate');
      dataDropZoneElement.find('#request-attachments').removeAttr('id');
      dataDropZoneElement
        .find('#request-attachments-pool')
        .addClass('request-attachments-pool-duplicate');
      dataDropZoneElement.find('#request-attachments-pool').removeAttr('id');
      let attachmentTitle = $this.parent().find('label');
      $(attachmentTitle).find('.optional').remove();
      dataDropZoneElement
        .find('label[for=request-attachments]')
        .html($(attachmentTitle).html());
      $this.parent().html(`${dataDropZoneElement.html()}`);
      $(document).on(
        'click',
        '.request-attachments-duplicate',
        function (event) {
          event.preventDefault();
          event.stopImmediatePropagation();
          $('#request-attachments').click();
        }
      );

      const attachmentPoolObserver = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
          if (mutation.type === 'childList') {
            $('.request-attachments-pool-duplicate').html('');
            $('#request-attachments-pool')
              .find('.upload-item')
              .each(function (index) {
                $(this).attr('data-upload-item', `${index}`);
              });
            $('.request-attachments-pool-duplicate').append($('#request-attachments-pool').html());
            $('.request-attachments-pool-duplicate').find('input').remove();
            $('.request-attachments-pool-duplicate')
              .find('span.upload-remove')
              .addClass('remove-upload');
            clearInterval(uploading_attachment);
            uploading_attachment = setInterval(checkUploading, 1000);
          }
        });
      });

      const targetElement = document.getElementById('request-attachments-pool');
      if (targetElement) {
        attachmentPoolObserver.observe(targetElement, {
          childList: true,
          subtree: true
        });
      }
      $(document).on('click', '.remove-upload', function (event) {
        event.preventDefault();
        event.stopImmediatePropagation();
        let uploadItemCount = $(this)
          .closest('li.upload-item')
          .attr('data-upload-item');
        if (uploadItemCount) {
          $('#request-attachments-pool')
            .find(`li[data-upload-item=${uploadItemCount}]`)
            .find('.upload-remove')
            .click();
        }
      });
    } else if (command === 'phone_field' && parameters['default']) {
      $this.closest('.form-field').addClass('phone_field_wrapper');
      $this.closest('.phone_field_wrapper').css('position', 'relative');

      let defaultCountries = [];
      if (parameters['countries']) {
        defaultCountries = parameters['countries'].split(',');
      }
      if (!defaultCountries.includes(parameters['default'])) {
        defaultCountries.splice(0, 0, parameters['default']);
      }
      let selectedCountries = countriesList;
      let defaultCountry;
      if (parameters['countries']) {
        selectedCountries = [];
        countriesList.forEach((element) => {
          if (defaultCountries.includes(element.code)) {
            selectedCountries.push(element);
          }
        });
      }
      countriesList.forEach((element) => {
        if (element.code === parameters['default']) {
          defaultCountry = element;
        }
      });
      let currentDialCode = defaultCountry.dial_code;

      const style = document.createElement('style');
      style.innerHTML = `#btn_counteirs_dial_codes{background-color:#e4e4e4;color:#fff;padding:9px 5px;font-size:16px;border:none;cursor:pointer;width:90px;border-top-left-radius:4px;border-bottom-left-radius:4px;padding-bottom:8px;cursor:pointer}#btn_counteirs_dial_codes:focus,#btn_counteirs_dial_codes:hover{background-color:#e4e4e4}.country_dropdown{position:absolute;left:1px;bottom:1px}.country_dropdown span{color:#000}.country_dropdown_content{display:none;position:absolute;background-color:#f1f1f1;min-width:80px;overflow:auto;box-shadow:0 8px 16px 0 rgba(0,0,0,.2);z-index:1}.country_dropdown_content a{color:#000;padding:12px 16px;text-decoration:none;display:block}.country_dropdown_content ul{min-width:300px;max-height:300px}.country_dropdown a:hover{background-color:#ddd}.show{display:block}.contact-page-wrapper .contact-form-wrapper form .form-field{position:relative}#btn_counteirs_dial_codes img,.dropdown-content-flag img{height:24px;margin-right:5px}#btn_counteirs_dial_codes:focus,#btn_counteirs_dial_codes:hover{background-color:#e4e4e4}.country_dropdown_content ul li{padding:5px 11px;cursor:pointer}.request_custom_fields_360046687232 input{padding-left:100px}.btn_counteirs_dial_codes:after{content:'';width:0;height:0;border-left:4px solid transparent;border-right:4px solid transparent;border-top:4px solid #000;position:absolute;bottom:19px;right:8px}.country_dropdown span{color:#000}.dropdown-content-text span{color:#9b9b9b}.country_dropdown_content ul li:hover{background:#fff}#dial_code_input{padding-left:100px}`;
      document.head.appendChild(style);
      let dorpDownContetnt = document.createElement('div');
      dorpDownContetnt.setAttribute('class', 'country_dropdown');
      dorpDownContetnt.innerHTML += `<div id="btn_counteirs_dial_codes" class="dropbtn btn_counteirs_dial_codes"><span class="countries_flag">
      <img src="https://flagcdn.com/w20/${defaultCountry.code.toLowerCase()}.png" srcset="https://flagcdn.com/w40/${defaultCountry.code.toLowerCase()}.png 2x" width="20" alt=${defaultCountry}>${defaultCountry.dial_code
        }</span></div>`;
      let countriesDialCodList = document.createElement('div');
      countriesDialCodList.setAttribute('id', 'countries_dial_code_list');
      countriesDialCodList.setAttribute('class', 'country_dropdown_content');
      let listContainer = document.createElement('ul');
      selectedCountries.forEach((element) => {
        listContainer.innerHTML += `<li class="dial_code" data-code="${element.dial_code
          }" data-country="${element.code
          }"><span class="dropdown-content-flag"><img src="https://flagcdn.com/w20/${element.code.toLowerCase()}.png" srcset="https://flagcdn.com/w40/${element.code.toLowerCase()}.png 2x" width="20" alt=${element.name
          }></span> <span class="dropdown-content-text">${element.name} <span>${element.dial_code
          }</span></span></li>`;
      });
      countriesDialCodList.appendChild(listContainer);
      dorpDownContetnt.appendChild(countriesDialCodList);

      $(countriesDialCodList).ready(function () {
        $('head').append(
          `<style>
          .country_dropdown{
            left: 0.1rem;
            top: 1.65rem;
            bottom: 0rem;
          }
          #btn_counteirs_dial_codes{
            padding: 0px;
             align-items: center; 
             display: flex; 
             height: calc(100% - 2px);
          }
          .country_dropdown span{
            display: flex;
            justify-content: left;
            margin-left: 0.5rem;
          }
          #btn_counteirs_dial_codes img{
            height: 20px;
            min-width: 14px;
            margin-right: 7px;
          }
          .btn_counteirs_dial_codes:after{
             top: 48%;
             bottom: initial;
          }
          .country_dropdown_content ul li{
            display: flex;
            padding: 8px 1px;
          }
          </style>`
        );
      });

      $(document).on('click', '#btn_counteirs_dial_codes', function (event) {
        event.preventDefault();
        event.stopImmediatePropagation();
        document
          .getElementById('countries_dial_code_list')
          .classList.toggle('show');
      });
      $(document).on('click', '.dial_code', function (event) {
        $this
          .parent()
          .find('input[id^=request_custom_fields_]')
          .val($(this).attr('data-code'));
        currentDialCode = $(this).attr('data-code');
        let dataCurrnetCountry = $(this).attr('data-country');
        $('#dial_code_input').trigger('change');
        $('#btn_counteirs_dial_codes').html(
          `<span class="countries_flag"><img src="https://flagcdn.com/w20/${dataCurrnetCountry.toLowerCase()}.png" srcset="https://flagcdn.com/w40/${dataCurrnetCountry.toLowerCase()}.png 2x" width="20" alt=${dataCurrnetCountry}>${currentDialCode}</span>`
        );
      });
      let dialCodeInput = document.createElement('input');
      dialCodeInput.setAttribute('id', 'dial_code_input');
      dialCodeInput.setAttribute('type', 'text');
      $this.parent().append(dialCodeInput);
      $this.parent().append(dorpDownContetnt);
      $this.parent().find('input[id^=request_custom_fields_]').hide();
      $this.hide();
      $('#dial_code_input').on('change keyup paste', function (event) {
        $this
          .parent()
          .find('input[id^=request_custom_fields_]')
          .val(`${currentDialCode} ${event.target.value}`);
      });
    } else if (command == 'currency') {
      let defaultCurrency = new Object();
      let incomingDefaultCurrencies = [];
      let defaultCurrencies = [];
      let currencySymbolsArray = [];
      if (parameters['default']) {
        defaultCurrency['code'] = parameters['default'];
      }
      if (parameters['currencies']) {
        incomingDefaultCurrencies = parameters['currencies'].split(',');
      }
      for (const key in commonCurrencies) {
        if (Object.hasOwnProperty.call(commonCurrencies, key)) {
          const element = commonCurrencies[key];
          if (element.code == defaultCurrency.code) {
            defaultCurrency['symbol'] = element['symbol'];
          }
          if (incomingDefaultCurrencies.length > 0) {
            incomingDefaultCurrencies.forEach((currencyCode) => {
              let currentCurrency = new Object();
              if (element.code == currencyCode) {
                currentCurrency['code'] = element.code;
                currentCurrency['symbol'] = element.symbol;
                defaultCurrencies.push(currentCurrency);
                currencySymbolsArray.push(element.symbol);
              }
            });
          } else {
            let currentCurrency = new Object();
            currentCurrency['code'] = element.code;
            currentCurrency['symbol'] = element.symbol;
            defaultCurrencies.push(currentCurrency);
            currencySymbolsArray.push(element.symbol);
          }
        }
      }

      $this.hide();
      $this.parent().find('input[type="text"]').addClass('currency-field');
      $(document).on('change', '.currency-field', function (event) {
        let currencySymbol = '';
        let targetValue = event.target.value;
        for (var i = 0; i < targetValue.length; i++) {
          if (
            Number.isNaN(Number(targetValue[i])) &&
            targetValue[i] !== ' ' &&
            targetValue[i] !== '.' &&
            targetValue[i] !== ','
          ) {
            if (currencySymbol === '') {
              currencySymbol = targetValue[i];
            } else {
              currencySymbol = currencySymbol + targetValue[i];
            }
          }
        }

        let currencyValue = event.target.value;
        let defaultCurrencyValueEntered = event.target.value;
        currencyValue = currencyValue.substring(currencySymbol.length);
        currencyValue = reverseString(currencyValue);
        let currencySeperatorArray = [];
        let currencyCode;
        if (
          !currencySymbolsArray.includes(currencySymbol) &&
          defaultCurrency.symbol
        ) {
          currencyValue = reverseString(defaultCurrencyValueEntered);
          currencySymbol = defaultCurrency.symbol;
        }
        if (currencySymbolsArray.includes(currencySymbol)) {
          defaultCurrencies.forEach((currencyElement) => {
            if (currencyElement.symbol === currencySymbol) {
              currencyCode = currencyElement.code;
            }
          });
          for (var i = 0; i < currencyValue.length; i++) {
            if (
              currencyValue[i] === '.' &&
              !currencySeperatorArray.includes('dot')
            ) {
              currencySeperatorArray.push('dot');
            }
            if (
              currencyValue[i] === ',' &&
              !currencySeperatorArray.includes('coma')
            ) {
              currencySeperatorArray.push('coma');
            }
          }

          if (currencySeperatorArray.length === 0) {
            currencyValue = Number(reverseString(currencyValue));
          } else if (
            currencySeperatorArray[0] === 'dot' &&
            currencySeperatorArray.length === 1
          ) {
            currencyValue = reverseString(currencyValue);
            let indexOfDot = currencyValue.indexOf('.');
            if (Number.isNaN(Number(currencyValue))) {
              currencyValue = currencyValue.replace('.', '');
              currencyValue = Number(currencyValue);
            } else if (currencyValue.length - 1 - indexOfDot === 3) {
              currencyValue = currencyValue.replace('.', '');
              currencyValue = Number(currencyValue);
            } else {
              currencyValue = Number(currencyValue);
            }
          } else if (
            currencySeperatorArray[0] === 'coma' &&
            currencySeperatorArray.length === 1
          ) {
            currencyValue = reverseString(currencyValue);
            let indexOfComa = currencyValue.indexOf(',');
            let splitedCurrency = currencyValue.split(',');
            if (
              currencyValue.length - 1 - indexOfComa <= 2 &&
              splitedCurrency.length <= 2
            ) {
              currencyValue = currencyValue.replaceAll(',', '.');
              currencyValue = Number(currencyValue);
            } else {
              currencyValue = currencyValue.replaceAll(',', '');
              currencyValue = Number(currencyValue);
            }
          } else if (
            currencySeperatorArray[0] === 'dot' &&
            currencySeperatorArray.length === 2
          ) {
            currencyValue = currencyValue.replaceAll(',', '');
            currencyValue = Number(reverseString(currencyValue));
          } else if (
            currencySeperatorArray[0] === 'coma' &&
            currencySeperatorArray.length === 2
          ) {
            currencyValue = currencyValue.replaceAll('.', '');
            currencyValue = currencyValue.replace(',', '.');
            currencyValue = Number(reverseString(currencyValue));
          }
        }
        if (currencyValue && !Number.isNaN(currencyValue) && currencyCode) {
          $('input.currency-field').val(`${currencyValue} ${currencyCode}`);
        } else if (
          defaultCurrency.symbol &&
          defaultCurrency.code &&
          currencyValue !== 0 &&
          !Number.isNaN(currencyValue)
        ) {
          $('input.currency-field').val(
            `${currencyValue} ${defaultCurrency.code}`
          );
        }
      });
    }
  }
  // Close the dropdown if the user clicks outside of it
  window.onclick = function (event) {
    if (!event.target.matches('.dropbtn')) {
      var dropdowns = document.getElementsByClassName(
        'country_dropdown_content'
      );
      var i;
      for (i = 0; i < dropdowns.length; i++) {
        var openDropdown = dropdowns[i];
        if (openDropdown.classList.contains('show')) {
          openDropdown.classList.remove('show');
        }
      }
    }
  };
  function checkUploading() {
    let totalUploadedItems = $('#request-attachments-pool').find(
      '.upload-item'
    ).length;
    let uploaded = 0;
    $('#request-attachments-pool')
      .find('.upload-item')
      .each(function (index) {
        if ($(this).attr('aria-busy') === 'false') {
          $('.request-attachments-pool-duplicate').html('');
          $('.request-attachments-pool-duplicate').append(
            $('#request-attachments-pool').html()
          );
          $('.request-attachments-pool-duplicate').find('input').remove();
          $('.request-attachments-pool-duplicate')
            .find('span.upload-remove')
            .addClass('remove-upload');
          uploaded = uploaded + 1;
        }
      });
    if (totalUploadedItems == uploaded) {
      clearInterval(uploading_attachment);
    }
  }
  function getOptionWrap(selectId, index, optionValue, optionText, isSelected) {
    var radioWrap = document.createElement('div');
    radioWrap.className = 'radio-single-wrap';

    var radioInput = document.createElement('input');
    radioInput.className = 'radio-single';
    radioInput.id = `${selectId}-${index}`;
    radioInput.value = optionValue;
    radioInput.style.display = 'inline-block';
    radioInput.style.width = 'auto';

    if (isSelected) {
      radioInput.checked = true;
    }
    radioInput.setAttribute('name', selectId);
    radioInput.setAttribute('type', 'radio');

    var radioLabel = document.createElement('label');
    radioLabel.className = 'radio-single-label';
    radioLabel.setAttribute('for', `${selectId}-${index}`);
    radioLabel.innerHTML = optionText;
    radioLabel.style.display = 'inline-block';
    radioLabel.style.marginLeft = '10px';

    radioWrap.appendChild(radioInput);
    radioWrap.appendChild(radioLabel);

    return radioWrap;
  }

  function performChatAction(commandArray, data, $this) {
    var commandIndex = 0;
    var actions = [];
    while (commandIndex < commandArray.length) {
      if (
        commandArray[commandIndex].command == 'when' &&
        commandArray[commandIndex].type == 'function'
      ) {
        var nextIndex = commandIndex + 1;
        var remainingCommands = commandArray.slice(nextIndex);
        var closingCommandIndex = remainingCommands.findIndex(
          (commandDetail) =>
            commandDetail.command === 'when' || commandDetail.command === 'else'
        );

        if (data['status'] == commandArray[commandIndex].parameters['status']) {
          if (closingCommandIndex >= 0) {
            actions = remainingCommands.slice(0, closingCommandIndex);
            break;
          } else {
            commandIndex = commandArray.length;
          }
        } else {
          commandIndex = nextIndex + closingCommandIndex;
        }
      } else if (commandArray[commandIndex].command == 'else') {
        var nextIndex = commandIndex + 1;
        var remainingCommands = commandArray.slice(nextIndex);
        var closingCommandIndex = remainingCommands.findIndex(
          (commandDetail) =>
            commandDetail.command === 'when' || commandDetail.type === 'closing'
        );
        if (closingCommandIndex >= 0) {
          actions = remainingCommands.slice(0, closingCommandIndex);
          break;
        } else {
          commandIndex = commandArray.length;
          console.error('No closing tag found');
        }
      } else {
        commandIndex++;
      }
    }
    for (let action of actions) {
      runCommand($this, action.command, action.parameters);
    }
  }

  function checFieldType(fieldId) {
    if (
      $(`.request_custom_fields_${fieldId}`).find('a.nesty-input').length > 0
    ) {
      return 'Drop-down';
    } else if (
      $(`#request_custom_fields_${fieldId}`)
        .parent()
        .find('.hc-multiselect-menu').length > 0
    ) {
      return 'Multi-select';
    } else {
      // Can be other fields then Drop-down and Multi-select
      return 'Other-field';
    }
  }

  function checkAddToDescription($this, includeFields, excludeFields) {
    var fieldId = $this.attr('id');
    fieldId = fieldId ? fieldId.match(/(\d+)/) : [];

    if (fieldId[0]) {
      fieldId = fieldId[0];
      var primaryConditions =
        $this.closest('div').css('display') == 'block' &&
          $this.val() &&
          $this.val() !== '' &&
          $this.attr('type') !== 'checkbox'
          ? true
          : false;

      if (includeFields.length > 0) {
        return primaryConditions && includeFields.includes(fieldId)
          ? true
          : false;
      } else {
        return primaryConditions && !excludeFields.includes(fieldId)
          ? true
          : false;
      }
    } else {
      return false;
    }
  }
  function restoreFormFields() {
    $('#new_request')
      .children('div.form-field')
      .each(function (index) {
        if (
          !$(this).is(':visible') &&
          $(this).find('.shouldBeRemoved').length > 0
        ) {
          $(this).find('.shouldBeRemoved').removeClass('shouldBeRemoved');
          if ($(this).css('display') == 'block') {
            $(this).css('display', '');
          }
        } else {
          $(this).find('.shouldBeRemoved').remove();
          if ($(this).css('display') == 'block') {
            $(this).css('display', '');
          }
        }
      });
  }
  function suggestArticle(fieldId, searchObject) {
    const END_URL = '/api/v2/help_center';
    let url = `${END_URL}/articles/search.json?query=${searchObject.query}`;
    delete searchObject.query;
    for (const key in searchObject) {
      if (Object.hasOwnProperty.call(searchObject, key)) {
        url = url.concat(`&${key}=${searchObject[key]}`);
      }
    }
    $.getJSON(url, function (data) {
      if (data.count > 0) {
        $(`.request_custom_fields_${fieldId}`)
          .find('.suggested-article')
          .show();
        $(`.request_custom_fields_${fieldId}`)
          .find('.suggested-article')
          .find('ul')
          .html('');
        data.results.forEach((element) => {
          $(`.request_custom_fields_${fieldId}`)
            .find('.suggested-article')
            .find('ul')
            .append(
              `<li><a href=${element.html_url}>${element.title}</a></li>`
            );
        });
      } else {
        $(`.request_custom_fields_${fieldId}`)
          .find('.suggested-article')
          .find('ul')
          .html('');
        $(`.request_custom_fields_${fieldId}`)
          .find('.suggested-article')
          .hide();
      }
    });
  }
  function suggestFormFieldModifierArticle(
    fieldId,
    fieldModifierValue,
    externalSearchObject
  ) {
    selectedTag = '';
    searchObject = externalSearchObject;
    if (
      $(`.request_custom_fields_${fieldId}`).find('.suggested-article')
        .length === 0
    ) {
      $(`.request_custom_fields_${fieldId}`).append(
        '<div class="suggested-article" style="display:none;"><p>Suggested articles</p><ul></ul></div>'
      );
    }
    fieldModifierValue.forEach((element) => {
      if (selectedTag === '') {
        selectedTag = `${element.section}_${element.tag}`;
      } else {
        selectedTag = selectedTag.concat(`,${element.section}_${element.tag}`);
      }
    });
    searchObject['query'] = '';
    searchObject['label_names'] = selectedTag;
    if (searchObject['label_names'] !== '') {
      suggestArticle(fieldId, searchObject);
    } else {
      $(`.request_custom_fields_${fieldId}`).find('.suggested-article').hide();
      $(`.request_custom_fields_${fieldId}`)
        .find('.suggested-article')
        .find('ul')
        .html('');
    }
  }
  async function getFormFields(fieldId, includeTags, excludeTags) {
    const END_URL =
      '/api/v2/ticket_forms/show_many.json?include=ticket_fields&locale=nl&associated_to_brand=true&end_user_visible=true&active=true';
    let wildCard = /[*]/;
    let includeAbleTagNames = [];
    let excludeAbleTagNames = [];
    let data = await $.getJSON(END_URL);
    if (data.count > 0 && data.ticket_fields.length > 0) {
      data.ticket_fields.forEach((element) => {
        if (element.id == fieldId && element.custom_field_options.length > 0) {
          element.custom_field_options.forEach((cutom_tag_element) => {
            if (excludeTags.length > 0) {
              excludeTags.forEach((element) => {
                if (wildCard.test(element)) {
                  let willdCardTagsArray = element.split('*');
                  if (willdCardTagsArray.length > 1) {
                    if (
                      cutom_tag_element.value.includes(willdCardTagsArray[0])
                    ) {
                      excludeAbleTagNames = excludeAbleTagNames.concat(
                        cutom_tag_element.name.split('::')
                      );
                    }
                  }
                }
              });
            }
            if (includeTags.length > 0) {
              includeTags.forEach((element) => {
                if (wildCard.test(element)) {
                  let willdCardTagsArray = element.split('*');
                  if (willdCardTagsArray.length > 1) {
                    if (
                      cutom_tag_element.value.includes(willdCardTagsArray[0])
                    ) {
                      includeAbleTagNames = includeAbleTagNames.concat(
                        cutom_tag_element.name.split('::')
                      );
                    }
                  }
                } else {
                  if (cutom_tag_element.value === element) {
                    includeAbleTagNames = includeAbleTagNames.concat(
                      cutom_tag_element.name.split('::')
                    );
                  }
                }
              });
            }
          });
        }
      });
    }
    return {
      excludeAbleTagNames: excludeAbleTagNames.filter(
        (v, i, a) => a.indexOf(v) === i
      ),
      includeAbleTagNames: includeAbleTagNames.filter(
        (v, i, a) => a.indexOf(v) === i
      ),
    };
  }
  $.fn.hasAttr = function (name) {
    return this.attr(name) !== undefined;
  };
  stepsScript();
});

$(document).ready(function () {
  const getElementAfterRender = setTimeout(function () {
    displayOrHideSubmit();
    hideCheckBox();
    clearTimeout(getElementAfterRender);
  }, 500);

  $(document).on('change', function () {
    displayOrHideSubmit();
    hideCheckBox();
  });
});
function setSubjectForForm(subjectData) {
  const requestSubjectInput = "input[name='request[subject]']";
  const hasSetSubject = subjectData;
  if (!hasSetSubject) {
    if ($("[name='request[ticket_form_id]']").is('select')) {
      $(requestSubjectInput).val(
        $("select[name='request[ticket_form_id]'] option:selected").text()
      );
      $(requestSubjectInput).parent().hide();
    } else {
      $(requestSubjectInput).val(
        $('.nesty-input:first').text().trim(' ').replaceAll('"', '')
      );
      $(requestSubjectInput).parent().hide();
    }
  }
}

//Script for steps start
function stepsScript() {
  $(document).on('click', '.block-accordion-title', function (event) {
    event.preventDefault();
    if (
      $(this).closest('.block-accordion-item').is('.block-accordion-active')
    ) {
      $(this)
        .closest('.block-accordion-item')
        .removeClass('block-accordion-active');
      $(this)
        .closest('.block-accordion-item')
        .find('.block-accordion-body')
        .css({ padding: '15px 0px' });
      $(this)
        .closest('.block-accordion-item')
        .find('.block-accordion-body-inner')
        .stop(true, true)
        .slideUp(250);
      $(this)
        .closest('.block-accordion-item')
        .find('.block-accordion-title svg')
        .css({ transform: 'rotate(0)' });
    } else {
      $(this)
        .closest('.block-accordion')
        .find('.block-accordion-item.block-accordion-active')
        .removeClass('block-accordion-active');
      $(this)
        .closest('.block-accordion-item')
        .addClass('block-accordion-active');
      $(this)
        .closest('.block-accordion-item')
        .find('.block-accordion-body')
        .css({ padding: '15px 0px' });
      $(this)
        .closest('.block-accordion-item')
        .find('.block-accordion-body-inner')
        .stop(true, true)
        .slideDown(250);
      $(this)
        .closest('.block-accordion-item')
        .find('.block-accordion-title svg')
        .css({ transform: 'rotate(180deg)' });
      //for closing other accordion blocks
      $(this)
        .closest('.block-accordion')
        .find('.block-accordion-item:not(.block-accordion-active)')
        .find('.block-accordion-body')
        .css({ padding: '15px 0px' });
      $(this)
        .closest('.block-accordion')
        .find('.block-accordion-item:not(.block-accordion-active)')
        .find('.block-accordion-body-inner')
        .stop(true, true)
        .slideUp(250);
      $(this)
        .closest('.block-accordion')
        .find('.block-accordion-item:not(.block-accordion-active)')
        .find('.block-accordion-title svg')
        .css({ transform: 'rotate(0)' });
    }
  });

  $(document).on(
    'click',
    '.block-stepper-horizontal .block-stepper-action-next',
    function (event) {
      event.preventDefault();
      var data_block = $(this)
        .closest('.block-stepper-body')
        .attr('data-block');
      let nextBlockLength = $(this)
        .closest('.block-stepper-horizontal')
        .find('[data-id="' + data_block + '"]')
        .next('li').length;
      if (nextBlockLength > 0) {
        $(this)
          .closest('.block-stepper-horizontal')
          .find('[data-id="' + data_block + '"]')
          .removeClass('block-stepper-active');
        $(this)
          .closest('.block-stepper-horizontal')
          .find('[data-id="' + data_block + '"]')
          .next('li')
          .addClass('block-stepper-active');

        $(this)
          .closest('.block-stepper-horizontal')
          .find('[data-id="' + data_block + '"]')
          .find('.block-stepper-title')
          .css({ 'font-weight': '400', color: 'rgb(104, 115, 125)' });
        $(this)
          .closest('.block-stepper-horizontal')
          .find('[data-id="' + data_block + '"]')
          .find('.block-stepper-circle')
          .css({
            background: 'rgb(233, 235, 237)',
            color: 'rgb(47, 57, 65)',
          });

        $(this)
          .closest('.block-stepper-horizontal')
          .find('[data-id="' + data_block + '"]')
          .next('li.block-stepper-active')
          .find('.block-stepper-title')
          .css({ 'font-weight': '600', color: 'rgb(47, 57, 65)' });
        $(this)
          .closest('.block-stepper-horizontal')
          .find('[data-id="' + data_block + '"]')
          .next('li.block-stepper-active')
          .find('.block-stepper-circle')
          .css({
            background: 'rgb(104, 115, 125)',
            color: 'rgb(255, 255, 255)',
          });

        $(this)
          .closest('.block-stepper-horizontal')
          .find('[data-id="' + data_block + '"]')
          .find('.stepper-number')
          .hide();
        $(this)
          .closest('.block-stepper-horizontal')
          .find('[data-id="' + data_block + '"]')
          .find('.block-stepper-circle svg')
          .show();

        $(this).closest('.block-stepper-body').hide();
        $(this)
          .closest('.block-stepper-body')
          .next('.block-stepper-body')
          .show();
      }
    }
  );
  $(document).on(
    'click',
    '.block-stepper-horizontal .block-stepper-action-back',
    function (event) {
      event.preventDefault();
      var data_block = $(this)
        .closest('.block-stepper-body')
        .attr('data-block');

      let previousBlockLength = $(this)
        .closest('.block-stepper-horizontal')
        .find('[data-id="' + data_block + '"]')
        .prev('li').length;
      if (previousBlockLength > 0) {
        $(this)
          .closest('.block-stepper-horizontal')
          .find('[data-id="' + data_block + '"]')
          .removeClass('block-stepper-active');
        $(this)
          .closest('.block-stepper-horizontal')
          .find('[data-id="' + data_block + '"]')
          .prev('li')
          .addClass('block-stepper-active');

        $(this)
          .closest('.block-stepper-horizontal')
          .find('[data-id="' + data_block + '"]')
          .find('.block-stepper-title')
          .css({ 'font-weight': '400', color: 'rgb(104, 115, 125)' });
        $(this)
          .closest('.block-stepper-horizontal')
          .find('[data-id="' + data_block + '"]')
          .find('.block-stepper-circle')
          .css({
            background: 'rgb(233, 235, 237)',
            color: 'rgb(47, 57, 65)',
          });

        $(this)
          .closest('.block-stepper-horizontal')
          .find('[data-id="' + data_block + '"]')
          .prev('li.block-stepper-active')
          .find('.block-stepper-title')
          .css({ 'font-weight': '600', color: 'rgb(47, 57, 65)' });
        $(this)
          .closest('.block-stepper-horizontal')
          .find('[data-id="' + data_block + '"]')
          .prev('li.block-stepper-active')
          .find('.block-stepper-circle')
          .css({
            background: 'rgb(104, 115, 125)',
            color: 'rgb(255, 255, 255)',
          });

        $(this).closest('.block-stepper-body').hide();
        $(this)
          .closest('.block-stepper-body')
          .prev('.block-stepper-body')
          .show();

        $(this)
          .closest('.block-stepper-horizontal')
          .find('[data-id="' + data_block + '"]')
          .prev('li.block-stepper-active')
          .find('.stepper-number')
          .show();
        $(this)
          .closest('.block-stepper-horizontal')
          .find('[data-id="' + data_block + '"]')
          .prev('li.block-stepper-active')
          .find('.block-stepper-circle svg')
          .hide();
      }
    }
  );
  $(document).ready(function () {
    $(document).on(
      'click',
      '.block-stepper-vertical .block-stepper-action-next',
      function (event) {
        event.preventDefault();
        let nextBlockLength = $(this).closest('li').next('li').length;
        if (nextBlockLength > 0) {
          $(this)
            .closest('li.block-stepper-active')
            .removeClass('block-stepper-active');
          $(this).closest('li').next('li').addClass('block-stepper-active');

          $(this)
            .closest('li')
            .find('.block-stepper-body-inner')
            .stop(true, true)
            .slideUp(250);
          $(this)
            .closest('li')
            .next('li.block-stepper-active')
            .find('.block-stepper-body-inner')
            .stop(true, true)
            .slideDown(250);

          $(this)
            .closest('li')
            .find('.block-stepper-title')
            .css({ 'font-weight': '400' });
          $(this).closest('li').find('.block-stepper-circle').css({
            background: 'rgb(233, 235, 237)',
            color: 'rgb(47, 57, 65)',
          });
          $(this)
            .closest('li')
            .find('.block-stepper-title-text')
            .css({ color: 'rgb(104, 115, 125)' });
          $(this).closest('li').find('.stepper-number').hide();
          $(this).closest('li').find('.block-stepper-circle svg').show();

          $(this)
            .closest('li')
            .next('li.block-stepper-active')
            .find('.block-stepper-title')
            .css({ 'font-weight': '600' });
          $(this)
            .closest('li')
            .next('li.block-stepper-active')
            .find('.block-stepper-circle')
            .css({
              background: 'rgb(104, 115, 125)',
              color: 'rgb(255, 255, 255)',
            });
          $(this)
            .closest('li')
            .next('li.block-stepper-active')
            .find('.block-stepper-title-text')
            .css({ color: 'rgb(47, 57, 65)' });
          $(this)
            .closest('li')
            .next('li.block-stepper-active')
            .find('.stepper-number')
            .show();
          $(this)
            .closest('li')
            .next('li.block-stepper-active')
            .find('.block-stepper-circle svg')
            .hide();
        }
      }
    );
    $(document).on(
      'click',
      '.block-stepper-vertical .block-stepper-action-back',
      function (event) {
        event.preventDefault();
        let previousBlockLength = $(this).closest('li').prev('li').length;
        if (previousBlockLength > 0) {
          $(this)
            .closest('li.block-stepper-active')
            .removeClass('block-stepper-active');
          $(this).closest('li').prev('li').addClass('block-stepper-active');

          $(this)
            .closest('li')
            .find('.block-stepper-body-inner')
            .stop(true, true)
            .slideUp(250);
          $(this)
            .closest('li')
            .prev('li.block-stepper-active')
            .find('.block-stepper-body-inner')
            .stop(true, true)
            .slideDown(250);

          $(this)
            .closest('li')
            .find('.block-stepper-title')
            .css({ 'font-weight': '400' });
          $(this).closest('li').find('.block-stepper-circle').css({
            background: 'rgb(233, 235, 237)',
            color: 'rgb(47, 57, 65)',
          });
          $(this)
            .closest('li')
            .find('.block-stepper-title-text')
            .css({ color: 'rgb(104, 115, 125)' });
          $(this).closest('li').find('.stepper-number').show();
          $(this).closest('li').find('.block-stepper-circle svg').hide();

          $(this)
            .closest('li')
            .prev('li.block-stepper-active')
            .find('.block-stepper-title')
            .css({ 'font-weight': '600' });
          $(this)
            .closest('li')
            .prev('li.block-stepper-active')
            .find('.block-stepper-circle')
            .css({
              background: 'rgb(104, 115, 125)',
              color: 'rgb(255, 255, 255)',
            });
          $(this)
            .closest('li')
            .prev('li.block-stepper-active')
            .find('.block-stepper-title-text')
            .css({ color: 'rgb(47, 57, 65)' });
          $(this)
            .closest('li')
            .prev('li.block-stepper-active')
            .find('.stepper-number')
            .show();
          $(this)
            .closest('li')
            .prev('li.block-stepper-active')
            .find('.block-stepper-circle svg')
            .hide();
        }
      }
    );
    $(document).on('click', '.progress-back', function (event) {
      event.preventDefault();
      let backItem = parseInt($(this).attr('data-id'));
      let previousBlockLength = $('#progress-block-' + (backItem - 1)).length;
      if (previousBlockLength > 0) {
        $('#progress-block-' + (backItem - 1)).show();
        $('#progress-block-' + backItem).hide();
        let totalsteps = parseInt($('.progress-bar').attr('data-id'));
        $('.progress-bar').css(
          'width',
          (100 / totalsteps) * (backItem - 1) + '%'
        );
      }
    });
    $(document).on('click', '.progress-next', function (event) {
      event.preventDefault();
      let nextItem = parseInt($(this).attr('data-id'));
      let nexBlockLength = $('#progress-block-' + (nextItem + 1)).length;
      if (nexBlockLength > 0) {
        $('#progress-block-' + (nextItem + 1)).show();
        $('#progress-block-' + nextItem).hide();
        let totalsteps = parseInt($('.progress-bar').attr('data-id'));
        $('.progress-bar').css(
          'width',
          (100 / totalsteps) * (nextItem + 1) + '%'
        );
      }
    });
  });
}

function createStepButtons(
  parameters,
  currentDiv,
  stepCount,
  stepTitle,
  activeType
) {
  if (parseInt(stepCount) > 1) {
    if (activeType == 'accordion') {
      addAccordionItem(stepTitle, stepCount, parameters);
    }

    if (activeType == 'horizontal') {
      addHorizontalStepper(stepTitle, stepCount, parameters);
      addHorizontalItem(stepCount, parameters);
    }

    if (activeType == 'vertical') {
      addVerticalStepper(stepTitle, stepCount, parameters);
    }
    if (activeType == 'progress') {
      progressItem(stepCount, parameters);
    }
  }

  if (typeof parameters['type'] != 'undefined') {
    let type = parameters['type'];
    switch (type) {
      case 'progress':
        showProgress(currentDiv, stepCount, parameters);
        break;

      case 'horizontal':
        showHorizontalStepper(currentDiv, stepTitle, stepCount, parameters);
        break;

      case 'vertical':
        showVerticalStepper(currentDiv, stepTitle, stepCount, parameters);
        break;

      case 'accordion':
        showAccordion(currentDiv, stepTitle, stepCount, parameters);
        break;

      default:
        break;
    }
  }
}

function showProgress(currentDiv, stepCount, parameters) {
  let backgroundColor = '#e9ebed';
  let barColor = '#038153';
  if (typeof parameters['background_color'] != 'undefined') {
    backgroundColor = parameters['background_color'];
  }
  if (typeof parameters['bar_color'] != 'undefined') {
    barColor = parameters['bar_color'];
  }
  let html =
    '<div class="block-progress" style="margin: 8px 0px; border-radius: 3px; background-color: ' +
    backgroundColor +
    '; color: ' +
    barColor +
    ';">';
  html +=
    '<div class="progress-bar" style="transition: width 0.1s ease-in-out 0s;border-radius: 3px;background: currentcolor none repeat scroll 0% 0%; width: 0%;height: 6px;margin-top: 25px;"></div>';
  html += '</div><div id="progress-div"></div>';
  currentDiv.before(html);
  progressItem(stepCount, parameters);
}

function progressItem(stepCount, parameters) {
  setTimeout(function () {
    let displayDiv = 'display:none';
    if (parseInt(stepCount) == 1) {
      displayDiv = '';
    }
    let html =
      '<div style="' +
      displayDiv +
      '" id="progress-block-' +
      stepCount +
      '"><div class = "progress-body" id=progress-item-' +
      stepCount +
      ' ></div><div style="margin-top: 12px;padding: 3px;">';
    if (typeof parameters['previous'] != 'undefined') {
      html +=
        '<button data-id="' +
        stepCount +
        '" style="display: inline-flex; -moz-box-align: center; align-items: center; -moz-box-pack: center; justify-content: center;  transition: border-color 0.25s ease-in-out 0s,box-shadow 0.1s ease-in-out 0s, background-color 0.25s ease-in-out -moz 0s, color 0.25s ease-in-out 0s; margin: 0px; border: 1px solid transparent; border-radius: 4px; cursor: pointer; overflow: hidden; text-decoration: none; text-overflow: ellipsis; white-space: nowrap; font-family: inherit; font-weight: 400; box-sizing: border-box; user-select: none;  padding: 0px 1.07143em; height: 40px; line-height: 38px; font-size: 14px; background-color:transparent;color: #1f73b7;border-color: #1f73b7;outline: none;"class="progress-back">' +
        parameters['previous'] +
        '</button>\n';
    }
    if (typeof parameters['next'] != 'undefined') {
      if (typeof parameters['submit'] != 'undefined') {
        if (parameters['submit'] === 'true') {
          html +=
            '<button data-id ="' +
            stepCount +
            '" style="display: inline-flex; -moz-box-align: center; align-items: center; -moz-box-pack: center; justify-content: center; transition: border-color 0.25s ease-in-out 0s, box-shadow 0.1s ease-in-out 0s, background-color 0.25s ease-in-out 0s, color 0.25s ease-in-out 0s; margin: 0px; margin-left: 12px; border: none; border-radius: 4px; cursor: pointer; overflow: hidden; text-decoration: none; text-overflow: ellipsis; white-space: nowrap; font-family: inherit; font-weight: 400; box-sizing: border-box; user-select: none; padding: 0px 1.07143em; height: 40px; line-height: 38px; font-size: 14px; background-color:' +
            progressButtonBackgroundColor +
            ';background:' +
            progressButtonBackground +
            ';color:' +
            progressButtonColor +
            ';outline: none;" id="submit_request">' +
            parameters['next'] +
            '</button>\n';
        }
      } else {
        html +=
          '<button data-id ="' +
          stepCount +
          '" style="display: inline-flex; -moz-box-align: center; align-items: center; -moz-box-pack: center; justify-content: center; transition: border-color 0.25s ease-in-out 0s, box-shadow 0.1s ease-in-out 0s, background-color 0.25s ease-in-out 0s, color 0.25s ease-in-out 0s; margin: 0px; margin-left: 12px; border: none; border-radius: 4px; cursor: pointer; overflow: hidden; text-decoration: none; text-overflow: ellipsis; white-space: nowrap; font-family: inherit; font-weight: 400; box-sizing: border-box; user-select: none; padding: 0px 1.07143em; height: 40px; line-height: 38px; font-size: 14px; background-color:' +
          progressButtonBackgroundColor +
          ';background:' +
          progressButtonBackground +
          ';color:' +
          progressButtonColor +
          ';outline: none;" class="progress-next">' +
          parameters['next'] +
          '</button>\n';
      }
    }
    html += '</div></div>';
    $('#progress-div').append(html);
  }, 100);
}
function showAccordion(currentDiv, stepTitle, stepCount, parameters) {
  let html =
    '<div class="block-accordion" style="font-size: 14px;line-height: 20px;color: #2f3941;font-kerning: normal"></div>\n';
  currentDiv.before(html);
  addAccordionItem(stepTitle, stepCount, parameters);
}

function addAccordionItem(stepTitle, stepCount, parameters) {
  let activeOne = '';
  let displayDiv = 'display:none';
  if (parseInt(stepCount) == 1) {
    activeOne = 'block-accordion-active';
    displayDiv = '';
  }

  if (
    typeof parameters['hide_title'] != 'undefined' &&
    parameters['hide_title'] === 'true'
  ) {
    stepTitle = '';
  }

  let html = '<div class="block-accordion-item ' + activeOne + '" >\n';
  html +=
    '<div class="block-accordion-title" style="display: flex;-moz-box-align: center; align-items:center; font-size: 14px;"><button style="transition: color 0.1s ease-in-out 0s;outline: currentcolor none medium; border: medium none; background: transparent none repeat scroll 0% 0%; padding: 15px 0px 0px 0px; width: 100%; text-align: left; line-height: 1.42857; font-size: 14px; cursor: pointer; font-weight: 600;">' +
    stepTitle +
    '</button>\n';
  html +=
    '<svg style="transform: rotate(180deg);transition: transform 0.25s ease-in-out 0s;" width="16" height="16" viewBox="0 0 16 16" focusable="false" role="presentation" theme="[object Object]" data-garden-id="accordions.rotate_icon" data-garden-version="8.28.0" class="sc-kasBVs cxRuaN"> <path fill="currentColor" d="M12.688 5.61a.5.5 0 01.69.718l-.066.062-5 4a.5.5 0 01-.542.054l-.082-.054-5-4a.5.5 0 01.55-.83l.074.05L8 9.359l4.688-3.75z"> </path></svg></div>\n';
  html +=
    '<section class="block-accordion-body" style="transition: padding 0.25s ease-in-out 0s; padding: 15px 0px; border-bottom: 1px solid rgb(216, 220, 222);"><div class="block-accordion-body-inner" style="transition:max-height 0.25s ease-in-out 0s;overflow: hidden;line-height: 1.42857;font-size: 14px;' +
    displayDiv +
    '" id="block-accordion-item-' +
    stepCount +
    '">\n';
  html += '</div></section></div>\n';

  $('.block-accordion').append(html);
}

function showHorizontalStepper(currentDiv, stepTitle, stepCount, parameters) {
  let html =
    '<div class="block-stepper-horizontal" style="font-size: 14px; line-height: 20px; color: #2f3941; font-kerning: normal; font-family: system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen-Sans,Ubuntu,Cantarell,Helvetica Neue,Arial,sans-serif;" id="block-item">';
  html +=
    '<ol style="display: flex; margin: 0px; padding: 0px; list-style: outside none none; margin-top: 25px;" id="horizontal-item">';
  addHorizontalStepper(stepTitle, stepCount, parameters);
  html += '</ol>';

  html += '</div>';
  currentDiv.before(html);
  addHorizontalItem(stepCount, parameters);
}

function addHorizontalStepper(stepTitle, stepCount, parameters) {
  setTimeout(function () {
    let activeClass = '',
      activeCircle =
        'background: rgb(233, 235, 237) none repeat scroll 0% 0%; color: rgb(47, 57, 65);',
      fontWeight = 'font-weight: 400;';
    displayLine = '';
    if (parseInt(stepCount) == 1) {
      activeClass = 'block-stepper-active';
      activeCircle =
        'background: rgb(104, 115, 125) none repeat scroll 0% 0%; color: rgb(255, 255, 255);';
      fontWeight = 'font-weight: 600;';
      displayLine = 'display:none';
    }
    if (
      typeof parameters['hide_title'] != 'undefined' &&
      parameters['hide_title'] == 'true'
    ) {
      stepTitle = '';
    }

    let html =
      '<li class="' +
      activeClass +
      '"  data-id="block-stepper-' +
      stepCount +
      '" style="position: relative; flex: 1 1 0%; min-width: 60px;">\n';
    html +=
      '<div class="step_line" style="position: absolute; top: 12px; right: calc(50% + 24px); left: calc(-50% + 24px); flex: 1 1 0%; border-top: 1px solid rgb(216, 220, 222); border-color: rgb(216, 220, 222);' +
      displayLine +
      '"></div>\n';
    html +=
      '<div class="block-stepper-title" style="text-align: center; line-height: 1.42857; color: rgb(47, 57, 65); ' +
      fontWeight +
      '">\n';
    html +=
      '<div style="display: flex; flex-basis: 100%; -moz-box-pack: center; justify-content: center; width: 100%;">\n';
    html +=
      '<div  class="block-stepper-circle" style="display: flex; -moz-box-align: center; align-items: center; -moz-box-pack: center; justify-content: center; transition: background 0.25s ease-in-out 0s, color 0.25s ease-in-out 0s; border-radius: 100%; margin-bottom: 8px; width: 24px; min-width: 24px; height: 24px; min-height: 24px; line-height: 2; font-size: 12px;' +
      activeCircle +
      '">\n';
    html += '<span class="stepper-number">' + stepCount + '</span>\n';
    html +=
      '<svg width="16" height="16" viewBox="0 0 16 16" focusable="false" role="presentation" style="display: none;"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.25" d="M3 9l3 3 7-7"></path></svg></div></div><div class="block-stepper-title-text" style="padding: 0px 12px; overflow-wrap: break-word; ">' +
      stepTitle +
      '</div></div></li>\n';

    $('#horizontal-item').append(html);
  }, 100);
}

function addHorizontalItem(stepCount, parameters) {
  let classVal = '';
  if (parseInt(stepCount) > 1) {
    classVal = 'display : none;';
  }
  let html =
    '<div  class="block-stepper-body"  style="margin: 20px 0px 0px; ' +
    classVal +
    '" data-block="block-stepper-' +
    stepCount +
    '" id="block-stepper-' +
    stepCount +
    '">\n';
  html += '<div style="margin-top: 12px;padding: 3px; ">';
  if (typeof parameters['previous'] != 'undefined') {
    html +=
      '<button style="display: inline-flex; -moz-box-align: center; align-items: center; -moz-box-pack: center; justify-content: center;  transition: border-color 0.25s ease-in-out 0s,box-shadow 0.1s ease-in-out 0s, background-color 0.25s ease-in-out -moz 0s, color 0.25s ease-in-out 0s; margin: 0px; border: 1px solid transparent; border-radius: 4px; cursor: pointer; overflow: hidden; text-decoration: none; text-overflow: ellipsis; white-space: nowrap; font-family: inherit; font-weight: 400; box-sizing: border-box; user-select: none;  padding: 0px 1.07143em; height: 40px; line-height: 38px; font-size: 14px; background-color:transparent;color: #1f73b7;border-color: #1f73b7;outline: none;" class="block-stepper-action-back">' +
      parameters['previous'] +
      '</button>\n';
  }
  if (typeof parameters['next'] != 'undefined') {
    if (typeof parameters['submit'] != 'undefined') {
      if (parameters['submit'] === 'true') {
        html +=
          '<button style="display: inline-flex; -moz-box-align: center; align-items: center; -moz-box-pack: center; justify-content: center; transition: border-color 0.25s ease-in-out 0s, box-shadow 0.1s ease-in-out 0s, background-color 0.25s ease-in-out 0s, color 0.25s ease-in-out 0s; margin: 0px; margin-left: 12px; border: none; border-radius: 4px; cursor: pointer; overflow: hidden; text-decoration: none; text-overflow: ellipsis; white-space: nowrap; font-family: inherit; font-weight: 400; box-sizing: border-box; user-select: none; padding: 0px 1.07143em; height: 40px; line-height: 38px; font-size: 14px; background-color:' +
          progressButtonBackgroundColor +
          ';background:' +
          progressButtonBackground +
          ';color:' +
          progressButtonColor +
          ';outline: none;" id="submit_request">' +
          parameters['next'] +
          '</button>\n';
      }
    } else {
      html +=
        '<button style="display: inline-flex; -moz-box-align: center; align-items: center; -moz-box-pack: center; justify-content: center; transition: border-color 0.25s ease-in-out 0s, box-shadow 0.1s ease-in-out 0s, background-color 0.25s ease-in-out 0s, color 0.25s ease-in-out 0s; margin: 0px; margin-left: 12px; border: none; border-radius: 4px; cursor: pointer; overflow: hidden; text-decoration: none; text-overflow: ellipsis; white-space: nowrap; font-family: inherit; font-weight: 400; box-sizing: border-box; user-select: none; padding: 0px 1.07143em; height: 40px; line-height: 38px; font-size: 14px; background-color:' +
        progressButtonBackgroundColor +
        ';background:' +
        progressButtonBackground +
        ';color:' +
        progressButtonColor +
        ';outline: none;" class="block-stepper-action-next">' +
        parameters['next'] +
        '</button>\n';
    }
  }
  html += '</div></div>\n';

  $('#block-item').append(html);
}

function showVerticalStepper(currentDiv, stepTitle, stepCount, parameters) {
  let html =
    '<ol class="block-stepper-vertical" style="margin: 0px; padding: 0px; list-style: outside none none; font-size: 14px; line-height: 20px; color: #2f3941; font-kerning: normal;" id="vertical-item">';
  addVerticalStepper(stepTitle, stepCount, parameters);
  html += '</ol>';
  currentDiv.before(html);
}

function addVerticalStepper(stepTitle, stepCount, parameters) {
  setTimeout(function () {
    let activeClass = '',
      activeCircle =
        'background: rgb(233, 235, 237) none repeat scroll 0% 0%; color: rgb(47, 57, 65);',
      fontWeight = 'font-weight: 400;';
    displayDiv = 'display: none;';
    if (parseInt(stepCount) == 1) {
      activeClass = 'block-stepper-active';
      activeCircle =
        'background: rgb(104, 115, 125) none repeat scroll 0% 0%; color: rgb(255, 255, 255);';
      fontWeight = 'font-weight: 600;';
      displayDiv = '';
    }
    if (
      typeof parameters['hide_title'] != 'undefined' &&
      parameters['hide_title'] == 'true'
    ) {
      stepTitle = '';
    }
    let html = '<li class="' + activeClass + '">\n';
    html +=
      '<div class="block-stepper-title" style="display: flex; -moz-box-align: center; align-items: center; line-height: 1.42857; color: rgb(47, 57, 65); ' +
      fontWeight +
      '">\n';
    html +=
      '<div class="block-stepper-circle" style="display: flex; -moz-box-align: center; align-items: center; -moz-box-pack: center; justify-content: center; transition: background 0.25s ease-in-out 0s, color 0.25s ease-in-out 0s; border-radius: 100%; margin-right: 12px; width: 24px; min-width: 24px; height: 24px; min-height: 24px; line-height: 2; font-size: 12px; ' +
      activeCircle +
      '">\n';
    html += '<span class="stepper-number">' + stepCount + '</span>';
    html +=
      '<svg width="16" height="16" viewBox="0 0 16 16" focusable="false" role="presentation" style="display: none;">\n';
    html +=
      '<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.25" d="M3 9l3 3 7-7"></path>\n';
    html += '</svg>\n';
    html += '</div>\n';
    html +=
      '<div class="block-stepper-title-text" style="line-height: 1.42857; color: rgb(47, 57, 65);">' +
      stepTitle +
      '</div>\n';
    html += '</div>';
    html +=
      '<div class="block-stepper-body" style="border-left: 1px solid rgb(216, 220, 222); border-color: rgb(216, 220, 222); margin: 12px 0px 12px 12px; padding: 0px 20px 24px 24px; min-width: 120px; word-break: break-word;">';
    html +=
      '<div class="block-stepper-body-inner" style="transition: max-height 0.25s ease-in-out 0s;' +
      displayDiv +
      '" id="vertical-item-' +
      stepCount +
      '">';
    html += '<div style="margin-top: 12px;padding: 3px;">';

    if (typeof parameters['previous'] != 'undefined') {
      html +=
        '<button style="display: inline-flex; -moz-box-align: center; align-items: center; -moz-box-pack: center; justify-content: center;  transition: border-color 0.25s ease-in-out 0s,box-shadow 0.1s ease-in-out 0s, background-color 0.25s ease-in-out -moz 0s, color 0.25s ease-in-out 0s; margin: 0px; border: 1px solid transparent; border-radius: 4px; cursor: pointer; overflow: hidden; text-decoration: none; text-overflow: ellipsis; white-space: nowrap; font-family: inherit; font-weight: 400; box-sizing: border-box; user-select: none;  padding: 0px 1.07143em; height: 40px; line-height: 38px; font-size: 14px; background-color:transparent;color: #1f73b7;border-color: #1f73b7;outline: none;" class="block-stepper-action-back">' +
        parameters['previous'] +
        '</button>\n';
    }
    if (typeof parameters['next'] != 'undefined') {
      if (typeof parameters['submit'] != 'undefined') {
        if (parameters['submit'] === 'true') {
          html +=
            '<button style="display: inline-flex; -moz-box-align: center; align-items: center; -moz-box-pack: center; justify-content: center; transition: border-color 0.25s ease-in-out 0s, box-shadow 0.1s ease-in-out 0s, background-color 0.25s ease-in-out 0s, color 0.25s ease-in-out 0s; margin: 0px; margin-left: 12px; border: none; border-radius: 4px; cursor: pointer; overflow: hidden; text-decoration: none; text-overflow: ellipsis; white-space: nowrap; font-family: inherit; font-weight: 400; box-sizing: border-box; user-select: none; padding: 0px 1.07143em; height: 40px; line-height: 38px; font-size: 14px; background-color: ' +
            progressButtonBackgroundColor +
            ';background:' +
            progressButtonBackground +
            ';color:' +
            progressButtonColor +
            ';outline: none;" id="submit_request">' +
            parameters['next'] +
            '</button>\n';
        }
      } else {
        html +=
          '<button style="display: inline-flex; -moz-box-align: center; align-items: center; -moz-box-pack: center; justify-content: center; transition: border-color 0.25s ease-in-out 0s, box-shadow 0.1s ease-in-out 0s, background-color 0.25s ease-in-out 0s, color 0.25s ease-in-out 0s; margin: 0px; margin-left: 12px; border: none; border-radius: 4px; cursor: pointer; overflow: hidden; text-decoration: none; text-overflow: ellipsis; white-space: nowrap; font-family: inherit; font-weight: 400; box-sizing: border-box; user-select: none; padding: 0px 1.07143em; height: 40px; line-height: 38px; font-size: 14px; background-color: ' +
          progressButtonBackgroundColor +
          ';background:' +
          progressButtonBackground +
          ';color:' +
          progressButtonColor +
          ';outline: none;" class="block-stepper-action-next">' +
          parameters['next'] +
          '</button>\n';
      }
    }

    html += '</div></div></div></li>';

    $('#vertical-item').append(html);
  }, 100);
}
// toggle submit (hide show)
function manageSubmit(command, decision) {
  let $formButton = $('form footer');
  let finalDecision = true;
  submitConditions[command] = decision;
  for (let singleCommand of Object.keys(submitConditions)) {
    if (!submitConditions[singleCommand]) {
      finalDecision = false;
    }
  }
  if (finalDecision) {
    $formButton.find("input[type='submit']").show();
    $formButton.find("input[type='submit']").prop('disabled', false);
    $('#submit_request').show();
    $('#submit_request').prop('disabled', false);
  } else {
    $formButton.find("input[type='submit']").hide();
    $formButton.find("input[type='submit']").prop('disabled', true);
    $('#submit_request').hide();
    $('#submit_request').prop('disabled', true);
  }
}

function setTitleData() {
  let newTitleArray = [];
  $('.addToTitle').each(function () {
    newTitleArray.push($(this).val());
  });
  $("input[name='request[subject]']").val(newTitleArray.join(' : '));
}

function hideCheckBox() {
  const storeCheckboxLength = $('input[type="checkbox"]').length;
  if (storeCheckboxLength > 0) {
    for (let i = 0; i < storeCheckboxLength; i++) {
      const storeElement = $('input[type="checkbox"]').parent().children('p')[
        i
      ];
      if (typeof storeElement !== 'undefined') {
        const storeSplitId = storeElement.id.split('_hint')[0];
        if (storeElement.textContent.includes('{{hide')) {
          $(`input[id="${storeSplitId}"]`).parent().attr('hidden', 'true');
        }
      }
    }
  }
}

function displayOrHideSubmit() {
  const storeCheckboxLength = $('input[type="checkbox"]').length;
  if (storeCheckboxLength === 1) {
    if (
      typeof $('input[type="checkbox"]').parent().children('p')[0] !==
      'undefined'
    ) {
      const hasHideSubmitCommand = $('input[type="checkbox"]')
        .parent()
        .find('p')[0].textContent
        ? $('input[type="checkbox"]').parent().find('p')[0].textContent ===
        '{{hide submit}}'
        : false;
      const hasHideSubjectCommand = $('input[type="checkbox"]')
        .parent()
        .find('p')[0].textContent
        ? $('input[type="checkbox"]').parent().find('p')[0].textContent ===
        '{{subject ticket_form_name}}'
        : false;
      const hasSetSubjectCommand = $('input[type="checkbox"]')
        .parent()
        .find('p')[0].textContent
        ? $('input[type="checkbox"]')
          .parent()
          .find('p')[0]
          .textContent.includes('{{subject set')
        : false;
      if (!hasSetSubjectCommand && hasHideSubjectCommand) {
        setSubjectForForm(hasSetSubjectCommand);
      }
      const getCheckboxElement = $('input[type="checkbox"]')[0];
      const getCheckboxId = getCheckboxElement.id;
      const isCheckBoxDisabled = $(`#${getCheckboxId}`).is(':disabled');
      if (!isCheckBoxDisabled && hasHideSubmitCommand) {
        return $('input[type="submit"]').attr('hidden', true);
      } else {
        $('input[type="submit"]').attr('hidden', false);
      }
    } else {
      $('input[type="submit"]').attr('hidden', false);
    }
  } else if (storeCheckboxLength > 1) {
    let checkForTrue = [];
    for (let i = 0; i < storeCheckboxLength; i++) {
      const pTagInCheckbox =
        $('input[type="checkbox"]').parent().find('p').length > 0
          ? $('input[type="checkbox"]').parent().find('p')[i]
          : false;

      let hasHideSubmitCommand = false;
      let hasHideSubjectCommand = false;

      if (typeof pTagInCheckbox !== 'undefined' && pTagInCheckbox !== false) {
        const storeSplitId = pTagInCheckbox.id.split('_hint')[0];
        hasHideSubmitCommand = pTagInCheckbox.textContent === '{{hide submit}}';
        hasHideSubjectCommand =
          pTagInCheckbox.textContent === '{{subject ticket_form_name}}';
        hasSetSubjectCommand =
          pTagInCheckbox.textContent.includes('{{subject set');

        if (!hasSetSubjectCommand && hasHideSubjectCommand) {
          setSubjectForForm(hasSetSubjectCommand);
        }

        const isCheckBoxDisabled = $(`input[id="${storeSplitId}"]`).is(
          ':disabled'
        );
        if (!isCheckBoxDisabled && hasHideSubmitCommand) {
          checkForTrue.push(true);
        }
      }
    }
    if (checkForTrue.length > 0) {
      return $('input[type="submit"]').attr('hidden', true);
    } else {
      $('input[type="submit"]').attr('hidden', false);
    }
  } else {
    $('input[type="submit"]').attr('hidden', false);
  }
}